30.10.08

Static Constructors

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Sample Code

public class Bus
{
// Static constructor:
static Bus()
{
System.Console.WriteLine("The static constructor invoked.");
}
public static void Drive()
{
System.Console.WriteLine("The Drive method invoked.");
}
}
class TestBus
{
static void Main()
{
Bus.Drive();
}
}

Sample Try - Catch in SQL 2005

begin tran Tran_DeleteAll
begin try
--Sample code
end try

begin catch
set @EMessage = @ProcedureName + ':' + ERROR_MESSAGE()
execute dbo.SPname @arg1,@arg2, 1, NULL, NULL, 2
rollback tran Tran_DeleteAll
end catch

Static Classes and Static Class Members

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static classes can be used when there is no data or behavior in the class that depends on object identity.
  • Static Classes

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
The main features of a static class are:

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Sample Code

static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
}

  • Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

Sample code

public class Automobile
{
public static int NumberOfWheels = 4;
public static int SizeOfGasTank
{
get
{
return 15;
}
}
public static void Drive() { }
public static event EventType RunOutOfGas;
}
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

Automobile.Drive();
int i = Automobile.NumberOfWheels;

Sample code

public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}


7.10.08

Property in C#:

Property ? it is a special method that can return a current object?s state or set it. Simple syntax of properties can see in the following example:
public int Old
{
get {return m_old;}
set {m_old = value;}
}
public string Name
{
get {return m_name;}
}
Here are two types of properties. A first one can set or get field of class named m_old, and the second is read only. That?s mean it can only get current object?s state.
The significance of these properties is its usability. These properties need not be called with any function names like objectname.get or objectname.set etc., But they can be directly assigned the values or retrieve the values.
Static Properties
C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also.
The following program shows a class with a static property.
using System;
class MyClass
{
private static int x;
public static int X
{
get{return x;}
set{x = value;}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.
Properties & Inheritance
The properties of a Base class can be inherited to a Derived class.
using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{Console.Write("Base SET");}
}
}
class Derived : Base{}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}
The above program is very straightforward. The inheritance of properties is just like inheritance any other member.
Properties & Polymorphism
A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.
using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}
Abstract Properties
A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.
If the abstract class contains only set accessor, we can implement only set in the derived class.
The following program shows an abstract property in action.
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}
The properties are an important features added in language level inside C#. They are very useful in GUI programming. Remember that the compiler actually generates the appropriate getter and setter methods when it parses the C# property syntax.

Output Parameters in Methods:

The return values in any function will be enough for any one if only one value is needed. But in case a function is required to return more than one value, then output parameters are the norm. This is not supported in C++ though it can be achieved by using some programming tricks. In C# the output parameter is declared with the keyword out before the data type. A typical example is as follows.

public void CalculateBirthYear(ref int year, out int birthyear)
{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}

Strictly speaking there is no difference between ref and out parameters.
The only difference is that the ref input parameters need an input value and the out parameters dont. Ref parameter Should be initilized before call. Out need not to initilized before call.
Ref paramenter is nothing but in & out parameter.
Out is only out parameter.
There is no performance issue occured.
A ref or out argument must be an lvalue.ie, you need to pass the same signature.
The casting is not allowed for both when you pass thevalues to ref/out.

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.