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.

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.

30.8.08

Creating StrongName and develop Com / Assembly in C#.Net

  1. Create a new Project Class Library

  2. Open .net command prompt andGo to the folder contanig DLL ie. navigate to the project’s folder eg: E:\Test Application\AssenblyLibry\AssenblyLibry\bin\Debug>

  3. Type sn -k keyname.snk, This will create keyname.snk file in that folder.

  4. A Properties folder with an AssemblyInfo.cs file was created right click on the folder and open properties. The default should be ‘Class Library’ / Open the assemblyinfo.cs file of project, Type file path in this tag [assembly:AssemblyKeyFile@"E:\hemant\practice\HP\bin\Debug\HP.snk")] Build application, finally your strong name created for your DLL.

  5. Goto the signing tab and check Sign the assembly, browse and point it to the ‘key.snk’ file.

  6. open the AssemblyInfo.cs , add [assembly: AssemblyKeyFileAttribute(@”..\..\key.snk”)]

  7. in the AssemblyInfo.cs set [assembly: ComVisible(true)], now copy the assembly GUID that was auto created with the file

  8. put [System.Runtime.InteropServices.GuidAttribute(”paste guid here”)] in your main class file in between the Namespace and Class.

  9. Build the solution.

  10. Register the Assembly. [”regasm xxxx.dll /tlb:xxxx.tlb /codebase xxxx” at the command prompt, while in the directory that contains xxxx.dll]

  11. The assembly is now accessible using COM
    Steps for Installing in GAC
  • After giving strong name in .net command prompt type gacutil in DLL path this will install file in assembly.
  • Copy the DLL file C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 folder
  • You can add references to another project using .net tab.




























Exceptions In C#.NET

In C# Exception / Error can be classified into
  • compile-time errors
  • runtime errors

Compile-time errors are errors that can be found during compilation process of source code. Most of them are syntax errors. Runtime errors happen when program is running. It is very difficult to find and debug the run-time errors. These errors also called exceptions.Exception generates an exception call at runtime. Exceptions in C# can be called using two methods:

  • Using the throw operator. It call the manage code anyway and process an exception.
  • If using the operators goes awry, it can generate an exception.

All Exception are inherited from base class named System.Exception.These class process many kind of exception:

  • out of memory exception,
  • stack overflow exception,
  • null reference exception,
  • index out of range exception,
  • invalid cast exception,
  • arithmetic exception etc.

28.8.08

From command line creating exe, dll ....

  • Compiles File.cs producing File.exe: csc File.cs
  • Compiles File.cs producing File.dll: csc /target:library File.cs
  • Compiles File.cs and creates My.exe: csc /out:My.exe File.cs
  • Compiles all of the C# files in the current directory, with optimizations on and defines the DEBUG symbol. The output is File2.exe: csc /define:DEBUG /optimize /out:File2.exe *.cs
  • Compiles all of the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed:
    csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs
  • Compiles all of the C# files in the current directory to Something.xyz (a DLL): csc /target:library /out:Something.xyz *.cs

Creating Assembly in VS C#.NET

Create an Empty Class Library Project
Select File->New->Project->Visual C# Projects->Class Library. Select your project name and appropriate directory using Browse button and click OK. See Figure 1.




















Figure 1.
Project and Its files
The Solution Explorer adds two C# classes to your project. First is AssemblyInfo.cs and second is Class1.cs. We don't care about AssemblyInfo. We will be concentrating on Class1.cs. See Figure 2.



























Figure 2
The mcMath Namespace
When you double click on Class1.cs, you see a namespace mcMath. We will be referencing this namespace in our clients to access this class library.
using System;


namespace mcMath
{
///
/// Summary description for Class1.
///

public class Class1
{
public Class1()
{
// // TODO: Add constructor logic here //
}
}
}
Now build this project to make sure every thing is going OK. After building this project, you will see mcMath.dll in your project's bin/debug directory.
Adding Methods
Open ClassView from your View menu. Right now it displays only Class1 with no methods and properties. Lets add one method and one property. See Figure 3.
















Figure 3.
Build the DLL
Now build the DLL and see bin\debug directory of your project. You will see your DLL. Piece of cake? Huh? :).
Building a Client Application
Calling methods and properties of a DLL from a C# client is also an easy task. Just follow these few simple steps and see how easy is to create and use a DLL in C#.
By adding the Dll to the reference of the project to get all the features
Call mcMath Namespace, Create Object of mcMathComp and call its methods and properties.
You are only one step away to call methods and properties of your component. You follow these steps:
  1. Use namespace
    Add using mcMath in the beginning for your project. using mcMath;
  2. Create an Object of mcMathComp. mcMathComp cls = new mcMathComp();
  3. Call Methods and Properties

Now you can call the mcMathComp class method and properties as you can see I call Add method and return result in lRes and print out result on the console.
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;

Console.WriteLine(lRes.ToString());

Entire Project

using System;
using mcMath;
namespace mcClient
{
///


/// Summary description for Class1.
///

class Class1
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main(string[] args)
{
mcMathComp cls = new mcMathComp();
long lRes = cls.Add( 23, 40 );
cls.Extra = false;
Console.WriteLine(lRes.ToString());
}
}
}

Difference Between Namespace and Assembly in C# .Net

Assembly will contain Namespaces, Classes, Data types it’s a small unit of code for deployment. Assembly defines the name of the .dll file.Namespace is used in order to avoid conflict of user defined classes
Namespace:
1) it is a Collection of names wherein each name is Unique.
2) They form the logical boundary for a Group of classes.
3) Namespace must be specified in Project-Properties.
Assembly:
1) It is an Output Unit.
2) It is a unit of Deployment & a unit of versioning.
3) Assemblies contain MSIL code.
4) Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).
7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

Keyboard Shortcuts for Visual c# 2005

The following keyboard shortcuts I find invaluable. It's amazing how many people still use the mouse to do everything.
Document navigation :
Ctrl+Tab Switch documents
Ctrl+Shift+Tab Reverse switch documents
Ctrl+kk Drop a bookmark
Ctrl+kn Itterate through bookmarks
F7 Switch from HTML to Codebehind view
Ctrl+- Navigate backward through last cursor locations
Code Navigation :
F12 Goto Definition
Ctrl+] Jump to matching brace
Editing :
Ctrl+c Copy a whole line
Ctrl+v When a whole line in the clipboard (as above) this will instet a whole copied line.. handy for quick duplication
Ctrl+u Change to lower case
Ctrl+Shift+U Change to UPPER case
Macros :
Ctrl+Shift+R Record a quick Macro
Ctrl+Shift+P Run the quick Macro you just recordedComments
Ctrl+kc Comment out selected lines
Ctrl+ku Uncomment selected lines
Formatting
Ctrl+kd Autoformat selected lines

20.8.08

Get VersionInfo

Steps :
*******
  • In assemblyinfo.cs
    [assembly: AssemblyVersion("x.x.x.x")]
GetVersion Info from any .cs:
**************************
  • System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString(); --Version
  • System.Reflection.Assembly.GetEntryAssembly().GetName().Name.ToUpper(); --Name

6.8.08

State management in ASP.NET

  • Define state management in ASP.NET

Answer - State management is implemented in order to retain information about the user requests. Web pages are stateless. Each request creates new page without retaining any previous information about the user requests. ASP.NET supports several State management techniques to maintain state information.

State management in ASP.NET can be classified into

Client-side state management & Server-side state management

  • Define each mechanism of Client-side state management and Server-side state management.

Client-side state management

This maintains information on the client's machine using Cookies, View State, and Query Strings.

Cookies.

A cookie is a small text file on the client machine either in the client's file system or memory of client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be disabled on the browser. Thus, you can't rely on cookies for state management.

View State

Each page and each control on the page has View State property. This property allows automatic retention of page and controls state between each trip to server. This means control value is maintained between page postbacks. Viewstate is implemented using _VIEWSTATE, a hidden form field which gets created automatically on each page. You can't transmit data to other page using view state.

View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive.

View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.// Add item to ViewStateViewState["myviewstate"] = myValue;//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);

Advantages:

Simple for page level data

Encrypted

Can be set at the control level

Disadvantages:

Overhead in encoding View State values.

Makes a page heavy

Querystring

Querystring can maintain limited state information. Data can be passed from one page to another with the URL but you can send limited size of data with the URL. Most browsers allow a limit of 255 characters on URL length.

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.

Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes:string productid;productid=Request.Params["productid"];

Advantages:

Simple to Implement

Disadvantages:

Human Readable

Client browser limit on URL length

Cross paging functionality makes it redundant

Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.

For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server-side state management

As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage of sessions object for state management can create load on server causing performance degradation

Application State

The data stored in an application object can be shared by all the sessions of the application. The application object stores data in the key value pair.

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.

In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea

Application.Lock();

Application["mydata"]="mydata";

Application.UnLock();

Session State

Session state stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application's configuration settings. By default, SessionID values are stored in a cookie.

Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.

Configuration information: cookieless = <"true" "false"> timeout = sqlconnectionstring= server = port =

Mode:This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:This identifies the database connection string that names the database used for mode SQLServer.

Server:In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

In process mode:

In process mode (in-memory)- State information is stored in memory of web server.This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server

Advantages:

Fastest mode

Simple configuration

Disadvantages:

Session data will be lost if the worker process or application domain recycles

Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):

session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line. This mode is ideal for scalable and highly available applications.

Advantages:

Supports web farm and web garden configuration

Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state

Disadvantages:

Out-of-process mode provides slower access compared to In processRequires serializing data

Database

Database can be used to store large state information. Database support is used in combination with cookies or session state.

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.

Session state management in ASP.NET

  • Define Session, SessionId and Session State in ASP.NET.

Answer - A session is the duration of connectivity between a client and a server application. SessionId is used to identify request from the browser. By default, value of SessionId is stored in a cookie. You can configure the application to store SessionId in the URL for a "cookieless" session.

  • What is Session Identifier?

Answer - Session Identifier is used to identify session. It has SessionID property. When a page is requested, browser sends a cookie with a session identifier. This identifier is used by the web server to determine if it belongs to an existing session. If not, a Session ID (120 - bit string) is generated by the web server and sent along with the response.

  • Advantages and disadvantages of using Session State

Advantages of using session state:

It is easy to implement.

It ensures data durability, since session state retains data even if ASP.NET work process restarts as data in Session State is stored in other process space.

It works in the multi-process configuration, thus ensures platform scalability.

Disadvantages of using session state:

Since data in session state is stored in server memory, it is not advisable to use session state when working with large sum of data. Session state variable stays in memory until you destroy it, so too many variables in the memory effect performance.

  • What are the Session State Modes? Define each Session State mode supported by ASP.NET

InProc Mode

This mode stores the session data in the ASP.NET worker process.This is the fastest among all of the storage modes.This mode effects performance if the amount of data to be stored is large.If ASP.NET worker process recycles or application domain restarts, the session state will be lost.

State Server mode

In this mode, the session state is serialized and stored in memory in a separate process.State Server can be maintained on a different system. State Server mode involves overhead since it requires serialization and de-serialization of objects. State Server mode is slower than InProc mode as this stores data in an external process.

SQL Server Mode

In this storage mode, the Session data is serialized and stored in a database table in the SQL Server database. This is reliable and secures storage of a session state. This mode can be used in the web farms. It involves overhead in serialization and de-serialization of the objects.SQL Server is more secure than the InProc or the State server mode.


Globalization and Localization in ASP.NET

  • What is Globalization and Localization in ASP.NET?

Answer - Localization is the process of adapting a software application for a specific locale. Globalization is the process of identifying the localizable resources of the application. You can provide support for Localization and Globalization to the application using System.Globalization, System.Resources and System.Threading namespaces.

The developer can define culture specific information using the System.Globalization namespace. The System.Resources namespace contains ResourceManager class that allows access to resources either from the main assembly or from the Satellite Assemblies. The System.Threading namespace supports for multithreaded programming.

A web form has two culture values, Culture and UICulture. Culture value is used for date and number formatting and UICulture values are used to determine culture specific resources.

You can set culture and UICulture values in the application as follows.

Using element of Web.Config.

Using @Page directive in the Page.

In Code-Behind Page

e.g.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ("en-GB");

Thread.CurrentThread.CurrentUICulture=new CultureInfo("en-GB");

  • What are the Globalization approaches possible in ASP.NET?

Answer - You can follow many approaches to have globalized application.

You can create separate web application for each culture.

You can create an application that can detect the user’s culture and adjusts output at run time using format specifiers and other tools.

You can store culture-dependent strings in resource files that are compiled into satellite assemblies.

  • Implementing ASP.NET Globalization

Answer - Create resource files and compile them into a binary resource file.

Create satellite assembly for each of the resource file for each culture.

Store them in separate folders for easy access and replacement.

Read the resources from the satellite assembly that is stored in different folders based on the locale and culture.

  • Define Resource Files and Satellite Assemblies

Answer-Resource Files: A resource file contains non-executable data that are used by the application and deployed along with it. Bitmaps, Icons etc are the examples of resource files. In ASP.NET, resource files are used to make application to support multiple cultures. You can create resource files each of them correspond to specific locale or culture of the application. You can use resgen utility to compile resource file into an assembly. You can create a satellite assembly from a compiled resource file using the AL utility provided with Microsoft .NET SDK

Advantages of resource files are as follows.

It supports Globalization features in ASP.NET.

You can have culture based information separate from the content and logic of the application.

You can change resource content without effecting application's code.

Satellite Assemblies

Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture-specific resources in a binary format. They store compiled localized application resources. They can be created using the AL utility and can be deployed even after deployment of the application. Satellite Assemblies encapsulate resources into binary format and thus make resources lighter and consume lesser space on the disk.

Note: Resource-only assemblies can contain any resource, such as images and text. Satellite assemblies contain only culture-specific resources

ASP.NET Caching Technique

Define Caching in ASP.NET
  • Answer - Caching technique allows to store/cache page output or application data on the client. The cached information is used to serve subsequent requests that avoid the overhead of recreating the same information. This enhances performance when same information is requested many times by the user.

Advantages of Caching

  • Answer - It increases performance of the application by serving user with cached output. It decreases server round trips for fetching data from database by persisting data in the memory.It greatly reduces overhead from server resources.

What are the types of Caching in ASP.NET?

  • Page Output Caching:This type of caching is implemented by placing OutputCache directive at the top of the .aspx page at design time. For example:<%@OutputCache Duration= "30" VaryByParam= "DepartmentId"%>The duration parameter specifies for how long the page would be in cache and the VaryByParam parameter is used to cache different version of the page. The VaryByParam parameter is useful when we require caching a page based on certain criteria.
  • Page Fragment Caching:This technique is used to store part of a Web form response in memory by caching a user control.
  • Data Caching: Data Caching is implemented by using Cache object to store and quick retrieval of application data. Cache object is just like application object which can be access anywhere in the application. The lifetime of the cache is equivalent to the lifetime of the application.

AJAX

Ajax is a set of client side technologies that allows asynchronous communication between client and web server. In synchronous communication, complete round trip happens with each request/response action event when small data of the page to be refreshed. Ajax has solved this problem of posting entire information every time through asynchronous communication.
XmlHttpRequest is the basic fundamental behind Ajax. This allows browser to communicate with server without making post backs.

Difference Between Constant and ReadOnly

Const Keyword :
  • Example: public const string abc = “xyz”;
  • Initialized only at declaration.
  • Value is evaluated at compile time and can not be changed at run time.An attempt to change it will cause a compilation error.
  • Const is already kind of static.
  • Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types.

Readonly Keyword:

  • Example: public readonly string abc;
  • Can be initialized in declaration code or consturctor code.
  • Value is evaluated at run time.
  • Can be declared as static or instance level attribute.
  • A read only field can hold a complex object by using the new keyword at run time.

A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. With Const fields, the compiler performs some optimization by not declaring any stack space for the field.

Constant means - > if you want to define something at compile time . after that u can't change that value that .....

Readonly means - > if you don't know value at compile time but u can find that at runtime that time u can use readonly ..

2.8.08

ADO.NET

ADO.NET Overview

ADO.NET is design to provide data access. ADO.NET supports disconnected database access model which means that connection is open long enough to perform data operation and is closed. When data is requested by the application, connection is opened, required data is loaded to the application and connection gets close. So in ADO.NET, connection is only available when it is required. This model reduces system resource usage and thus enhances performance.
ADO.NET is shipped with the Microsoft .NET Framework. It is used to access relational data sources, XML, and application data.ADO.NET uses XML for data transaction between client application and database.

To access data using ADO.NET's DataAdapter objects

  • Create connection using connection object.
  • Create Dataset object using DataAdapter object.
  • Load data into Dataset using fill method of DataAdapter.
  • Display Data using Dataset object.
  • Close connection

ADO.NET vs ADO

  • ADO.NET is considered as evolution version of ADO.
  • ADO.NET works with both connected as well as disconnected fashion whereas ADO works with connected architecture.
  • ADO.NET provides disconnected access through DataSet while ADO provides disconnected access using recordset.
  • ADO.NET use XML to transfer data between objects while ADO use binary format to transfer data.
  • ADO.NET is shipped with .Net Framework and implemented using .Net methodology whereas ADO relies on COM.

ADO.NET Data Architecture

ADO.NET has four layers.

* The Physical Data Store

This can be any database, XML files or OLE.

*The DataSet

The dataset stores relevant portion of the database on the local machine. It allows data to be loaded in the memory of the machine and is disconnected from the database. The dataset can manipulate disconnected data in the memory. It contains one or more DataTable objects. The DataTable objects contain DataColumns, DataRows and Constraint collections. The DataSet contains a DataRelations collection which allow you to create associations between rows in one table and rows in another table.

*The Data Provider

A data provider provides a set of components that helps to extract data from database. The components are as follows:

Connection object

Command object

DataReader

DataAdapter

*The Dataview

This determines presentation of a table in the dataset. This is mainly used to sort or filter data in the dataset.

Type of database connection in ADO.NET

SQL Connection

This object connects to the SQL Server.

Oracle Connection

This object is used to connect oracle database.

Oledb connection

This object is used to connect MS Access or MySQL(third party database).
Apart from these connections, ADO.NET also allows access to XML files using Dataset object's ReadXML and WriteXML method.

Components of data providers in ADO.NET

The Connection Object

The Connection object represents the connection to the database. The Connection object has ConnectionString property that contains all the information, required to connect to the database.

The Command Object

The command object is used to execute stored procedures and command on the database. It contains methods to execute command on the database such as ExecuteNonQuery, ExecuteScalar and ExecuteReader.

ExecuteNonQuery

Executes commands that return no records, such as INSERT, UPDATE, or DELETE

ExecuteScalar

Returns a single value from a database query

ExecuteReader

Returns a result set by way of a DataReader object

The DataReader Object

The DataReader object provides a connected, forward-only and read-only recordset from a database. The Command.ExecuteReader method creates and returns a DataReader object. Since it is connected to the database throughout its lifetime, it requires exclusive use of connection object.

The DataAdapter Object

The DataAdapter object acts a communication bridge between the database and a dataset. It fills the dataset with data from the database. The dataset stores the data in the memory and it allows changes. The DataAdapter's update method can transmit the changes to the database.

The DataAdapter Object's properties.
SelectCommand-Contains the command text or object that selects the data from the database.
InsertCommandCont-ains the command text or object that inserts a row into a table.
DeleteCommand-Contains the command text or object that deletes a row from a table.
UpdateCommand-Contains the command text or object that updates the values of a database.

Define connected and disconnected data access in ADO.NET

You have connected data access through the DataReader objects of data provider. This object requires exclusive use of the connection object. It can provide fast and forward-only data access. It doesn't allow editing. Disconnected data access is achieved through the DataAdapter object. This object establishes connection, executes the command, load data in the DataSet. The dataset works independent of database. It contains data in the memory and can edit the data. The changes in the data can be transmitted to the database using Update method of DataAdapter object.

Describe CommandType property of a SQLCommand in ADO.NET.

A SQLCommand has CommandType property which can take Text, Storedprocedure or TableObject as value. If it is set to Text, the command executes SQL string that is set to CommandText property. When set to StoredProcedure, the command runs the stored procedure of the database. If the property is set to TableObject, the command returns the entire content of the table indicated by the CommandText property.

Define Dataview component of ADO.NET.

A DataView object allows you work with data of DataTable of DataSet object. It is associated with a DataTable and sits on the top of DataTable. It is used to filter and sort data. Data sorting is accomplished by setting the Sort property and data filter by setting the RowFilter property.

What are the ways to create connection in ADO.NET?

There are two ways to create connection supported by ADO.NET.

Steps to create connection in codeCreate instance of connection object.Set the ConnectionString property.

Steps to create connection using designerDrag connection object from the Data tab of the toolbox.Set the ConnectionString property using properties window.

ADO.NET transaction Processing
Steps to use transaction object
Open a database connection.Create the transaction object using BeginTransaction method of connection object.Create command object by using transaction object as the parameter. Execute the commands and check for the error.If no error, commit the changes to the database or restore the database state.Close the connection.

sample code

//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();
}

.Net Assembly

  • Question - Define .Net Assembly.
    Answer - It is a primary unit of deployment in a Microsoft .NET Framework application. It is called as building block of an application which provides all required execution information to common language runtime[CLR]. An assembly perform following functions:It contains IL code that gets executed by common language runtime. It forms a security boundary. An assembly is the unit at which permissions are requested and granted. It ensures type safety by establishing name scope for types at the runtime. It contains version information. It allows side-by-side execution of multiple versions of same assembly. Assemblies can be static or dynamic. Static assemblies are created when the program is compiled using .Net compiler. It exists as PE file either in .exe or .dll. However, dynamic assemblies are created at runtime and run from the memory without getting saved on the disk.
  • Question - What does an assembly contain?
    Answer - An assembly contains following information: Assembly manifest: Information about the assembly. Type metadata: Information about the types. IL Code Resource files.
    An assembly manifest contains the following information:
    Identity of the assemblyTypes and resourcesFilesSecurity permissions
  • Question - Define private assembly and a shared assembly.
    Answer - A private assembly is stored in the application’s directory and used by a single application. A share assembly can be used by multiple applications and is stored in the Global assembly cache, a repository of assemblies maintained by the .Net Framework.
  • Question - What are Satellite Assemblies?
    Answer - Satellite assemblies provide an application the multilingual support. Satellite assemblies contain alternate sets of resources to be used in the application for different cultures.
  • Question - What do you understand by side-by-site execution of assembly?
    Answer - This means multiple version of same assembly to run on the same computer. This feature enables to deploy multiple versions of the component.
  • Question - How do you create a resource-only assembly?
    Answer - Resources are nonexecutable data in an application and the data can be updated without recompiling application. Resource assemblies can be created as follows:Add resource files to an empty project. Built the project.The resource will get compiled into assembly.
  • Question - Explain how to retrieve resources using ResourceManager class.
    Answer - ResourceManager class is used to retrieve resources at run time. Create a ResourceManager with resource file name and the resource assembly as parameters.After having created, you can use ResourceManager.GetString method to retrieve a string.Use the ResourceManager.GetObject method to retrieve images and objects from a resource file.
  • Question - Define Strong Name. How do you apply a strong name to assembly?
    Answer - A strong name means generating public key in order to provide unique name to the assembly.The name is used to provide global name to the assembly and allows it to be shared amongst several different applications. The key generated include assembly's name, the version number, the developer's identity, and a hash number. The developer's identity identifies the author of the assembly. The hash checks if the assembly is tempered since it is created. The key pair that defines the strong name is created using the Strong Name utility, Sn.exe.
    To sign an assembly with a strong name
    Create Key pair using the Strong Name utility, Sn.exe. Open the AssemblyInfo file of your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. The strong name will be generated and signed to the assembly.
  • Question - Define Global Assembly Cache.
    Answer - Global Assembly Cache is the place holder for shared assembly. If an assembly is installed to the Global Assembly Cache, the assembly can be accessed by multiple applications. In order to install an assembly to the GAC, the assembly must have to be signed with strong name.
  • Question - How do you install assembly to the Global Assembly Cache?
    Answer - Followings are the steps to install assembly to the GAC. Sign assembly with a strong name using strong name utility, sn.exe. Open the AssemblyInfo file for your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. Install the assembly to GAC by using gacutil utility e.g. gacutil -i abc.dll

Net Framework

  • Question - Explain the .Net Framework.
    Answer - The .Net framework allows infrastructural services to all the applications developed in .net compliant language. It is an engine that provides runtime services using its component like Common Runtime Language. It consists of two main components such as Common Language Runtime and Framework Class Library.
  • Question - Describe the .Net Framework Architecture.
    Answer - The .Net Framework has two main components: .Net Framework Class Library: It provides common types such as data types and object types that can be shared by all .Net compliant language. The Common language Runtime: It provides services like code execution, type safety, security, thread management, interoperability services.
  • Question - What are the components of the .Net Framework.
    Answer - Class Loader, Compiler, Garbage Collection, Type checker, Debug engine, Exception Manager, Security engine, Thread manager, COM Marshallar, Class Library.
  • Question - Explain the role of assembly in the .Net Framework.
    Answer - .Net Framework keeps executable code or DLL in the form of assembly. .Net Framework maintains multiple versions of the application in the system through assembly. The assemblies have MSIL code and manifest that contains metadata. The metadata contains version information of the assembly.
  • Question - Describe the GAC in the .Net Framework.
    Answer - .Net Framework provides Global Assembly cache, a machine-wide cache. It stores shared assemblies that can be accessed by multiple languages

.Net Debugging and tracing

Question - What is break mode? What are the options to step through code?
Answer - Break mode lets you to observe code line to line in order to locate error.VS.NET provides following option to step through code.Step Into Step Over Step Out Run To Cursor Set Next Statement
Question - Debug Vs Trace.
Answer - Both these objects are found in the System.Diagnostics namespace. Both are used for diagnose problems without interrupting application execution. Debug statement can only be used in debug mode while trace statement can be used both in debug and released mode.Debug statements can't be compiled into a release version.
Question - Define trace class.
Answer - The trace class in the code is used to diagnose problem. You can use trace messages to your project to monitor events in the released version of the application.The trace class is found in the System.Diagnostics namespace.
Question - Define Listeners collection of Trace and Debug objects.
Answer - The Trace and Debug objects contain a Listeners collection. These Listeners collection collect output from the trace statements. There are three types of predefined listeners: DefaultTraceListenerTextWriterTraceListenerEventLogTraceListener
DefaultTraceListener: This is default listener and writes trace statements in the Output window. TextWriterTraceListener: can write output to the text file or to the console window. EventLogTraceListener: can write messages to the Event Log.
Question - Define Trace Switches.
Answer - Trace switches are used to configure tracing behavior. There are two kinds of trace switches: BooleanSwitch and TraceSwitch. BooleanSwitch: It is either on or off. TraceSwitch : It has property to determine trace behaviour. Trace switches can be configured through application's .config file even after the application is compiled.

C#.NET Interview Questions

Question - Define assembly.
Answer - An assembly is the primary unit of a .NET application. It includes an assembly manifest that describes the assembly.
Question - What is Constructor?
Answer - It is the first method that are called on instantiation of a type. It provides way to set default values for data before the object is available for use. Performs other necessary functions before the object is available for use.
Question - What is Destructor?
Answer - It is called just before an object is destroyed. It can be used to run clean-up code. You can't control when a destructor is called since object clean up by common language runtime. Question - Define Abstract class in C#.NET.
Answer - Abstract class cannot be instantiated.
Same concept in C++ known as pure virtual method.
A class that must be inherited and have the methods over-ridden.
A class without any implementation.
Question - Explain serialization?
Answer - Serialization is a process of converting an object into a stream of bytes. .Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer. Serialization is maily used in the concept of .Net Remoting.
Question - C#.Net support multiple inheritance, comment.
Answer - No, but we can use interface instead.
Question - Can private virtual methods be overridden in C#.NET?
Answer - No, moreover, you cannot access private methods in inherited classes,
They have to be protected in the base class to allow any sort of access.