30.9.08

Tips on SQL

  • To knowwhich database running on the Server : "exec sp_who2"

ProcessID - get the processId from exec sp_who2

  • How to Kill the database running on the Server : Kill ProcessID

  • Use Order by but without culumn name
    -> SELECT id,name FROM tablename order by 1 asc / -> SELECT id,name FROM tablename order by 1 desc
  • HAVING clause can also be used without aggregates

->SELECT job FROM works_on GROUP BY job HAVING job LIKE 'M%'

-> SELECT SERVERPROPERTY('productversion'),SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition')

  • Get accurate count of number of records in tha table

-> SELECT rows FROM sysindexes WHERE id=OBJECT_ID(tablename) AND indid<2

  • To Rename DB, Table, Column

-> sp_renamedb 'oldDBname', 'newDBname'

before that we have to change the user mode using

-> sp_dboption DBname,'single user', true

after name change 'single user' as fasle

-> sp_rename 'oldTablename', 'newTablename' for Table anme change

->sp_rename 'tablename.column name', Name change', COLUMN


  • Find Columns in table
<->Select Column_Name
From Information_Schema.Columns Where Table_Name = 'WBI_sitemap'And Column_Name <> 'RowVersion' Order By Ordinal_Position



  • * To get Scalar Value to the variable

DECLARE @sql nvarchar(100),@i INT
SET @sql='select @i= count(*) from TABLE_NAME'
EXEC SP_EXECUTESQL @sql, @params = N'@i INT OUTPUT', @i = @i OUTPUT



  • * To Replace some Char in String

REPLACE(@string,'char need to find','char need to change')



  • * To identify the most used indexes in your DB run the following query.

This will help you to identify whether or not your indexes are useful and used.
declare @dbid int
--To get Datbase ID
set @dbid = db_id()
select
db_name(d.database_id) database_name
,object_name(d.object_id) object_name
,s.name index_name,
c.index_columns
,d.*
from sys.dm_db_index_usage_stats d
inner join sys.indexes s
on d.object_id = s.object_id
and d.index_id = s.index_id
left outer join
(select distinct object_id, index_id,
stuff((SELECT ','+col_name(object_id,column_id ) as 'data()' FROM sys.index_columns t2 where t1.object_id =t2.object_id and t1.index_id = t2.index_id FOR XML PATH ('')),1,1,'')
as 'index_columns' FROM sys.index_columns t1 ) c on
c.index_id = s.index_id and c.object_id = s.object_id
where database_id = @dbid
and s.type_desc = 'NONCLUSTERED'
and objectproperty(d.object_id, 'IsIndexable') = 1
order by
(user_seeks+user_scans+user_lookups+system_seeks+system_scans+system_lookups) desc


26.9.08

Generic in C#.NET

Introduction:
Parametric Polymorphism is a well-established programming language feature. Generics offers this feature to C#.The best way to understand generics is to study some C# code that would benefit from generics. The code stated below is about a simple Stack class with two methods: Push () and Pop ().
First, without using generics example you can get a clear idea about two issues:
a) Boxing and unboxing overhead and
b) No strong type information at compile type.
After that the same Stack class with the use of generics explains how these two issues are solved.
Example Code
Code without using generics:
public class Stack
{
object[] store;
int size;
public void Push(object x)
{...}
public object Pop()
{...}
}
Boxing and unboxing overhead:.
You can push a value of any type onto a stack. To retrieve, the result of the Pop method must be explicitly cast back. For example if an integer passed to the Push method, it is automatically boxed. While retrieving, it must be unboxed with an explicit type cast.
Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop(); //unboxing with explicit int casting
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.
No strong Type information at Compile Time
Another issue with the Stack class:
It is not possible to enforce the kind of data placed on a stack.
For example, a string can be pushed on a stack and then accidentally cast to the wrong type like integer after it is retrieved:
Stack stack = new Stack();
stack.Push("SomeName");//pushing the string
int i = (int)stack.Pop();//run-time exception will be thrown at this point
The above code is technically correct and you will not get any compile time error. The problem does not become visible until the code is executed; at that point an InvalidCastException is thrown.
CODE WITH GENERICS:
In C# with generics, you declare class Stack {...}, where T is the type parameter. Within class Stack you can use T as if it were a type. You can create a Stack as Integer by declaring
Simply your type arguments get substituted for the type parameter. All of the Ts become ints or Customers, you don't have to downcast, and there is strong type checking everywhere.
public class Stack OpenTag(T)CloseTag
{
// items are of type T, which is kown when you create the object
T[] items;
int count;
public void Push(T item)
{...}
//type of method pop will be decided when you creat the object
public T Pop()
{...}
}
In the following example, int is given as the type argument for T:
Stack OpenTag Int CloseTag stackobj = new Stack OpenTag Int CloseTag ();
stackobj .Push(3);
int i = stackobj .Pop();
The Stack type is called a constructed type. In the Stack type, every occurrence of T is replaced with the type argument int. The Push and Pop methods of a Stack operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when they are retrieved.
You can use parameterization not only for classes but also for interfaces, structs, methods and delegates.
For Interfaces
interface IComparable OpenTag T CloseTag
For structs
struct HashBucket OpenTag T CloseTag
For methods
static void Reverse OpenTag T CloseTag (T[] arr)
For delegates
delegate void Action OpenTag T CloseTag (T arg)
Inside the CLR
When you compile StackOpenTag T CloseTag , or any other generic type, it compiles down to IL and metadata just like any normal type. The IL and metadata contains additional information that knows there's a type parameter. This means you have the type information at compile time.
Implementation of parametric polymorphism can be done in two ways
1. Code Specialization: Specializing the code for each instantiation
2. Code sharing: Generating common code for all instantiations.
C# implementation of generics uses both code specialization and code sharing as explained below.
At runtime, when your application makes its first reference to StackOpenTag T CloseTag , the system looks to see if anyone already asked for Stack calss . If not, it feeds into the JIT the IL and metadata for Stack and the type argument int.
The .NET Common Language Runtime creates a specialized copy of the native code for each generic type instantiation with a value type, but shares a single copy of the native code for all reference types (since, at the native code level, references are just pointers with the same representation).
In other words, for instantiations those are value types:
such as Stack OpenTag int CloseTag ,
Stack OpenTag Long CloseTag ,
Stack OpenTag Double CloseTag ,
Stack OpenTag Float CloseTag,
CLR creates a unique copy of the executable native code.above all gets unique code
Stack OpenTag int CloseTag uses 32 bits and Stack OpenTag Long CloseTag uses 64 bits. While reference types, Stack OpenTag Dog CloseTag is different from Stack OpenTag Cat CloseTag , but they actually share all the same method code and both are 32-bit pointers.
This code sharing avoids code bloat and gives better performance.
Advantages Of Generic:
Generics can make the C# code more efficient, type-safe and maintainable.
Efficiency: Instantiations of parameterized classes are loaded dynamically and the code for their methods is generated on demand [Just in Time].Where ever possible, compiled code and data representations are shared between different instantiations.Due to type specialization, the implementation never needs to box values of primitive types.
Safety: Strong type checking at compile time, hence more bugs caught at compile time itself.
Maintainability: Maintainability is achieved with fewer explicit conversions between data types and code with generics improves clarity and expressively.

10.9.08

Bind Data in datagrid in C#.Net

//Connection
SqlConnection sqlConn = new SqlConnection(@"Data Source=LCHNS1403\SQLEXPRESS;Initial Catalog=ODS_Tracking718;uid=sa;pwd=Windows123;");
//Command
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlConn;
//if incase of stored procedure
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "SpName";
sqlCmd.Parameters.Add("parm1");
sqlCmd.Parameters.Add("parm2");
//SQl DataAdapter
SqlDataAdapter sqlDadp = new SqlDataAdapter();
sqlDadp.SelectCommand = sqlCmd;
DataTable sqlDT = new DataTable();
sqlDadp.Fill(sqlDT);
//Grid Bind
datagridname.DataSource = sqlDt;
datagridname.DataBind();
}

7.9.08

Partial Classes with C#.NET

Partial Classes:
It is possible to split definition of classes, interfaces and structures over more than one files.some Features of partial classes are
  • More than one developer can simultaneously write the code for the class.
  • You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.

Things that you should be careful about when writing code for partial classes:

  • All the partial definitions must preceede with the key word "Partial".
  • All the partial types meant to be the part of same type must be defined within a same assembly and module.
  • Method signatures (retrn type, name of the method, and parameters) must be unique for the agregated typed (which was defined partially). i.e. you can write default constructor in two separate definitions for a particular partial class.

Example:

File 1:
public partial class myPartialClass
{
public myPartialClass(string pString)
{
Console.WriteLine("I am in a partial class in Partial.cs. The parmeter passed is: " + pString);
}
public void doSomethingElse()
{
Console.WriteLine(" I am in Partial.cs ");
}
}
File 2:
public partial class myPartialClass
{
public myPartialClass()
{
Console.WriteLine(" I am in a partial class in Program.cs");t
}
public void doSomething()
{
Console.WriteLine(" I am in Progam.cs ");
}
}
class TestProgram
{
static void Main(string[] args)
{
/// see the classe are partial but the object is complete.
myPartialClass myCompleteObject = new myPartialClass();
myCompleteObject.doSomething();
myCompleteObject.doSomethingElse();
Console.ReadLine();
}
}

6.9.08

Method Hiding in C#.NET

  • Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;

namespace Polymorphism

{

class A

{

public void Foo()

{ Console.WriteLine("A::Foo()"); }

}

class B : A

{

public new void Foo() { Console.WriteLine("B::Foo()"); }

}

class Test

{

static void Main(string[] args)

{

A a = new A();

B b = new B

a.Foo(); // output --> "A::Foo()"

b.Foo(); // output --> "B::Foo()"

a = new B();

a.Foo(); // output --> "A::Foo()"

}

}

}

Conclusion

  • Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
  • Know what your doing and look out for compiler warnings.

Virtual and Overridden Methods in C#.NET

  • Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System; [two function with the same name inside a class]

namespace Polymorphism

{

class A

{

public virtual void Foo()

{ Console.WriteLine("A::Foo()"); }

}

class B : A

{

public override void Foo()

{ Console.WriteLine("B::Foo()"); }

}

class Test

{

static void Main(string[] args)

{

A a= new A();

B b= new B();

a.Foo(); // output --> "A::Foo()"

b.Foo(); // output --> "B::Foo()"

a = new B();

a.Foo(); // output --> "B::Foo()"

}

}

}

Sample Code for Delegate in C#.net


Delegate
To encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
A delegate can be defined as a type safe function pointer. It encapsulates the memory address of a function in your code. Whenever you create or use an event in code, you are using a delegate. When the event is thrown, the framework examines the delegate behind the event and then calls the function that the delegate points to. As we will see later, delegates can be combined to form groups of functions that can be called together.

Example:1
using System;
namespace BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}

Example:2
public class Comp
{
public class string str = null;
public string s = null;
}

//Declare Delegate
public delegate void DelegatedName(Comp ClsObj);

//Function which uses delegate
public static void FunctionName(DelegatedName DelObj)
{
//Class Comp was in the Delegate invocation
Comp ClsObj= obj.func();
}
/****************************/
Multicasting
Being able to point to member functions is nice, but there are more tricks you can do with delegates. In C#, delegates are multicast, which means that they can point to more than one function at a time (that is, they're based off the System.MulticastDelegate type). A multicast delegate maintains a list of functions that will all be called when the delegate is invoked. We can add back in the logging function from the first example, and call both delegates. Here's what the code looks like:

Example:3
using System;
using System.IO;
namespace SimpleMulticastDelegate
{
// Delegate Specification
public class MyClass
{
// Declare a delegate that takes a single string and has no return type.
public delegate void LogHandler(string message);
// The use of the delegate is just like calling a function directly though we need to add a check to see if the delegate is (that is, not pointing to a function) before calling the function.
public void Process(LogHandler logHandler)
{
if (logHandler != null)
{
logHandler("Process() begin");
}
if (logHandler != null)
{
logHandler ("Process() end");
}
}
}
// The FileLogger class merely encapsulates the file I/O
public class FileLogger
{
FileStream fileStream;
StreamWriter streamWriter;
// Constructor
public FileLogger(string filename)
{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
// Member Function which is used in the Delegate
public void Logger(string s)
{
streamWriter.WriteLine(s);
}
public void Close()
{
streamWriter.Close();
fileStream.Close();
}
}
// Test Application which calls both Delegates
public class TestApplication
{
// Static Function which is used in the Delegate
static void Logger(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
FileLogger fl = new FileLogger("process.log");
MyClass myClass = new MyClass();
// Crate an instance of the delegates, pointing to the Logger() function defined in the TestApplication class then to member function on the fl instance of a FileLogger.

MyClass.LogHandler myLogger = null;
myLogger += new MyClass.LogHandler(Logger);
myLogger += new MyClass.LogHandler(fl.Logger);
myClass.Process(myLogger);
fl.Close();
}
}
}
Compile an test:
# csc SimpleDelegate4.cs
# SimpleDelegate4.exe
Process() begin
Process() end
# cat process.log
Process() begin
Process() end

5.9.08

Sample code for Garbage Collector [GC] in C#.Net

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
public class Base
{
~Base()
{
Console.WriteLine(“Base Finalizer called”);
}
}

public class Derived : Base
{
~Derived()
{
Console.WriteLine(“Derived Finalizer called”);
}

public void Suppress()
{
GC.SuppressFinalize(this);
}
}

class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.Suppress();
Console.ReadLine();
}
}
}

Abstract & Interface with in C#.Net

Introduction
  • Interfaces
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. An interface represents a contract, and a class that implements an interface must implement every aspect of that interface exactly as it is defined.
Example
interface IPerson
{
void Eat();
void Sleep();
int Weight
{
set;
get;
}
}
In order to use this interface, you must declare your class in the same way that you declare a class inheriting from any other object.
Example
public class Man:IPerson
{
int iWeight;
public Man()
{}
public void Eat()
{
MessageBox.Show("Man:Eat");
}
public void Sleep()
{
MessageBox.Show("Man:Sleep");
}
public int Weight
{
set
{
iWeight = value;
}
get
{
return iWeight;
}
}
static void Main()
{
Man i = new Man();
i.Eat();
i.Sleep();
}
}
You get the following result when you run the above code.
Man:Eat
Man:Sleep
It is important to note here that an interface is very different from a base class. An interface is implemented, not extended.
1.A class can implement multiple interfaces.
2.An interface cannot contain data declarations but you can declare properties.
3.All method declarations in an interface are public.
4.There can be no implementation in an interface.
5.The class implementing the interface must provide implementation code.
6.An interface can be derived from another interface
  • Abstract Classes

An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes.

When you have a class that contains methods that have no implementation (i.e. abstract methods), the class is said to be abstract as well. An abstract method is simply a shell or place-marker for a method that will be defined later in a derived class. The intention of abstract methods is to force every derivation of the class to implement those methods. If a derived class does not implement an abstract method, then that class must also be declared as abstract.

abstract public class Person

{

abstract public void Eat();

public void Sleep()

{MessageBox.Show("Person:Sleep");}

abstract public int Weight

{

set;

get;

}

}

You can inherit the abstract class just like any other class.

public class Man:Person

{

int iWeight;

public Man()

{}

override public void Eat()

{MessageBox.Show("Man:Eat"); }

override public int Weight

{

set

{

iWeight = value;

}

get

{

return iWeight;

}

}

static void Main()

{

Man i = new Man();

i.Eat();

i.Sleep();

}

}

You get the following result when you execute the above code.

Man:Eat

Person:Sleep

So why would you declare a class abstract? It’s actually a very powerful class hierarchy design tool since you can provide the structure for something that is not very specific —just like our Person class. You will never create an Person object; but you will create Man and Woman objects. The other advantage is that you are moving the code to where it actually belongs. This helps you locate program logic problems. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. If additional functionality is needed in derived classes, it can be added to the base class without breaking code.

In the above example, an abstract class is declared with one implemented method, one unimplemented method and one unimplemented property. A class inheriting from this class would have to implement the Eat method and Weight property

When implementing an abstract class, you must implement each abstract method in that class, and each implemented method must receive the same number and type of arguments, and have the same return value, as the method specified in the abstract class.

Recommendations on using Abstract Classes and Interfaces:

1. If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

2. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

3. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

4. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

  • Abstract class vs. interfaces

Abstract class Interface May or may not have abstract methods. Can only have abstract methods (Implicitly abstract) but abstract keyword is not allowed. Methods can have access modifiers. No access modifier is allowed, implicitly public. Can have fields. Not intended to define fields. Can be instantiated via sub-class. Can be instantiated via implementing class. Can extend a Single class, implement one or more interfaces. Cannot extend a class, Can extend single or multiple interfaces. Abstract classes form part of the inheritance scheme Interfaces do not. We can use the same interface in two projects that are not related in terms of inheritance. For example an interface IWheel can be implemented in a Car project and also a Bicycle project. Can have constructor. Can't have constructor. A class, by comparison, can only extend ("implementation inheritance") one other class Interfaces provide a form of multiple inheritance ("interface inheritance"), because you can implement multiple interfaces. An abstract class can have static methods, protected parts, and a partial implementation. Interfaces are limited to public methods and constants with no implementation allowed.

2.9.08

Acess Modifiers in C#.NET

Access modifiers are keywords used to specify the declared accessibility of a member or a type

  • public: Access is not restricted.The item is visible to any other code.
  • protected: Access is limited to the containing class or types derived from the containing class.The item is visible only to any derived type.
  • Internal: Access is limited to the current assembly.The item is visible only within its containing assembly.
  • protected internal: Access is limited to the current assembly or types derived from the containing class.The item is visible to any code within its containing assembly and also to any code inside a derived type.
  • private: Access is limited to the containing type.The item is visible only inside the type to which it belongs.

Method Access Modifiers

If no modifier is specified, the method is given private access

  • public indicates the method is freely accessible inside and outside of the class in which it is defined.
  • internal means the method is only accessible to types defined in the same assembly.
  • protected means the method is accessible in the type in which it is defined, and in derived types of that type. This is used to give derived classes access to the methods in their base class.
  • protected internal means the method is accessible to types defined in the same assembly or to types in a derived assembly.
  • private methods are only accessible in the class in which they are defined.
  • virtual methods can be overriden by a derived class using the override keyword.
  • abstract methods must be overriden in a derived class. If any method of a class is abstract, the entire class must be declared as abstract.
  • sealed methods are methods that override an inherited virtual method having the same signature. When a method is sealed, it cannot be overriden in a derived class.

Class Modifiers

The class is one of the two basic encapsulation constructs in C# (the other being the struct). Every executable statement must be placed inside a class or struct. Classes define reference types that are the basic building blocks of C# programs, and they are the architectural blueprint for the "objects" in OOP.

  • abstract: An instance of the class cannot be created.Usually this means the class is intended to serve as a base class.
  • sealed: The class cannot serve as a base class for another class (it can't be derived from). A class cannot be both abstract and sealed.
  • internal: The class is only accessible from other classes in the same assembly. This is the default access for non-nested types. If no modifier is specified, the class has internal access.
  • new: Used only with nested classes. "New" indicates that the class hides an inherited member of the same name.
  • private: A nested class that can only be accessed inside the class in which it is defined.
  • public: Instances of this class are available to any class that wants to access it.