Pages

Monday, October 13, 2008

Interview Questions- DOTNetUncle

What is the use of the main() function in C#?
Every executable C# application must contain a class defining a Main() method that signifies the entry point of the application. Note that the Main() method is of the access type public by nature. Moreover, it is also static. See example below:

using System;
class Question
{
public static int Main(string[] args)
{
Console.Writeline("Another Question");
Console.Readline();
return 0;
}
}
A public member is accessible from other types. The main() method is set as static so that it may be invoked at class level itself, without the need of creating an instance of it. The single parameter is an array of strings. that may contain any number of incoming command line arguments.

Are C# Keywords in lowercase or uppercase?
All C# keywords are in lowercase.
Namespaces, Types and Members have their first character in uppercase.

What is the use of Console.Readline() in C#?
Using the Console.Readline() method means that the command prompt launched by Visual Studio remains visible during an application session until the ENTER key is pressed by the user.

Can we set the specifier of the main() method in C# as private?
Yes. When the access specifier is set as private for the Main() method, then other assemblies may not invoke this class' Main() method as the starting point of the application. The startup scope gets limited to the class in context itself. See code below:

private static void Main()
{
//This code isn't invoked automatically by other assemblies
}

Can we set different types of parameters & return-types in main() method"?
Yes. The Main() method may easily be played around with by developers by passing different parameters and setting different return types. See the code below, that demonstrates different ways the Main() method may be implemented:
(1)
public static void Main(string[] args)
{
//NO return type, the argument is an array of strings
}

(2)
public static int Main(string[] args)
{
//Return type is int, argument is an array of strings
}

(3)
public static int Main()
{
//Return type is int, NO arguments
}

(4)
public static void Main()
{
//Return type is void, NO arguments
}

What is the use of GetCommandLineArgs() method?
The GetCommandLineArgs() method is used to access the command line arguments. The return value of this method is an array of strings. It is a method of the System.Environment class. See the code example below:

public static int Main(string[] args)
{
string[] strArgs = System.Environment.GetCommandLineArgs();
Console.WriteLine("Arguments {0}", strArgs[0]);
}

What is the use of System.Environment class?
The class System.Environment is used to retrieve information about the operating system. Some of the static members of this class are as follows:
1) Environment.OSVersion - Gets the version of the operating system
2) Environment.GetLogicalDrives() - method that returns the drives
3) Environment.Version - returns the .NET version running the application
4) Environment.MachineName - Gets name of the current machine
5) Environment.Newline - Gets the newline symbol for the environment
6) Environment.ProcessorCount - returns number of processors on current machine
7) Environment.SystemDirectory - returns complete path to the System Directory
8) Environment.UserName - returns name of the entity that invoked the application

Why is the new keyword used for instantiating an object in .NET?
The new keyword instructs the .NET compiler to instantiate a new object, with appropriate number of bytes (depending on the type) for the object and gather required memory from the managed heap.

What are the default values for bool, int, double, string, char, reference-type variables?
When the objects of the following types are declared, then they have a default value during declaration. The following table shows the default value for each type:

Type

Default Value

bool

false

int

0

double

0

string

null

char

'\0'

Reference Type

null

Why does the compiler throw an error when variables are declared with an initial value?
The compiler throws an error when a variable is declared without an initial value, when the declaration is within a member scope. The variables do not recieve default value when they are declared within a scope.
Note that if the variable is used as an output parameter, this variable does not need to be assigned an initial value.

How to declare a constant variable in C#? What is the use of the const keyword?
If a variable needs to have a fixed value, that may not be changed across the application's life, then it may be declared with the const keyword. The value assigned to a constant variable (using the const keyword) must be known at the time of compilation.

In C#, can we create an object of reference type using const keyword?
No. A constant member may not be created of an object that is of reference type, because its value is decided dynamically at runtime.

What is the difference between const and readonly in C#?
When using the const keyword to set a constant variable, the value needs to be set at compile time. The const keyword may not be used with an object of reference type.

In case a reference type needs to be assigned a non-changeable value, it may be set as readonly

What are the different parameter modifiers available in C#? What is a parameter modifier?
Parameter modifiers in C# are entities that controls the behaviour of the arguments passed in a method. Following are the different parameter modifiers in C#:
1) None - if there is NO parameter modifier with an argument, it is passed by value, where the method recieves a copy of the original data.
2) out - argument is passed by reference. The argument marked with "out" modifier needs to be assigned a value within this function, otherwise a compiler error is returned.

public void multiply(int a, int b, out int prod)
{
prod = a * b;
}

Here, note that prod is assigned a value. If not done so, then a compile time error is returned.
3) params- This modifier gives the permission to set a variable number of identical datatype arguments.
Note that a method may have only one "params" modifier. The params modifier needs to be in the last argument.

static int totalruns(params int[] runs)
{
int score = 0;
for(int x=0; x
&nsbp;score+=runs[x];
return score;
}
Further, from the calling function, we may pass the scores of each batsman as below...

score = totalruns(12,36,0,5,83,25,26);

4) ref - The argument is given a value by the caller, where data is passed by reference. This value may optionally be reset in the called method. Note that even if NO value is set in the called method for the ref attribute, no compiler error is raised.

What is the difference between out and ref in C#?
1)
out parameters return compiler error if they are not assigned a value in the method. Not such with ref parameters.
2) out parameters need not be initialized before passing to the method, whereas ref parameters need to have an initial value before they are passed to a method.

What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.
In VB.NET, the equivalent of protected internal is protected friend.
The access of this modifier is limited to the current assembly or the types derived from the defining class in the current assembly.

Can multiple data types be stored in System.Array?
So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.
An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array).

A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#...

int[] testIntArray = new int[4] { 2, 3, 4, 5 };
Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };

Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See code example below written in VB.NET...

Dim allTypes As Object() = New Object() {}

'In this kind of scenario, the performance may tend to slow down, as data conversions may take place.
'In case a value type is converted to reference type, then boxing and unboxing occurs
'To know more on Value Types & Reference Types, Click Here

Dim studentTable(2) As Object
studendTable(0) = "Vishal Khanna"
studentTable(1) = 28
studentTable(2) = #9/1/1978#

'To get these values of these varying datatypes, their values are converted to their original data type

Dim myAge As Integer = CInt(studentTable(1))
Dim myBirthDay as Date = CDate(studentTable(2))

The World of Difference!

Whats the difference between Classic ASP and ASP.NET?
Major difference:
Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles, otherwise does'nt.
Other differences: ASP works with VB as the language. ASP.NET works with VB.NET & C# as the languages (Also supported by other languages that run on the .NET Framework).
ASP.NET is the web technology that comes with the Microsoft .NET Framework. The main process in ASP.NET is called aspnet_wp.exe that accesses system resources. ASP.NET was launched in 2002 with version 1.0. Subsequent versions are 1.1 and version 2.0. ASP.NET is built up using thousands of objects, ordered in the System namespace. When an ASP.NET class is compiled, its called an assembly.
In Classic ASP, complex functionalities are achieved using COM components, that are nothing but component objects created using VB 6, C++ etc, and are usually in a DLL format. These components provide an exposed interface to methods in them, to the objects that reference these components. Last version of classic ASP is version 3.0. ASP has 7 main objects - Application, ASPError, ObjectContext, Request, Response, Server, Session.

What is the difference between ADO and ADO.NET?
The old ADO (ActiveX Data Object) has evolved to ADO.NET in the .NET Framework. The ADO.NET object is a lightweight object. The ADO Recordset was a huge object in ADO. It provided the ability to support multiple types of cursors. It provided fast lightweight "firehose" cursor and also supported a disconnected client-side cursor that supported tracking, optimistic locking, and automatic batch updates of a central database. However, all of this functionality was difficult to customize.
ADO.NET breaks the functionality of the ADO object to multiple classes, thereby allowing a focused approach to developing code. The ADO.NET DataReader is equivalent to the "firehose" cursor. The DataSet is a disconnected cache with tracking and control binding functionality. The DataAdapter provides the ability to completely customize how the central data store is updated with the changes to a DataSet.

Whats the difference betweeen Structure, Class and Enumeration
Structures
and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory.
Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a structure, but, remember, A No-argument constructor for a structure is not possible. The structure's constructor should always have a parameter.

So if we define the following structure

struct MyStruct
{
public int y,z;
}
and we create a structure type
MyStruct st = new MyStruct();

In case of a class, no-argument constructors are possible. Class is defined using the class keyword.

A struct cannot have an instance field, whereas a class can.

class A
{
int x = 5; //No error
...
}

struct
{
int x = 5; //Syntax Error
}

A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure.

Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1.

enum colors {red, green, blue, yellow};

Here, red is 0, green is 1, blue is 2 and so on.
An explicit casting is required to convert an enum value to its underlying type

int x = (int)colors.yellow;

Explain the access specifiers Public, Private, Protected, Friend, Internal, Default
The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.
1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.

4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

What is the difference between Overriding and Shadowing?
Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though here is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.

What is the difference between abstract class and interface?
If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below

Example: Abstract Class with Abstract method
namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}

Example: Abstract Class with Virtual method
namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}
}

Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()
}
}
}

An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:

Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
Boolean HasFourWheels()
}

Time to discuss the Difference between Abstract Class and Interface

1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.

Whats the difference between a class and an object?
In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}

From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor

Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.

What is the difference between Shared and Static?
They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example
//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print

//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class

To use static members, give a reference to the exact class, as an instance in this case won't work.

To make this work, write...
Console.Writeline("Vishal likes static members");

To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.

Note Indexers in C# cannot be declared static.

Note Static member functions cannot access non-static members directly.

What is the difference between value type and reference type? Can a value type contain NULL values?
In simple words, all value based types are allocated on the stack, while all reference based types are allocated on the heap. What does this mean? A value type contains the actual value. A reference type contains a reference to the value. When a value type is assigned to another value type, it is copied. When a reference type is assigned to another reference type, a reference is assigned to the value.
By saying stack, we mean things are kept one on top of the other. We keep track of each value at the top. By saying heap, we mean things are kept in a mashed order. We keep track of each value by its address, that is referenced by a pointer to it.
All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in System.Object, the base class for all objects which is a reference type itself.
Data types like integers, floating point numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes, Strings, Arrays are examples of Reference Types.
A value type may not contain NULL values. Reference types may contain NULL values.
It is not possible to derive new types from Value Types. This is possible in Reference types. However, Value Types like Structures can implement interfaces.

Whats the difference between MSIL and CIL?
MSIL
is the name given to the intermediate language in .NET Framework Beta, 1.0 and 1.1. From version 2.0 onwards, the intermediate language is called CIL. We can say, MSIL is the old name. MSIL stands for Microsoft Intermediate Language. CIL stands for Common Intermediate Language. Its actually a low level human readable language implementation of CLI.
There is not much difference between the two. Compilers like vbc.exe and csc.exe compile the code into intermediate language. CIL is the name submitted by Microsoft to the European Computer Manufacturer's Association(ECMA) as a standard.

What is the difference between a DLL and an EXE?
In .NET, an assembly may become a DLL or an EXE. Yet, there is a major underlying difference between the two.
An EXE is an executable file, that may run on its own. Its independant. Where as a DLL is a Dynamic Link Library, that binds to an exe, or another DLL at runtime.
A DLL has an exposed interface, through which members of the assembly may be accessed by those objects that require it.
A DLL runs in tandem with the application space in memory, as the application references it. Whereas an EXE is independant, and runs as an independant process.

What is the difference between a Class Library and a Namespace?
Class Library
is another major entity of the .NET Framework (the other being the CLR). This library gives the program access to runtime environment. The class library consists of lots of prewritten code that all the applications created in .NET will use. The code for all the elements like forms, controls actually comes from the class library. The main class library in .NET is mscorlib.dll. This library contains a large number of core types that encapsulate a wide variety of common tasks. When a .NET application, there is automatic access to this library. We may view the class libraries provided by the .NET Framework by seeing the Global Assembly Cache (Go to C:\Windows\Assembly OR C:\Winnt\Assembly).
Namespace is a grouping of related types contained in an assembly. For example, the System.Drawing namespace consists of classes, methods that are grouped together to achieve similar tasks.
Note that a single assembly like mscorlib.dll may contain any number of namespaces. In fact, namespaces may be nested (means a namespace within a namespace) to arrange classes in a hierarchical fashion.
Also note that any language, that works on the .NET environment, targets the same set of namespaces & types provided by the .NET framework.

What is the difference between String and StringBuilder?
Both String and StringBuilder are classes used to handle strings.
The most common operation with a string is concatenation. This activity has to be performed very efficiently. When we use the "String" object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted. This process is a little long. Hence we say "Strings are immutable".
When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed.

What is the difference between Web Services and Remoting?
Both Remoting and Web Services are ways of communication between applications.
Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.
Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.
Here are some of the major differences:
* ASP.NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP
* Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation
* ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.
* Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.
* In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET.
* Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.

What is the difference between a Public Assembly and a Private Assembly?
An assembly is the basic building block in .NET. It is the compiled format of a class, that contains Metadata, Manisfest & Intermediate Language code.
An assembly may be either Public or Private. A public assembly means the same as Shared Assembly.
Private Assembly - This type of assembly is used by a single application. It is stored in the application's directory or the applications sub-directory. There is no version constraint in a private assembly.
Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named. In order to share an assembly with many applications, it must have a strong name.
A Strong Name assembly is an assembly that has its own identity, through its version and uniqueness.
In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below..
1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following...
sn -k C:\samplekey.snk

This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute.
Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file...



We may write this in our code as well, like this...

Imports System.Reflection

Namespace StrongName
Public class Sample
End Class
End Namespace

3) Build your project. Your assembly is now strongly named.
Installing the Shared assembly in GAC...
Go to .NET command interpreter, use the tool gacutil.exe
Type the following...
gacutil /i sampleclass.dll
To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC.

What is the difference between Trace and Debug?
Trace and Debug
- There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.
Tracing is actually the process of collecting information about the program's execution. Debugging is the process of finding & fixing errors in our program. Tracing is the ability of an application to generate information about its own execution. The idea is that subsequent analysis of this information may help us understand why a part of the application is not behaving as it should and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in .NET via the System.Web.TraceContext class via the System.Diagnostics.Trace and System.Diagnostics.Debug classes. Tracing can be thought of as a better alternative to the response.writes we used to put in our classic ASP3.0 code to help debug pages.

If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output is appended in the web form output. Messeges can be displayed in the Trace output using Trace.Warn & Trace.Write.

NOTE The only difference between Trace.Warn & Trace.Write is that the former has output in red color. If the trace is false, there is another way to enable tracing. This is done through the application level. We can use the web.config file and set the trace attribute to true. Here we can set

Note that the Page Directive Trace attribute has precedence over th application level trace attribute of web.config. While using application level tracing, we can view the trace output in the trace.axd file of the project.

What is the difference between Server.Transfer and Response.Redirect?
Both "Server" and "Response" are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is an underlying difference.//Usage of Server.Transfer & Response.Redirect
Server.Transfer("Page2.aspx");
Response.Redirect("Page2.aspx");

The Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this established standard works very well. By the time Page2 is requested, Page1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.
The more efficient Server.Transfer method simply renders the next page to the browser without an extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because it’s still in memory. This technique would be ideal if it wasn’t for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still show “Page1.aspx” even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. This may occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of touch with the server. Say, the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing. In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may be the deciding factor in choosing.

What is the difference between Server.Transfer and Server.Execute?
Both Server.Transfer and Server.Execute were introduced in Classic ASP 3.0 (and still work in ASP.NET).
When Server.Execute is used, a URL is passed to it as a parameter, and the control moves to this new page. Execution of code happens on the new page. Once code execution gets over, the control returns to the initial page, just after where it was called. However, in the case of Server.Transfer, it works very much the same, the difference being the execution stops at the new page itself (means the control is'nt returned to the calling page).
In both the cases, the URL in the browser remains the first page url (does'nt refresh to the new page URL) as the browser is'nt requested to do so.

What is the difference between Authorization and Authentication?

Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement.

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system.

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.

When a user logs on to an application/system, the user is first Authenticated, and then Authorized.
ASP.NET has 3 ways to Authenticate a user:
1) Forms Authentication
2) Windows Authentication
3) Passport Authentication (This is obsolete in .NET 2.0)
The 4th way is "None" (means no authentication)

The Authentication Provider performs the task of verifying the credentials of the user ans decides whether a user is authenticated or not. The authentication may be set using the web.config file.
Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS.
There are 4 types of Windows Authentication methods:
1) Anonymous Authentication - IIS allows any user
2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure). 3) Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above
4) Integrated Windows Authentication - Relies on Kerberos technology, with strong credential encryption

Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information.

Authorization in .NET - There are two types:

FileAuthorization - this depends on the NTFS system for granting permission
UrlAuthorization - Authorization rules may be explicitly specified in web.config for different web URLs.

What is the difference between ExecuteScalar and ExecuteNonQuery? What is ExecuteReader?
ExecuteScalar
- Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.

ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example:
SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);
//note that con is the connection object
con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed

ExecuteReader - This method returns a DataReader which is filled with the data that is retrieved using the command object. This is known as a forward-only retrieval of records. It uses our SQL statement to read through the table from the first to the last record.

What is the difference between a DataReader and Dataset in ADO.NET?
A DataReader works in a connected environment, whereas DataSet works in a disconnected environment.
A DataReader object represents a forward only, read only access to data from a source. It implements IDataReader & IDataRecord interfaces. For example, The SQLDataReader class can read rows from tables in a SQL Server data source. It is returned by the ExecuteReader method of the SQLCommand class, typically as a result of a SQL Select statement. The DataReader class' HasRows property can be called to determine whether the DataReader retrieved any rows from the source. This can be used before using the Read method to check whether any data has been retrieved.

Example
Dim objCmd as New SqlCommand("Select * from t_Employees", objCon)
objCon.Open()
Dim objReader as SqlDataReader
objReader = objCom.ExecuteReader(CommandBehavior.CloseConnection)
If objReader.HasRows = True then
Do While objReader.Read()
ListBox1.Items.Add(objReader.GetString(0) & vbTab & objReader.GetInt16(1))
Loop
End If
objReader.Close()

(NOTE: XmlReader object is used for Forward only Read only access of XML).

A DataSet represents an in-memory cache of data consisting of any number of inter-related DataTable objects. A DataTable object represents a tabular block of in-memory data. Further, a DataRow represents a single row of a DataTable object. A Dataset is like a mini-database engine, but its data is stored in the memory. To query the data in a DataSet, we can use a DataView object.

Example
Dim objCon as SqlConnection = New SqlConnection("server=(local);database=NameOfYourDb;user id=sa; password=;)
Dim da as New SqlDataAdapter
Dim ds as DataSet = New DataSet
da.SelectCommand.Connection = objCon 'The Data Adapter manages on its own, opening & closing of connection object
da.SelectCommand.CommandText = "Select * from t_SomeTable"
da.Fill(ds,"YourTableName")

Suppose you want to bind the data in this dataset to a gridview

Gridview1.DataSource = ds
Gridview1.DataMember = "YourTableName"
Gridview1.Databind()

What is the difference between System.Array.CopyTo and System.Array.Clone in .NET?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy.

What is the difference between a Thread and Process?
A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each application has at least one process, and a process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution.
When a thread begins to execute, it continues until it is killed or until it is interrupted by a thread with higher priority (by a user action or the kernel’s thread scheduler). Each thread can run separate sections of code, or multiple threads can execute the same section of code. Threads executing the same block of code maintain separate stacks. Each thread in a process shares that process’s global variables and resources.

OOPs Unleashed!

What is OOPs?
OOPs - Object Oriented Programming Languages & Systems

Everything in the world is an object. The type of the object may vary. In OOPS, we get the power to create objects of our own, as & when required. OOPs is a programming methodology where each entity is an object.
It is a method of computer programming where entities of related data together with routines associated with it are treated as one object in the program.

What is a class? What is a Base Class?
A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
It is important to note that a class is a Reference Type.
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.

What is Encapsulation?
Encapsulation
- is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);

What is inheritance?
Inheritance
- is the concept of passing the traits of a class to another class.
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon. (Reference)

What is a class member? What is an object?
The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.
When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.

Whats the difference between a class and an object?
In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}

From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor

Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.

What is polymorphism?
Polymorphism
means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading

What is a property? What is an event?
Property
- A property is a thing that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at this definition, we might think we could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the real technical term for a public variable in a class is a field. The main difference between a field and a property is in the inclusion of an interface.

We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set.ss="a">

Private _Color As String
Public Property Color()
Get
Return _Color
End Get
Set(ByVal Value)
_Color = Value
End Set
End Property

Event - An action that an object does. When something happens, we say an event has happened. For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an image, we say the mouseover( ) event has taken place.

What is an access modifier? What are the different types of Access modifiers?
Access Modifiers
- Keywords used to change the way members of a class are accessed. The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.

Explain the access specifiers Public, Private, Protected, Friend, Internal, Default
The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.
1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.

4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

What is Overloading? What is Overloads? What is Overload?
Overloading
- is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.
The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.
Overloading is a way through which polymorphism is achieved.

What is shared keyword used for? What is static?
Shared and Static mean the same. Shared is used in VB.NET, while Static is used in C#.

They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example

//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print

//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class

To use static members, give a reference to the exact class, as an instance in this case won't work.

To make this work, write...
Console.Writeline("Vishal likes static members");

To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.

Note Indexers in C# cannot be declared static.

Note Static member functions cannot access non-static members directly

What is the virtual keyword used for?
Virtual
- If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.

public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}


public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}

Explain overridable, overrides, notoverridable,mustoverride
These keywords are used in VB.NET.
Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.
Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.
NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.

What is shadowing? Explain shadows keyword
Shadowing
- is a concept of altering the behavior of a base class member.

What is the difference between Overriding and Shadowing?
Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.

What is a constructor? Explain the New Keyword. What is a Private Constructor?
Constructor
- A constructor is a function with the same name as that of the class. The Default Constructor of a class is without an argument. The default constructor ensures that every member data is initialized to a default value. Constructors provide a way for classes to initialize a state for their members. Note that constructors dont have a return type(not even void).

public SomeClass()
{
Console.Writeline("Vishal says, Default Constructor is called");
}
\
public SomeClass(string str)
{
Console.Writeline("Vishal says, Custom Constructor is called" + str);
}

When a custom constructor is defined, the Default Constructor is not called. A constructor may also be overloaded.
New - This keyword may be used as a modifier and as an operator. When used as an operator, it creates an object on a heap to invoke constructors. When used an a modifier, it hides an inherited member from the base class member.
As an operator, it can be used to create an object and then to invoke the constructor of the class. See example below.

Example
SomeClass objSomeClass = new SomeClass(); //Creating a class object and invoking its constructor

float amount = new float(); //Creating an object of the type, and invoking its constructor

As a modifier, it is used to explicitly hide a member from the base class. See example.

Example
public class MamaClass
{
public void SomeMethod() { ... }
}

public class BabyClass : MamaClass
{
new public void SomeMethod() { .... }
}

Private Constructor - When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. It is also used to create Singleton classes.

What is a static constructor?
Static Constructor
- It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}

While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?
No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

What is Serialization? What is serializable attribute used for?
Serialization
- The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.
.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter

The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...

Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()

Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…

Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next

Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.
XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

What is a delegate? What is a Multicast Delegate?
Delegate
- It is a type safe function pointer. It is a type that holds the reference of a method. A delegate may be used to call a method asynchronously.
Multicast Delegate - it is a delegate that holds reference of more than one method. Multicast Delegates must have a return type of void.

What is an abstract class?
If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated.

What is an interface? How to implement an interface?
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented.

Is multiple inheritance possible in .NET?
No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.

.NET Framework Explored!

What is .NET?
.NET
- is the Microsoft Web services strategy to connect information, people, systems, and devices through software. Integrated across the Microsoft platform, .NET technology provides the ability to quickly build, deploy, manage, and use connected, security-enhanced solutions with Web services. .NET-connected solutions enable businesses to integrate their systems more rapidly and in a more agile manner and help them realize the promise of information anytime, anywhere, on any device.

Which languages can be used to program in .NET?
Microsoft provides these languages for programming .NET - C#, VB.NET, JS.NET, C++.NET.
C++.NET may be used as a Managed Code Language by using managed extensions. This is done using an _gc postfix. A managed C++ class can inherit from VB.NET classes, C# classes, JS.NET classes. A managed class can inherit from only one class. .NET does'nt allow multiple inheritance in managed classes.
Any Language that has a compiler that can compile the language code to MSIL is a .NET compliant language.
Below is an alphabetical list of languages supported by .NET
APL
- It is a language for describing procedures in the processing of information. It is a very powerful language. It may be used to describe mathematical procedures.
C++ - A widely known language. One of the oldest Object Oriented Languages, an advanced version of the C language. Microsoft has its own Visual C++ compiler that includes special tools and libraries for development on Windows platform. C++ is an object-oriented programming language that is viewed by many as the best language for creating large-scale applications. C++ is a superset of the C language.
C# - Pronounced C Sharp. It is a complete Object-Oriented programming language from Microsoft built into the .NET Framework. First created in the late 1990’s was part of Microsoft’s whole .NET strategy.
COBOL - Expanded as Common Business Oriented Language. It is a widely used high level language for developing Business Applications.
Component Pascal - Its a Pascal derived programming language for development of programming components.
Eiffel - It is an Object-Oriented programming language which emphasizes the production of robust software.
Forth - It is both a programming language & a programming environment. It supports shell programming to a high level.
Fortran - Stands for Formula Translator. Its a high level programming language used for scientific computations. It supports plenty of compact notations.
Haskell - It is a standardized functional programming language with non-strict semantics, named after the logician Haskell Curry. It was created by a committee formed in the 1980s for the express purpose of defining such a language.The latest semi-official language standard is Haskell 98, intended to specify a minimal, portable version of the language for teaching and as a base for future extensions.
Java - It is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly.
Microsoft JScript - A scripting language developed by Microsoft to enable Web page designers to design interactive sites. Although it shares many of the features and structures of the full Java language, it was developed independently. Jscript can interact with HTML source code, better enabling Web authors to spice up their sites with dynamic content.
Mercury - Mercury is a functional/logical programming language based on Prolog, but more useful for real-world programming.
Mondrian - It is a simple functional scripting language for Internet applications. It is a functional language specifically designed to inter-operate with other languages in an OO environment. Current versions of Mondrian run on .NET. Mondrian also supports ASP.NET, allowing you to embed functional language code in web pages along with C# code.
Oberon - It is a programming language very much like Modula-2 in syntax but with several interesting features. It's based on OOP concepts and also provides a Windows-based GUI.
Pascal - A high-level, highly structured, general-purpose programming language. Named after Blaise Pascal.
Perl - Stands for Practical Extraction and Report Language. It is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information.
Python - It is an interpreted, interactive, Object-Oriented programming language. Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing.
RPG - Stand for Report Program Generator. It is used for generation of reports from data files, including matching record and sub-total reports. RPG is one of the few languages created for punch card machines that is still in common use today.
Scheme - It is a statically scoped programming language. It was designed to have an exceptionally unambigous and simple semantics and few different ways to form expressions. A vast variety of programming paradigms, including imperative, functional, and message passing styles, find convenient expression in Scheme.
Smalltalk - It is a simple language that uses a simple sub set of human languages, nouns and verbs. Smalltalk was the first, and remains one of the few, pure object systems, which simply means that everything in a Smalltalk program is an object.
Standard ML - It is a safe, modular, strict, functional, polymorphic programming language with compile-time type checking and type inference, garbage collection, exception handling, immutable data types and updatable references, abstract data types, and parametric modules.
Microsoft Visual Basic - Most widely used language in the world today! Used for developing Windows based Applications, Windows Services, Remoting Applications, Web Services and Web Applications(using ASP.NET).

Which versions of .NET have been released so far?
The final version of the .NET 1.0 SDK & runtime were made publically available on 15 - Jan -2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.
.NET 1.1 was released in April 2003, with bugs fixed. Visual Studio 2003 supports development of applications in version 1.1.
.NET 2.0 was launched in October 2005 for MSDN subscribers, and officially released in Nov 2005.
On - Jun - 2006, .NET 3.0 was launched. This version was earlier called WinFX. Visual Studio 2005 supports development of .NET 2.0 and .NET 3.0 applications. .NET 3 is comprised of the following:
Windows Communication Foundation
Windows Presentation Foundation
Windows Workflow Foundation
Windows Cardspace
The next version of Visual Studio, code named Orcas, Beta 1 has been released as a Beta Version. The .NET Framework 3.5 Beta is also available as a download.

Which tools can be used for .NET Development?
The .NET Framework SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or novice developers and are available for FREE Download at Microsoft site. Note that .NET 2.0 Framework gets downloaded along with Visual Studio Express & All versions above Visual Studio Express. Download Visual Studio Express
There are different versions for C#, VB, web development etc. Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade. At the top end of the price range are the Microsoft Visual Studio Team Edition for Software Developers 2005 with MSDN Premium and Team Suite editions. Visual Web Developer Express is available as a free download.
The next version of Visual Studio, code named Orcas, Beta 1 has been released as a Beta Version and is available for download. Download Orcas

Explain CLI, CIL, CTS, Metadata, CLS, IL and VES in .NET
CLI
- Common Language Infrastructure. Microsoft has a piece of shared source, its the public implementation of ECMA Common Language Infrastructure. This shared code is code-named "Rotor". It has around 3 million lines of code. Those who are interesed in development of a language that targets the .NET Framework, may extensively make use of this CLI. The following topics are covered in the Shared Source CLI :
* The CLI type system
* Component packing & assemblies
* Type Loading & JIT Compilatino
* Managed code & Execution Engine (CLR)
* Description of Garbage Collection process & memory management
* The Platform Adaptation Layer (PAL): a portability layer for Win32®, Mac OS® X, and FreeBSD
Its been written by the Microsoft Team that has developed the .NET Framework.
Note: A compiled managed assembly is comprised of IL, Metadata and Manifest.

CIL Stands for Common Intermediate Language. Its actually a low level human readable language implementation of CLI. All .NET-aware languages compile the source oode to an intermediate language called Common Intermediate Language using the language specific compiler. It is also possible to build .NET assemblies direclty using CIL using the ilasm.exe compiler. This compiler is shipped along with the .NET Framework 2.0 SDK. CIL is the only language that allows access to each aspect of the CTS. CIL is the definition of the fundamentals of the .NET framework.

CTS - stands for Common Type Specification. It is at the core of .NET Framework's cross-language integration, type safety, and high-performance code execution. It defines a common set of types that can be used with many different language syntaxes. Each language (C#, VB.NET, Managed C++, and so on) is free to define any syntax it wishes, but if that language is built on the CLR, it will use at least some of the types defined by the CTS.

Metadata - is code that describes the compiled IL. A .NET language compiler will generate the metadata and store this in the assembly containing the CIL. Metadata describes all class members and classes that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly. The metadata for a method contains the complete description of the method, including the class (and the assembly that contains the class), the return type and all of the method parameters. When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as the metadata that is stored in the calling method. This ensures that a method can only be called with exactly the correct number of parameters and exactly the correct parameter types.

CLS - Common Language Specification. A type that is CLS compliant, may be used across any .NET language. CLS is a set of language rules that defines language standards for a .NET language and types declared in it. While declaring a new type, if we make use of the [CLSCompliant] attribute, the type is forced to conform to the rules of CLS.

IL - Intermediate Language, is the compiled form of the .NET language source code. When .NET source code is compiled by the language specific compiler (say we compile C# code using csc.exe), it is compiled to a .NET binary, which is platform independent, and is called Intermediate Language code. The .NET binary also comprises of metadata.

Its important to note here that metadata describes the IL, whereas manifest describes the assembly.

VES - Virtual Execution System. The Virtual Execution System(VES) provides an environment for executing managed code. It provides direct support for a set of built-in data types, defines a hypothetical machine with an associated machine model and state, a set of control flow constructs, and an exception handling model.To a large extent, the purpose of the VES is to provide the support required to execute the Common Intermediate Language instruction set.

What is CLR in .NET?
Common Language Runtime
- It is the implementation of CLI. The core runtime engine in the Microsoft .NET Framework for executing applications. The common language runtime supplies managed code with services such as cross-language integration, code access security, object lifetime management, resouce management, type safety, pre-emptive threading, metadata services (type reflection), and debugging and profiling support. The ASP.NET Framework and Internet Explorer are examples of hosting CLR.

The CLR is a multi-language execution environment. There are currently over 15 compilers being built by Microsoft and other companies that produce code that will execute in the CLR.

The CLR is described as the "execution engine" of .NET. It's this CLR that manages the execution of programs. It provides the environment within which the programs run. The software version of .NET is actually the CLR version.

When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL, now called CIL, Common Intermediate Language). This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL.

What is a Class Library in .NET?
Class library
is the another major entity of the .NET Framework. This library gives the program access to runtime environment. The class library consists of lots of prewritten code that all the applications created in .NET aware languages and Visual Studio .NET will use. The code for all the elements like forms, controls and the rest in VB .NET applications actually comes from the class library.
Code in class libraries may be shared & reused. One of the core . NET libraries is mscorlib.dll. .NET language compilers reference this library automatically as it contains core types. A class library, contains types, that may be used by external applications. A class library may be a DLL or an EXE. Note that the .NET class libraries, even though have a same extension as the old COM Win32 binaries, yet they are very different internally.

Explain Managed code, managed class and managed data in .NET
Managed Code
- The .NET framework provides lots of core runtime services to the programs that run within it. For example - security & exception handling. Such a code has a minimum level of information. It has metadata associated with it. Such a code is called Managed Code. VB.NET, C#, JS.NET code is managed by default. In order to make C++ code managed, we make use of managed extensions, which is nothing but a postfix _gc after the class name.
Managed Data - Data that is allocated & freed by the .NET runtime's Garbage collecter.

Managed Class - A class whose objects are managed by the CLR's garbage collector. In VC++.NET, classes are not managed. However, they can be managed using managed extentions. This is done using an _gc postfix. A managed C++ class can inherit from VB.NET classes, C# classes, JS.NET classes. A managed class can inherit from only one class. .NET does'nt allow multiple inheritance in managed classes.

What is an assembly in .NET? What is ILDASM?
Assembly
- An assembly may be an exe, a dll, an application having an entry point, or a library. It may consist of one or more files. It represents a group of resources, type definitions, and implementation of these types. They may contain references to other assemblies. These resources, types & references are compacted in a block of data called manifest. The manifest is a part of the assembly, which makes it self-describing. Assemblies also increase security of code in .NET. An assembly maybe shared(public) or private. The assembly, overall comprises of 3 entities: IL, Manifest, Metadata. Metadata describes IL, whereas Manifest describes the assembly.
An assembly may be created by building the class(the .vb or .cs file), thereby producing its DLL.
ILDASM - The contents of an assembly may be viewed using the ILDASM tool, that comes with the .NET SDK or the Visual Studio.NET. The ildasm.exe tool may also be used in the command line compiler.

What is Reflection in .NET?
Reflection
- The process of getting the metadata from modules/assemblies. When .NET code is compiled, metadata about the types defined in the modules is produced. These modules are in turn packaged as assemblied. The process of accessing this metadata in called Reflection.
The namespace System.Reflection contains classes that can be used for interrogating the types for a module/assembly. We use reflection for examining data type sizes for marshalling across process & machine boundaries.
Reflection is also used for:
1) To dynamically invoke methods (using System.Type.InvokeMember)
2) To dynamically create types at runtime (using System.Reflection.Emit.TypeBuilder).

What are the different types of assemblies in .NET?
An assembly may be Public or Private. A public assembly is also called a Shared Assembly.
A Satellite Assembly - is an assembly that contains only resources, and no code. The resources are location specific. A satellite assembly is associated with a main assembly, the one that actually contains the code.

What is the difference between a Public Assembly and a Private Assembly?
An assembly is the basic building block in .NET. It is the compiled format of a class, that contains Metadata, Manisfest & Intermediate Language code.
An assembly may be either Public or Private. A public assembly means the same as Shared Assembly.
Private Assembly - This type of assembly is used by a single application. It is stored in the application's directory or the applications sub-directory. There is no version constraint in a private assembly.
Shared Assembly or Public Assembly - A shared assembly has version constraint. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. It is located at C:\Windows\Assembly OR C:\Winnt\Assembly. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named. In order to share an assembly with many applications, it must have a strong name.
A Strong Name assembly is an assembly that has its own identity, through its version and uniqueness.
In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below...
1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following...
sn -k C:\samplekey.snk

This will create a strong key and save it to the location C:\samplekey.snk 2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute. If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute.
Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file...



We may write this in our code as well, like this...
Imports System.Reflection

Namespace StrongName
Public class Sample
End Class
End Namespace

3) Build your project. Your assembly is now strongly named.
Installing the Shared assembly in GAC...
Go to .NET command interpreter, use the tool gacutil.exe
Type the following...
gacutil /i sampleclass.dll
To uninstall it, use... gacutil /u sampleclass.dll. Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC.

How to share an assembly? How to make it strongly named? What is SN.EXE?
In order to share an assembly with many applications, it must have a strong name.
In order to convert a private assembly to a shared assembly, i.e. to create a strongly named assembly, follow the steps below...
1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The key pair that is generated by the Strong Name tool can be kept in a file or we can store it our your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command interpreter, and type the following...

sn -k C:\samplekey.snk
This will create a strong key and save it to the location C:\samplekey.snk
2) If the key is stored in a file, just like we have done above, we use the attribute AssemblyKeyFileAttribute. This belongs to the namespace System.Reflection.AssemblyKeyFileAttribute.
If the key was in the CSP, we would make use of System.Reflection.AssemblyKeyNameAttribute.
Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this file...

We may write this in our code as well, like this...
Imports System.Reflection

Namespace StrongName
Public class Sample
End Class
End Namespace

3) Build your project. Your assembly is now strongly named.
Installing the Shared assembly in GAC...
Go to .NET command interpreter, use the tool gacutil.exe
Type the following...
gacutil /i sampleclass.dll To uninstall it, use... gacutil /u sampleclass.dll Visual Studio.NET provides a GUI tool for viewing all shared assemblies in the GAC.

Folder of GAC: C:\Windows\Assembly OR C:\Winnt\Assembly

What is GAC?
A shared assembly has version constraints. It is stored in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by the .NET runtime. The shared assemblies may be used by many applications. To make an assembly a shared assembly, it has to be strongly named.
To know more on how to share an assembly, create a strongly named assembly
GAC is located at C:\Windows\Assembly OR C:\Winnt\Assembly

Can garbage collector control the activities of a thread?
Garbage Collection
- Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time. The garbage collector runs periodically. It runs through a list of objects that are currently being referenced by an application. All objects that it does not find during this search are ready to be destroyed (using the finalize method) and hence free the memory. However, the runtime gets notified of the object that has been destroyed, only in the next round of the garbage collector's periodic cycle.

In the class System.GC, there is a method called collect( ). This forces the garbage collector to collect all unreferenced objects immediately, thereby giving the developer some control over the garbage collector.
There is a gcConcurrent setting that can be set through the applications's .config file. This specifies whether or not the garbage collector performs its activities on a specified thread or not.
We can view the performance monitor to view the activities of the garbage collector

What is IDisposable interface in .NET?
IDisposable interface
- We implement this interface to a class when we have to work with unmanaged types. For example, an IntPtr member representing an operating system's file handler is actually unmanaged, and in order to destroy it, we make use of the Dispose method by implementing the IDisposable interface. In this case, we override the Finalize method. Note that we make use of Dispose method on those objects which have an uncertain life period, and thus the garbage collector does not finalize them automatically.
We also make use of Dispose method while working with managed code, for example, an object os System.IO.FileStream may have an uncertain life, and in order to dispose it, we use the dispose method. Such types of objects are not accessed by the Garbage Collector's Finalizer.

What is Serialization in .NET? SoapFormatter, BinaryFormatter, XmlFormatter? Serialization - The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.

What is Serialization? What is serializable attribute used for?
Serialization
- The process of converting an object into a stream of bytes. This stream of bytes can be persisted. Deserialization is an opposite process, which involves converting a stream of bytes into an object. Serialization is used usually during remoting (while transporting objects) and to persist file objecst & database objects.
.NET provides 2 ways for serializtion 1) XmlSerializer and 2) BinaryFormatter/SoapFormatter
The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for Remoting. While using XmlSerializer, it is required that the target class has parameter less constructors, has public read-write properties and has fields that can be serialized. The XmlSerializer has good support for XML documents. It can be used to construct objects from existing XML documents. The XmlSerializer enables us to serialize and deserialize objects to an XML format.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize private and public fields of a class. The target class must be marked with the Serializable attribute. On deserialization, the constructor of the new object is not invoked.

The BinaryFormatter has the same features as the SoapFormatter except that it formats data into binary format. The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize. To serialize an object, we pass an instance of the stream and the object to the Serialize method. To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework. For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as DataReaders or TextBox controls. To serialize a class, the class must have the Serializable attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the BinaryFormatter & the SoapFormatter captures both the public & private members of the class. The output using the BinaryFormatter is quite compact, as the information is in binary format, whereas the XmlSerializer format is filled with XML tags. See example below...

Imports System.IOImports System.Runtime.Serialization.Formatters.Binary
Dim colArrayList As ArrayListDim
objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormattercolArrayList = New ArrayList()
colArrayList.Add( "Whisky")
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
objFileStream = New FileStream(MapPath("C:\myArrayList.data"), FileMode.Create)
objBinaryFormatter = New BinaryFormatterobjBinaryFormatter.Serialize(objFileStream, colArrayList)objFileStream.Close()

Here we see that an instance of the file stream (objFileStream) and an instance of the object (colArrayList) is passed to the Serialize method of the BinaryFormatter object (objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-drive.In order to deserialize an object, see the code below…

Dim colArrayList As ArrayListDim objFileStream As FileStreamDim
objBinaryFormatter As BinaryFormatterDim strItem As String
objFileStream = New FileStream( MapPath("myArrayList.data"), FileMode.Open )
objBinaryFormatter = New BinaryFormatter
colArrayList = CType( objBinaryFormatter.Deserialize( objFileStream ), ArrayList )
objFileStream.Close()
For Each strItem In colArrayList
Response.Write( " " & strItem )
Next

Here, CType takes in two parameters, the first parameter is the serialized object in the file stream format, and the second parameter is the desired type. Finally, the page iterates through all the elements of the ArrayList and displays the value of each element.

XmlSerializer does not serialize instances of classes like Hashtable which implement the IDictionary interface.

Serializable - This is a class attribute. When we use this attribute with a class, an instance of this class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized, and the class will act as if it is simply stored in the memory.

What is CAS in .NET?
Code Access Security (CAS)
- CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.) To view codegroups on our system, use the following command on .NET command interpretor... caspol -lg Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent. If we want to trust a particular website giving it full rights to our system...Use caspol. For example, suppose we trust code from www.mydomain.com and we want it have full access to our system, but we want to keep the default restrictions for all other internet sites. To achieve this, we would add a new code group as a sub-group of the 'Zone - Internet' group,
like this: caspol -ag 1.3 -site www.mydomain.com FullTrust To change the permission, we use the -cg attribute.To turn off caspol, use caspol -s off

What is a class attribute in .NET?
Class Attributes
- Is a kind of property attached with a class. It allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[Serializable]
Public Class SampleClass
( ... )

What is a thread? How to use and create a thread in .NET?
Threads
- When we want to run one or more instances of a method, we make use of threading. Suppose we have a method like this...
Private Sub OnGoingProcess()
Dim i As Integer = 1
Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Loop
End Sub

Dim t As Thread
t = New Thread(AddressOf Me.OnGoingProcess)
t.Start()
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread. After the thread is started, you have some control over the state of it by using methods of the Thread object. You can pause a thread's execution by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. If you wanted to slow down the addition of items to the listbox in the example above, place a call to the sleep method in this code:

Private Sub OnGoingProcess()
Dim i As Integer = 1
Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Thread.CurrentThread.Sleep(2000)
Loop
End Sub

You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method. Similar to Sleep and Interrupt are Suspend and Resume. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Lastly, Thread.Abort stops a thread from executing. In our simple example, we would want to add another button on the form that allows us to stop the process. To do this all we would have to do is call the Thread.Abort method as follows:

Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
t.Abort()
End Sub

This is where the power of multithreading can be seen. The UI seems responsive to the user because it is running in one thread and the background process is running in another thread. The cancel button immediately responds to the user's click event and processing stops. The next example shows a rather simple situation. Multithreading has many complications that we have to work out when we program. One issue that we will run into is passing data to and from the procedure passed to the constructor of the Thread class. That is to say, the procedure we want to kick off on another thread cannot be passed any parameters and we cannot return data from that procedure. This is because the procedure wepass to the thread constructor cannot have any parameters or return value. To get around this, wrap our procedure in a class where the parameters to the method are written as fields of the class. A simple example of this would be if we had a procedure that calculated the square of a number:

Function Square(ByVal Value As Double) As Double Return Value * Value End Function To make this procedure available to be used in a new thread we would wrap it in a class: Public Class SquareClass Public Value As Double Public Square As Double Public Sub CalcSquare() Square = Value * Value End Sub End Class

Use this code to start the CalcSquare procedure on a new thread. following code:

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim oSquare As New SquareClass()
t = New Thread(AddressOf oSquare.CalcSquare)
oSquare.Value = 30
t.Start()
End Sub

Notice that after the thread is started, we do not inspect the square value of the class, because it is not guaranteed to have executed once you call the start method of the thread. There are a few ways to retrieve values back from another thread. The easiest way is to raise an event when the thread is complete. We will examine another method in the next section on thread synchronization. The following code adds the event declarations to the SquareClass.

Public Class SquareClass
Public Value As Double
Public Square As Double
Public Event ThreadComplete(ByVal Square As Double)
Public Sub CalcSquare()
Square = Value * Value
RaiseEvent ThreadComplete(Square)
End Sub
End Class

Catching the events in the calling code has not changed much from VB6, you still declare the variables WithEvents and handle the event in a procedure. The part that has changed is that you declare that a procedure handles the event using the Handles keyword and not through the naming convention of Object_Event as in VB6. Dim WithEvents oSquare As SquareClass

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
oSquare = New SquareClass()
t = New Thread(AddressOf oSquare.CalcSquare)
oSquare.Value = 30
t.Start()
End Sub

Sub SquareEventHandler(ByVal Square As Double) _
Handles oSquare.ThreadComplete
MsgBox("The square is " & Square)
End Sub

The one thing to note with this method is that the procedure handling the event, in this case SquareEventHandler, will run within the thread that raised the event. It does not run within the thread from which the form is executing.

What is globalization in .NET?
Globalization
refers to the process with which an application or software is designed and developed so as to make it run across all platforms and all sites with minimum or no modification to the software application. The software is very easy to customize so as to suit to the location-specific conditions and it is also capable of providing information based on the varied inputs and the location-specific operating system.
There are two processes in Globalization and they are customisation or localisation of the application and internationalizing the application codes so as to meet the standards of the local culture and other related matters.
In internationalization process the application code base is same and the efforts will be on jobs such as translating, storing, retrieving and to make the application user friendly for the selected locale. In any given place the culture and the language will always be different and besides this you should also take into account the other factors such as time zone, normal date pattern usage, cultural and language environments, currencies, telephone numbers, and so many other factors that are specific to the locale. In globalization the process of internationalization enables us to remove from the code base and the presentation layer all the contents and make you to use only a single presentation layer and single code base with a common contents that can suit any culture. The internationalization process will aid us to keep all the contents in a common place with an idea of making it easily accessible by the programme codes and the results can easily be populated all over presentation layer and the application with ease and efficiently.

Moreover, the internationalization process also enables you to store the contents and all the collected inputs from the user in a user friendly format and in a highly secured manner without compromising any standards pertaining to the local culture. The internationalization process is one step before any attempt for localising the application to suit to the local needs.
With the help of the localization process of globalization, you can make your application adaptable to the various location specific conditions and it will be easy for you to translate and re-format our application to suit to our new location and that too without changing any of the codes. Further, we can make use of the process for rectifying any of the reported bugs and for fine tuning the application for running efficiently. The globalization process also makes use of the locally prevailing information on culture where the software or the application is to be installed and maintained. The locational details and the language used in that particular area constitute to culture information and for working with any culture based information the namespace concept is utilised and the SystemGlobalization, SystemResources and SystemThreading are the available namespaces in .NET Framework.
Out of the various namespaces, the SystemGlobalization namespace constitute classes that are used to hold information relating to region or country, the local language used, type of calendars, date format used, numbers, currency, etc., all in a meticulously arranged fashion and all these classes are used while developing the globalized (internationalized) applications. We can use advanced globalization functionalities with the assistance of classes such as StringInfo and TextInfo classes and the various functionalities include text element processing and surrogate support systems.
The SystemResources namespace constitutes interfaces and classes that are very helpful for developers and maintenance experts in creating, storing, retrieving, and managing various resources used in the application that are culture and location-specific.
The SystemThreading namespace constitutes interfaces and classes that aid in multithreaded programming. The classes that are used in this type of SystemThreading namespace are also useful in accessing data and for synchronization of thread activities.

What are Generations in Garbage Collector?
Generations in the Garbage Collector is a way of enhancing the garbage collection performance. In .NET, all resources are allocated space (memory) from the heap. Objects are automatically freed from the managed heap when they are no longer required by the application.
When objects are no longer being used by the application, the .NET runtime's garbage collector performs the task of collection, to determine the status of the objects. Necessary operations are performed to relieve the memory, in case the object is no longer in use. This is identified by the GC by examining the metadata of the object. For this, the GC has to know the location of the roots that represent the object. Roots are actually the location of the object on the managed heap. There are two types of memory references, strong & weak. When a root references an object, it is said to be a strong reference as the object is being pointed to by application code. The other type of object, that is not being referenced by the application code is called the weak reference, and this may be collected by the GC. However, this may still be accessed by the application code if required. But for the application to access the weakly referenced object, this has to be converted to a strong reference (and note that this has to be done before the GC collects the weakly referenced object).
So what are Generations in the GC? Its a feature of the GC that enhances its performance. There are 3 Generations...0,1,2.
Generation 0 - When an object is initialized, its in generation 0. These are new objects that have never been played around with by the GC. As and when more objects get created, the process of Garbage Collection is invoked by the CLR.
Generation 1 - The objects that survive the garbage collection process are considered to be in generation 1. These are the old objects.
Generation 2 - As more new objects get created and added to the memory, the new objects are added to generation 0, the generation 1 old objects become older, and so are considered to be in generation 2. Generation 2 is the highest level generation in the garbage collection process. Any further garbage collection process occuring causes the level 1 objects promoted to level 2, and the level 2 objects stay in level 2 itself, as this generation level is the highest level.
So what is the importance & use of the generations process? Its actually the priority the GC gives to objects while freeing objects from the heap. During every GC cycle, the objects in the Generation 0 are scanned first -> Followed by Generation 1 and then 2. This is because the generation 0 objects are usually short term objects, that need to be freed. The newer an object, the shorter its life is. The older an object, longer its life is.
This process also helps in categorizing the memory heap as to where the de-allocation needs to be done first and where next.

How to call COM components from .NET? What is interoperability?
COM components & .NET components have a different internal architecture. For both of them to communicate with each other, inter-operation feature is required, this feature is called interoperability. Enterprises that have written their business solutions using the old native COM technology need a way for re-using these components in the new .NET environment.
.NET components communicate with COM using RCW (Runtime Callable Wrapper (RCW).
To use a COM component,
* Right click the Project & click on Add References.
* Select the COM tab
* Select the COM component
Another way of using a COM component is using the tblimp.exe tool (Type Library Import).
Using the COM component directly in the code may be achieved by using System.Runtime.InteropServices namespace. This contains class TypeLib Converter which provides methods to convert COM classes and interface in to assembly metadata. If the COM component does not have a Type Library, then custome wrappers need to be created. Once the COM wrapper is created, it has to be registered in the registry.

How to call .NET component from COM?
In case a .NET component needs to be used in COM, we make use of COM Callable Wrapper (CCW). Following are the different approaches to implement it:
* Explicitly declare interfaces.
* The second way to create CCW using InteropServices attributes.Here interfaces are created automatically.
Following are different type of class attributes :
None-- No class interface is generated for the class.This is default setting when you do not specify anything.
AutoDispatch-- Interface that supports IDispatch is created for the class. However, no type information is produced.
AutoDual-- A dual interface is created for the class. Typeinfo is produced and made available in the type library.
In below source code we have used the third attribute.

Imports System.Runtime.InteropServices
_
Public Class ClsCompliant
End Class

Other than class attributes defined up there are other attributes with which you can govern other part of assembly.Example “GuidAttribute” allows you to specify the GUID,”ComVisibleAttribute “ can be used to hide .NET types from COM etc

Most Wanted in ASP.NET!

How to redirect a page to another page?
The Response object has a famous Redirect method that is used most widely to transfer a web page visitor from one page to another page.
Syntax of Response.Redirect ...

Response.Redirect("DestinationPage.aspx")

There is another famous method called Transfer method of the Server object.
Syntax of Server.Transfer ...

Server.Transfer("DestinationPage.aspx")

What is the difference between Server.Transfer and Response.Redirect?
Both "Server" and "Response" are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is an underlying difference.
//Usage of Server.Transfer & Response.Redirect
Server.Transfer("Page2.aspx");
Response.Redirect("Page2.aspx");
The Response.Redirect statement sends a command back to the browser to request the next page from the server. This extra round-trip is often inefficient and unnecessary, but this established standard works very well. By the time Page2 is requested, Page1 has been flushed from the server’s memory and no information can be retrieved about it unless the developer explicitly saved the information using some technique like session, cookie, application, cache etc.
The more efficient Server.Transfer method simply renders the next page to the browser without an extra round trip. Variables can stay in scope and Page2 can read properties directly from Page1 because it’s still in memory. This technique would be ideal if it wasn’t for the fact that the browser is never notified that the page has changed. Therefore, the address bar in the browser will still show “Page1.aspx” even though the Server.Transfer statement actually caused Page2.aspx to be rendered instead. This may occasionally be a good thing from a security perspective, it often causes problems related to the browser being out of touch with the server. Say, the user reloads the page, the browser will request Page1.aspx instead of the true page (Page2.aspx) that they were viewing. In most cases, Response.Redirect and Server.Transfer can be used interchangeably. But in some cases, efficiency or usability may be the deciding factor in choosing.

How to pass values between pages?
There are several methods to pass values from one page to another page. Described below are few methods to pass values between pages:
QueryString - The QueryString method of passing values between web pages is one of the oldest methods of passing values between pages. A variable value is properly encoded before it is placed on a querystring. This is to make sure that characters that cause problems (like symbols and spaces) are encoded correctly. See the code below to see how QueryString functionality works.
//Code in InitialPage.aspx
String sString;
sString = Server.UrlEncode("string in InitialPage.aspx");
Response.Redirect("DestinationPage.aspx?Value=" & sString);

//Code in DestinationPage.aspx reads the QueryString
String sString;
sString = Request.QueryString("Value");
Response.Write("Your name is " & sString);

The data in the DestinationPage.aspx in the URL looks like this...

http://www.dotnetuncle.com/DestinationPage.aspx?Value=dotnetUncle

Context - The context object is used to send values between pages. Its similar to the session object, the difference being that, the Context object goes out of scope when the page is sent to a browser. Example code below shows how to use Context object.

'InitialPage.aspx stores value in context before sending it
Context.Items("MyData") = "dotnetuncle";
Server.Transfer("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's context
String sString;
sString = Context.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

Session - The session object is used to persist data across a user session during the user's visit to a website. It is almost same as the Context object. When we use Response.Redirect, it causes the Context object to go away, so rather the Session object is used in such a scenario. Session object uses more of server memory than a context object. Example code below shows how to use Session object.

'InitialPage.aspx stores value in session before sending it
Session.Items("MyData") = "dotnetuncle";
Response.Redirect("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's session
String sString;
sString = Session.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

You may notice above, I have used Response.Redirect with session object, and server.transfer with a context object.

Application, Cache, Session - objects are used to store global variables.

How to store global variables?
Global variables should always be used with caution. They are the best means of storing data that has to be accessed anywhere. The most common ways of accessing global variables in ASP.NET are by using Application, Cache, and Session objects.
Application - Application objects are application level global variables, that need to be shared for all user sessions. Thus, data specific to a user should'nt be saved in application objects. While using application objects, the objects are locked so that multiple page requests cannot access a specific application object. Below is a code example for usage of application object...
Application.Lock();
Application("UserData") = "dotnetuncle";
Application.UnLock();
Response.Redirect("DestinationPage.aspx");

//DestinationPage.aspx gets the value from the Application State
String sString = Application("UserData").ToString();
Cache - The cache object is similar to the application object in scope, however, it does not need any explicit locking and unlocking. Code below shows usage of Cache object...

Cache("Userdata") = "dotnetuncle";
Response.Redirect("DestinationPage.aspx");

//Destination.aspx retrieves the value from Cache object
String sString = Cache("Userdate").ToString();

The cache object also shares data across all user sessions. The cache object has features like it can automatically expire cached content after specified time periods or once memory consumption has reached a maximum.
Session - The session object is used to store the data specific to a user for the entire length of a user's visit to a website. Below is a code that shows usage of the session object in ASP.NET ...
//InitialPage.aspx stores the user’s credentials in Session state
Session("UserName") = txtUserName.Text;
Server.Transfer("DestinationPage.aspx");

//DestinationPage.aspx gets the user’s name from Session state
String sString = Session("UserName").ToString();

ASP.NET stores session values in the server memory. If there are plenty of active user's of a website, then the memory consumption on the server increases by leaps. Because of this reason, large websites use very less Session Variables. Session state can be configured to be automatically stored in a SQL Server database, or it can be configured to be stored centrally in a state server within a server farm. By default, a user’s session ends 20 minutes after their last page request and their data goes out of scope, freeing it from memory. In case user information is to be tracked by a large website, then a oookie is preferred.
Cookie - A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory.

What is a cookie? Limitations of cookie? Permanent cookie?
Cookie
- A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory. It is actually a small text file which is created by the broswer on the hard disk of the user. It is actually a piece of information in the form of text strings. A web server sends a cookie to a user (client browser) and then the browser stores it.
A cookie is used to store information of a user & information about a user's preferences. How does the cookie works? - When a user visits a site, say www.amazon.com, and creates a profile out there, the server sends an ID (basically an ID to track this user) and saves the ID through the user's browser in the form of a cookie on the user's system. When the user revisits this site, the website tracks the user's system for the existence of any cookie, and in case it finds a cookie, it customizes the site based on the user's settings and preferences.
Now lets talk about how to create a cookie in ASP.NET. It is pretty simple. There is a class in the System.Web namespace by the name HttpCookie. This class may be used to easily create a cookie on the user's system. Below is a code sample on how to use a cookie in ASP.NET ...
//Creating a cookie HttpCookie sampleCookie = new HttpCookie("UserColorSetting");
sampleCookie.Values.Add("Background", txtBackgroundColor.Text);
sampleCookie.Expires = #12/31/2010#; Response.Cookies.Add(sampleCookie);

//Getting a cookie value from the user's computer
String sGetCookie;
sGetCookie = Request.Cookies("UserColorSetting")("Background").ToString();

Limitations of Cookies - Cookies are meant for infrequent storage of small pieces of information. They are not meant as a normal communication or mechanism. Note that web browsers are not required to save more than 300 cookies total, nor more than 20 cookies per web server (for the entire server, not just for the page or site on the server), nor to retain more than 4 kilobytes of data per cookie (both name and value count towards this 4 kilobyte limit). The biggest limitation of these is the 20 cookies per server limit, and so it is not a good idea to use a different cookie for each variable that has to be saved. Rather save a single cookie containing a lot of information

What is the role of the ASP.NET worker process? What is aspnet_wp.exe?
For faster execution of ASP.NET applications, that are primarily based to be hosted on IIS servers, the aspnet_wp.exe comes into picture. This file (aspnet_wp.exe) is actually the ASP.NET worker process. The worker process is introduced to actually share the load on the IIS, so that application domains and other services may be maintained by a single worker process.
The aspnet_wp.exe worker process is a part of the Microsoft ASP.NET framework, and it is responsible for most of the technical processes in the ASP.NET framework. There may be multiple instances of ASP.NET worker process running on IIS 6 (a process running as inetinfo.exe), depending on multiple application pools. The worker process handles all the requests passed to the ASP.NET framework, so we may say that its actually the main engine that handles all requests pertaining to ASPNET. For example, when a request for an .aspx page is recieved by the IIS server, the dll called aspnet_isapi.dll passes this request to the aspnet_wp.exe worker process.

Explain the page life cycle in ASP.NET 2.0
ASP.NET 2.0 Page Life Cycle
- The lifetime of an ASP.NET page is filled with events. A series of processing steps takes place during this page life cycle. Following tasks are performed:
* Initialization
* Instantiation of controls
* Restoration & Maintainance of State
* Running Event Handlers
* Rendering of data to the browser
The life cycle may be broken down into Stages and Events. The stages reflect the broad spectrum of tasks performed. The following stages take place
1) Page Request - This is the first stage, before the page life cycle starts. Whenever a page is requested, ASP.NET detects whether the page is to be requested, parsed and compiled or whether the page can be cached from the system.
2) Start - In this stage, properties such as Request and Response are set. Its also determined at this stage whether the request is a new request or old, and thus it sets the IsPostBack property in the Start stage of the page life cycle.
3) Page Initialization - Each control of the page is assigned a unique identification ID. If there are themes, they are applied. Note that during the Page Initialization stage, neither postback data is loaded, nor any viewstate data is retrieved.
4) Load - If current request is a postback, then control values are retrieved from their viewstate.
5) Validation - The validate method of the validation controls is invoked. This sets the IsValid property of the validation control.
6) PostBack Event Handling - Event handlers are invoked, in case the request is a postback.
7) Rendering - Viewstate for the page is saved. Then render method for each control is called. A textwriter writes the output of the rendering stage to the output stream of the page's Response property.
8) Unload - This is the last stage in the page life cycle stages. It is invoked when the page is completely rendered. Page properties like Respone and Request are unloaded.
Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.
PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To set master pages dynamically. Gets and Sets profile propety values.
Init - Raised after all controls are initialized, and skin properties are set.
InitComplete - This event may be used, when we need to be sure that all initialization tasks are complete.
PreLoad - If processing on a control or a page is required before the Load event.
Load - invokes the OnLoad event on the page. The same is done for each child control on the page. May set properties of controls, create database connections.
Control Events - These are the control specific events, such as button clicks, listbox item selects etc.
LoadComplete - To execute tasks that require that the complete page has been loaded.
PreRender - Some methods are called before the PreRenderEvent takes place, like EnsureChildControls, data bound controls that have a dataSourceId set also call the DataBind method.
Each control of the page has a PreRender event. Developers may use the prerender event to make final changes to the controls before it is rendered to the page.
SaveStateComplete - ViewState is saved before this event occurs. However, if any changes to the viewstate of a control is made, then this is the event to be used. It cannot be used to make changes to other properties of a control.
Render - This is a stage, not an event. The page object invokes this stage on each control of the page. This actually means that the ASP.NET server control's HTML markup is sent to the browser.
Unload - This event occurs for each control. It takes care of cleanup activities like wiping the database connectivities.

How to store values between postbacks in ASP.NET? What is viewstate in ASP.NET?
When a postback happens (i.e. when a form is submitted to a server), the variable values that are set in the code-behind page are erased from the memory of the client system. This concept would be different from what happens in Windows-based applications, where the variable variables persist in memory until they are freed from the memory either by the garbage collector, or by specific codes like dispose or finalize.
In web applications, variable values simply get erased. But it is very simple to persist these values. They may be persisted using the Viewstate object. Before the postback is invoked, the variable's value is saved in a viewstate object. In the recieving page, the viewstate's value may be retrieved back. See example code below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();
Note that the viewstate value is saved and then passed to the next page by ASP.NET in the form of a hidden variable. Ideally, big values like datasets should not be saved in viewstate as they may tend to slow down the performance of the web page.
Apart from the viewstate object, values may also be sent across postbacks between pages using Application, Session and Cache objects.



What is a server control in ASP.NET?
A server control in ASP.NET is a control that has the runat="server" attribute. The component is processed on the server, and its HTML equivalent stream is passed to the browser. Note that all server controls inherit from the System.Web.UI.Control class. The server side controls may be dragged to a web page from the standard toolbox. Note that HTML controls are not server side controls, but they may behave so if the runat="server" attribute is added to their source.

What is viewstate in ASP.NET?
Viewstate
object is used to persist data of variables across postbacks. It even existed in classic ASP. In ASP.NET, a variable's value is assigned to a a viewstate object and then this is passed as a hidden variable and then may be retrieved by a page after a postback. See the example below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();

Note that Viewstate object's value is accessible only at page level. This means that if a viewstate is created at page1.aspx, then it may be used only within page1.aspx after the postback, and cannot be used by any other page. To know how to pass values from one page to another, see below:

How to pass values between pages?
There are several methods to pass values from one page to another page. Described below are few methods to pass values between pages:
QueryString - The QueryString method of passing values between web pages is one of the oldest methods of passing values between pages. A variable value is properly encoded before it is placed on a querystring. This is to make sure that characters that cause problems (like symbols and spaces) are encoded correctly. See the code below to see how QueryString functionality works.

//Code in InitialPage.aspx
String sString;
sString = Server.UrlEncode("string in InitialPage.aspx");
Response.Redirect("DestinationPage.aspx?Value=" & sString);

//Code in DestinationPage.aspx reads the QueryString
String sString;
sString = Request.QueryString("Value");
Response.Write("Your name is " & sString);

The data in the DestinationPage.aspx in the URL looks like this...

http://www.dotnetuncle.com/DestinationPage.aspx?Value=dotnetUncle

Context - The context object is used to send values between pages. Its similar to the session object, the difference being that, the Context object goes out of scope when the page is sent to a browser. Example code below shows how to use Context object.

'InitialPage.aspx stores value in context before sending it
Context.Items("MyData") = "dotnetuncle";
Server.Transfer("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's context
String sString;
sString = Context.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

Session - The session object is used to persist data across a user session during the user's visit to a website. It is almost same as the Context object. When we use Response.Redirect, it causes the Context object to go away, so rather the Session object is used in such a scenario. Session object uses more of server memory than a context object. Example code below shows how to use Session object.

'InitialPage.aspx stores value in session before sending it
Session.Items("MyData") = "dotnetuncle";
Response.Redirect("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's session
String sString;
sString = Session.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

You may notice above, I have used Response.Redirect with session object, and server.transfer with a context object.

Which namespace does a webpage belong? What is the base class of a webpage?
System.Web.UI.Page is the base class from which all web pages in ASP.NET derive from.

How to store information about a user's locale in ASP.NET? What is localization?
Localization
is the feature of ASP.NET through which an application may be localized for a specific location. There are built-in mechanisms in .NET to allow localization process. The concept of localization is achieved in .NET as .NET is based on Unicode, thus it allows multiple characters of regions across the globe to be sent across in applications.
In .NET, the concept of localization is achieved using the System.Globalization namespace. A class named CultureInfo is used to localize .NET objects in the web applications. The functions provided in the globalization namespace work in tandem with the browswer's culture encoding properties. In order to set the culture encoding of a web application, changes may simply be done in the web.config file.





Here, the default culture is set to Hindi (hi-IN). However, the rest of the web application will use UTF8 character encoding. The default UI culture is "en" by default. Now in order to render different locality specific characters for different locations, different folders with their own Web.config files are created. Each of this folder will cater to a location. Note that in ASP.NET, a web.config file is allowed on any folder, this web.config file will override any settings provided in the web.config of any of its parent folder.

This is how locale specific directories are created for a site. Further note that culture settings may be set at page level as well. This is done using the @Page directive by setting its culture attribute to the desired culture.

<%@ Page Culture="hi-IN" UICulture="hi" ResponseEncoding="utf-8"%>

Instances of the CultureInfo class may also be created in code, to set the culture of a page through code.

What are validation controls in ASP.NET? How do validation controls work? What are validation groups in ASP.NET 2?
Validation controls in ASP.NET are server side controls that validate input values client-side. Sounds strange? Well, the best approach to validate any input value is to validate it client-side to avoid any postback and load to the server. This approach is followed to reduce the load on the server.
ASP.NET validation controls greatly improve the perfomance of a web application and may be used by web developers to reduce plenty of code that they used to write previously to validate input values using javascript or vbscript.
Input validations improvise security of a web application, by preventing SQL Injection attacks.
There are 6 validations controls in both ASP.NET 1.1 and ASP.NET 2.0
1) RequiredFieldValidator - as the name suggests, this control makes sure that the input box is not left blank.
2) CompareValidator - This control validates values in two controls, and checks for equality
3) RangeValidator - This validation control makes sure that the value entered in the control falls within a range specified. This specification may be done using its properties.
4) RegularExpression - Based on a regular expression, values entered in an input box must match the ones specified by this control's RegulareExpression property
5) CustomValidator - This type of validator control may be customized & created by a developer as per need
6) ValidationSummary - This control may be used to show the summary of the information gathered using rest of the other validation controls

To use a validation control, set a validation control on a form. Associate it with a server control by using its ControlToValidate property. Note that the server control has a property called CausesValidation and this is set to true for the validation control to trigger. This property is true by default for every server control. The validation control also has an ErrorMessage property that is assigned some text to explain what the error is, in case the validation control is trigerred. The validation control actually calls a client-side script that comes with ASP.NET, and this script does the job of validation for us. All this validation is done client-side.
Suppose we want to use the RequiredFieldValidator control so that a textbox is'nt left blank, for this, see the inline code below...
Please Enter Some Text

Code used for RequiredFieldValidator used above


The Page.IsValid property of the page is TRUE only if there are no validation errors returned.
Validation controls are supported by Internet Explorer, Firefox and Opera.
ASP.NET 2.0 provides a method to allow multiple sets of controls that may be grouped together into a validation group. The purpose of this approach makes it easy to invoke validation checks on specific server controls and not all ot them who have an associated validation control.

What is global.asax in ASP.NET? Application_start, Session_start?
The global.asax file is used to add application level logic & processing. Note that the global.asax does not handle any UI related processing, nor does it process individual page level requests. It basically controls the following events...
Application_Start
Application_End
Session_Start
Session_End
Note that in Visual Studio 2003 automatically creates this file for every web application, but in Visual Studio 2005, this file has to be added to the web project specifically.
Code in the global.asax is compiled when the web appication is built for the first time. The application level code and variables may be declared in Application_Start. Similarly, session level code & variables may be declared in Session_Start event. Application level events are for the entire application, and may be used for any user, while Session level events are user specific for a length of a session.

What is an HTTP handler in ASP.NET? Can we use it to upload files? What is HttpModule?
The HttpHandler and HttpModule are used by ASP.NET to handle requests. Whenever the IIS Server recieves a request, it looks for an ISAPI filter that is capable of handling web requests. In ASP.NET, this is done by aspnet_isapi.dll. Same kind of process happens when an ASP.NET page is trigerred. It looks for HttpHandler in the web.config files for any request setting. As in machine.config default setting, the .aspx files are mapped to PageHandlerFactory, and the .asmx files are mapped to the WebServiceHandlerFactory. There are many requests processed by ASP.NET in this cycle, like BeginRequest, AuthenticateRequest, AuthorizeRequest, AcquireRequestState, ResolveRequestCache, Page Constructor, PreRequestHandlerExecute, Page.Init, Page.Load, PostRequestHandlerExecute, ReleaseRequestState, UpdateRequestCache, EndRequest, PreSendRequestHeaders, PreSendRequestContent.
Yes, the HttpHandler may be used to upload files.
HttpModules are components of .NET that implement the System.Web.IHttpModule interface. These components register for some events and are then invoked during the request processing. It implements the Init and the Dispose methods. HttpModules has events like AcquireRequestState, AuthenticateRequest, AuthorizeRequest, BeginRequest, Disposed , EndRequest, Error, PostRequestHandlerExecute, PreRequestHandlerExecute, PreSendRequestHeaders, ReleaseRequestState, ResolveRequestCache, UpdateRequestCache

What is a session in ASP.NET? Different ways to maintain session?
Session
- The session object is used to store the data specific to a user for the entire length of a user's visit to a website. Below is a code that shows usage of the session object in ASP.NET ...
//InitialPage.aspx stores the user’s credentials in Session state
Session("UserName") = txtUserName.Text;
Server.Transfer("DestinationPage.aspx");

//DestinationPage.aspx gets the user’s name from Session state
String sString = Session("UserName").ToString();

What is the @Register directive used for? What is the purpose of @Register directive in ASP.NET?
Directives
in ASP.NET are used to set attributes for a page. The @Register directive is a directive used to register user defined controls on a web page. A user created server control has an ascx extenstion. These controls inherit from the namespace System.Web.UI.UserControl. This namespace inherits from the System.Web.UI.Control.
A user control may be embedded in an aspx web page using the @Register directive. A user control cannot be executed on its own independently, but may be registered on a web page and then used out there. Below is the syntax for registering an @register directive in an aspx page in ASP.NET

<%@ Register TagPrefix="UC1" TagName="UserControl1" Src="UserControl1.ascx" %>

The TagPrefix attributes is used to specify a unique namespace for the user control. The TagName is a name used to refer a user control uniquely by its name. Say we want to use this control in a webpage, we may use the code below...

How to implement a web farm and a web garden? Whats a web farm and a web garden in ASP.NET? What is the difference between a web farm and web garden in ASP.NET?
So what is a web farm. A Web Farm is a setup of a website across multiple servers.
A Web Garden is a setup of a website on a single server with multiple processors. To set a a multi-server web application in ASP.NET, the following link may be read

HOW TO: Set Up Multi-Server ASP.NET Web Applications and Web Services
SUMMARY

This step-by-step article discusses how to set up multi-server ASP.NET Web Applications and Web services. For most uses of ASP.NET, a single server can handle all requests in a timely manner. However, many environments must deploy multiple servers to handle consistently high volumes of traffic, to support processor-intensive applications, to respond to sudden bursts in traffic, or to meet redundancy requirements
In the simplest form, you can deploy Web pages that consist only of static HTML pages and images in a multi-server configuration by copying the files to multiple Web servers and then configuring a load balancing mechanism to distribute requests between the Web servers.

As the Web site complexity increases, the difficulty of synchronizing files and configurations between the servers also increases. Dynamic sites require multiple servers to have access to a single database and to share state information among themselves. This article describes how to design multi-server ASP.NET solutions that include databases and sessions.

Manage State

As a user navigates through an ASP.NET site, ASP.NET stores information about the user's session state. The exact information that is stored in the session varies by application, but may include the user’s name, preferences, and shopping cart information.
By default, ASP.NET stores session information in the server memory. This configuration is known as in process. Although this configuration provides the best performance possible, you lose the session information if you restart the ASP.NET server. Additionally, in multi-server architectures, a single user’s request can be sent to a different server. A user may start a session at one server, but later requests are sent to a different in-process server. This results in a new session being created for that user and all earlier information that was stored in the session is lost.
ASP.NET provides two solutions for sharing state information between multiple servers: the ASP.NET State Server service, and Microsoft SQL Server. You can use either of these solutions to store state information between server restarts, and to allow users to move between servers during a single session

Synchronize Configuration and Content

A Web site’s security, performance, and many other aspects of its behavior are defined by the configuration of the Web server. Multi-server sites must have the configuration synchronized between all the servers to provide a consistent experience to users whose requests are sent to different Web servers. ASP.NET makes it simple to synchronize configuration between multiple servers because all configuration information is stored in the virtual server’s path as XML files. These files have a .config file name extension.
You can copy configuration files to servers by using any standard file copy or synchronization method, including DFS, the File Replication service, and Microsoft Application Center 2000. The following batch file will work in environments where each Web server has the virtual server root folder shared as wwwroot$:

XCOPY \\source-server\wwwroot$ \\destination-server#\wwwroot$ /D /E /O /X

When you deploy configuration information and ASP.NET content to multiple servers, it is critical to deploy the content from a single staging server to all production servers at the same time. This reduces the chance of problems occurring when a user’s requests are sent to different servers. Microsoft recommends that all configuration and content updates occur on the staging server. Ideally, this staging server does not receive requests from users. It is dedicated to the task of testing and deploying new content.

When you replicate updated .config files to a Web server, that Web application automatically restarts.

Note If you put assemblies in the Global Assembly Cache, you cannot replicate them by using file synchronization.

Other Tasks

Besides configuring state management and content synchronization, you must perform the following tasks to deploy a multi-server ASP.NET solution. These tasks are not specific to ASP.NET.

Request distribution: Incoming HTTP requests must be distributed among all servers by using a mechanism such as round-robin DNS, Microsoft Application Center 2000, or a third-party load distribution device.

Log aggregation: Before you process HTTP usage logs, it is a good idea to combine the logs to create a single log that includes requests sent to all systems.

Monitoring: To detect problems that affect a single server or the whole site, you must monitor both the external URL for the site and the URLs for each of the Web servers.

Centralized database: Web applications that use a database must have a single database that is shared between multiple Web servers. In environments that require no single point of failure, cluster the database server.

Can dataset be stored in a viewstate?
Yes, a dataset may be stored in a viewstate. However, a viewstate is passed to the server as a hidden variable. Precaution should be taken that the dataset size is not too big, otherwise such an activity will take a toll on both the client and server system resources, and ultimately slow down rendering of the data on the client system. Also note that the viewstate data may not be sent to another aspx page, as thats a limitation of a viewstate object.

How to set view state for a server control? Enableviewstate property?
The enableviewstate property of a server control indicates whether the server control persists its viewstate. It also controls the viewstate behavior of the child controls within it.
So what is Viewstate? - Viewstate is the property of a server control that groups all the other property values of the control, so that the entire set of property values is preserved across multiple HTTP requests. The enableviewstate property when set to true, makes the viewstate property persist all the other property values.
How does viewstate work? - The viewstate values are passed as an HTML hidden input element when HTTP requests are invoked. To see how a viewstate variable's value looks like, right click any aspx page and click view source, you will find something like this...

type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEw.. .. .. .. 2FzcF9hc3AubmV0LmFzcHgfB=="

An instance of the StateBag class is created to store the property values.
There are scenarios when a Viewstate is set to false. For example, say a database request is loaded to a server control, then the size of the database values may be humongous, for which the Viewstate is set to false.
Example of setting viewstate of a server control ...

What is smart navigation?
Before explaining what smart navigation is, let me point out that Smart Navigation is obsolete in .NET 2.0. It works with 1.1 & versions before it. The SetFocus and MaintainScrollPositionOnPostBack are used instead
Smart Navigation basically enhances a web pages' performance by doing the following:

* It eliminates the flash caused during navigation
* It persists element focus during postbacks
* It persists scroll position during postbacks between pages
* It retains the lasts page information in the history of the browser

I suggest not to use SmartNavigation because it does not work with many browsers.

The C# Ocean!

What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.
In VB.NET, the equivalent of protected internal is protected friend.
The access of this modifier is limited to the current assembly or the types derived from the defining class in the current assembly.

Explain the access specifiers Public, Private, Protected, Friend, Internal, Default
The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifiers.
1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.
4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.

Can multiple data types be stored in System.Array?
So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.
An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array).

A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#...

int[] testIntArray = new int[4] { 2, 3, 4, 5 };
Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };

Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See code example below written in VB.NET... Dim allTypes As Object() = New Object() {}

'In this kind of scenario, the performance may tend to slow down, as data conversions may take place.
'In case a value type is converted to reference type, then boxing and unboxing occurs

Dim studentTable(2) As Object
studendTable(0) = "Vishal Khanna"
studentTable(1) = 28
studentTable(2) = #9/1/1978#

'To get these values of these varying datatypes, their values are converted to their original data type

Dim myAge As Integer = CInt(studentTable(1))
Dim myBirthDay as Date = CDate(studentTable(2))

What is the difference between value type and reference type? Can a value type contain NULL values?
In simple words, all value based types are allocated on the stack, while all reference based types are allocated on the heap. What does this mean? A value type contains the actual value. A reference type contains a reference to the value. When a value type is assigned to another value type, it is copied. When a reference type is assigned to another reference type, a reference is assigned to the value.
By saying stack, we mean things are kept one on top of the other. We keep track of each value at the top. By saying heap, we mean things are kept in a mashed order. We keep track of each value by its address, that is referenced by a pointer to it.
All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in System.Object, the base class for all objects which is a reference type itself.
Data types like integers, floating point numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes, Strings, Arrays are examples of Reference Types.
A value type may not contain NULL values. Reference types may contain NULL values.
It is not possible to derive new types from Value Types. This is possible in Reference types. However, Value Types like Structures can implement interfaces.

How to sort array elements in descending order in C#?
Elements of an array may not be sorted by default. To sort them in descending order, the Sort() method is first called. Next, to descend the order, call the Reverse() method.

Whats the use of "throw" keyword in C#?
The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically...
class SomeClass
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division Occured");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception - Divide by Zero" );
}
}
}

Can we put multiple catch blocks in a single try statement in C#?
Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#.

class ClassA
{
public static void Main()
{
int y = 0;
try
{
val = 100/y;
Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ex)
{
Console.WritLine("Some Exception" );
}
finally
{
Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}
}

How to achieve polymorphism in C#?
In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.

What is polymorphism?
Polymorphism
means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.

Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading


How to achieve inheritance in C#?
When a class derives features of another class, this feature is called Inheritance.

What is inheritance?
Inheritance
- is the concept of passing the traits(behaviour) of a class to another class.
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon. (Reference)

Compare Session state and Viewstate in .NET?
Session state
is the feature of ASP.NET based web applications using which values of a variable may be persisted and then posted to another page.
Viewstate property of a page or a control, or a viewstate object for a variable value, may also be created to persist its value across a postback. However, the viewstate value are for page level, i.e. they cannot be posted across to another page.
The datagrid or the gridview has a property called AutoGenerateColumns. Make this property false. Once false, the columns may then be added to the gridview manually.

What is viewstate in ASP.NET?
Viewstate
object is used to persist data of variables across postbacks. It even existed in classic ASP. In ASP.NET, a variable's value is assigned to a a viewstate object and then this is passed as a hidden variable and then may be retrieved by a page after a postback. See the example below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();

Note that Viewstate object's value is accessible only at page level. This means that if a viewstate is created at page1.aspx, then it may be used only within page1.aspx after the postback, and cannot be used by any other page

How to add gridview/datagrid columns manually? Autogenerate in .NET?
The datagrid (of ASP.NET 1.1) and gridview (of ASP.NET 2.0) has a property called AutoGenerateColumns. This property is set to false. After this, columns may be set manually. Sample source below...










">

How to add a ReadOnly property in C#?
Property
- A property is an entity that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface. We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set. See code below to set a property as ReadOnly. If a property does not have a set accessor, it becomes a ReadOnly property.

public class ClassA
{
private int length = 0;
public ClassA(int propVal)
{
length = propVal;
}
public int length
{
get
{
return length;
}
}
}


How to prevent a class from being inherited? Sealed in C#?
In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...

sealed class ClassA
{
public int x;
public int y;
}

No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...

class DerivedClass: ClassA {} // Error

How to inherit the class, but not the method inside it in C#? What is a sealed method in C#? Can a method in C# be sealed? How to create a sealed method in C#?
If a method is not to be inherited, but the class is, then the method is sealed. It becomes a sealed method of a class. It is important to note here that in C#, a method may not be implicitly declared as sealed. This means that a method cannot be sealed directly. A method in C# can be sealed only when the method is an overriden method. Once the overriden method is declared as sealed, it will not be further overriding of this method. See code sample below, where an overriden method is sealed.

class SomeClass
{
public int a;
public int b;

public virtual void SomeMethod()
{
Console.WriteLine("This is a virtual method");
}
}
class SomeClass : DerivedClass
{
public override sealed void SomeMethod()
{
Console.WriteLine("This is a sealed method");
}
}

Can we inherit multiple interfaces in C#?
Yes. Multiple interfaces may be inherited in C#.
Note that when a class and multiple interfaces are to be inherited, then the class name should be written first, followed by the names of the interfaces. See code example below, on how to inherit multiple interfaces in C#.

class someclass : parentclass, IInterface1, IInterface2
{
//...Some code in C#
}

What are the different ways of overloading methods in C#? What is function overloading in C#?
Before knowing the different methods of overloading in C#, lets first clear out what exactly overloading is. Overloading is the OOPs concept of using a method or a class in different styles by modifying the signature of the parameters in it. To know more on overloading,
In order to achieve overloading, there may be several techniques applied. There are different types of overloading like Operator Overloading, Function Overloading etc.
Function overloading may be achieved by changing the order of parameters in a function, by changing the types passed in the function, and also by changing the number of parameters passed in a function. See code sample below to see types of overloading.

//Define a method below
public void fnProcess(int x, double y)
{
......
}
//change the order of parameters
public void fnProcess(double x, int y) {
//.......Some code in C#
}
//Similarly, we may change the number of parameters in fnProcess
//and alter its behaviour

What is Overloading? What is Overloads? What is Overload?
Overloading
- is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.
The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.
Overloading is a way through which polymorphism is achieved

How to call a specific base constructor in C#?
What is a Constructor? - It is a method that gets invoked when an instance of a class is created. In case a class has plenty of constructors, i.e. there are plenty of overloaded constructors, in such a scenario, it is still possible to invoke a specific base constructor. But there is a special way, as explicit calls to a base constructor is not possible in C#. See code below:

public class dotnetClass
{
public dotnetClass()
{
// The constructor method here
}
// Write the class members here
}

//Sample code below shows how to overload a constructor
public class dotnetClass
{
public dotnetClass()
{
// This constructor is without a parameter
// Constructor #1
}

public dotnetClass(string name)
{
// This constructor has 1 parameter.
// Constructor #2

}
}

This constructor gets executed when an object of this class is instantiated. This is possible in C#. Calling a specific constructor will depend on how many parameters, and what parameters match a specific constructor. Note that a compile time error may get generated when 2 constructors of the same signature are created.
We may make use of the this keyword and invoke a constructor. See code example below.

this("some dotnet string");
//This will call Constructor #2 above

What is the use of the base keyword. Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor.

public class dotnetClass
{
public dotnetClass()
{
// The 1st base class constructor defined here
}

public dotnetClass(string Name)
{
// The 2nd base class constructor defined here
}
}

public class dotnetderivedclass : dotnetClass
// A class is being inherited out here
{
public dotnetderivedclass()
{
// dotnetderivedclass 1st constructor defined here
}

public dotnetderivedclass(string name):base(name)
{
// dotnetderivedclass 2nd constructor defined here
}
}

Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows:
public dotnetClass() method -> public dotnetderivedclass() method

The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it.

What are generics in C#?
Generics
in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared. The generics feature in C# has been introduced with version 2.0 of the .NET Framework. Using generics, a class template may be declared that may follow any type as required at runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this generic class.

Generics (C# Programming Guide)

Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

C#

// Declare the generic class
public class GenericList
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();
 
        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();
 
        // Declare a list of type ExampleClass
        GenericList list3 = new GenericList();
    }
}

Generics Overview

· Use generic types to maximize code reuse, type safety, and performance.

· The most common use of generics is to create collection classes.

· The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.

· You can create your own generic interfaces, classes, methods, events and delegates.

· Generic classes may be constrained to enable access to methods on particular data types.

· Information on the types used in a generic data type may be obtained at run-time by means of reflection.

ADO.NET - Behind the scenes!

What is ADO.NET?
ADO.NET
is a part of the Microsoft .NET Framework. This framework provides the set of classes that deal with data communication between various layers of the software architecture and the database. It provides a continious access to different data source types such as SQL Server versions 7, 2000, 2005. It also provides connectivity options to data sources through OLE DB and XML. Connectivity may be established with other databases like Oracle, MySQL etc. as well.
ADO.NET has the ability to separate data access mechanisms, data manipulation mechanisms and data connectivity mechanisms.
ADO.NET introduces along with it the disconnected architecture. In a disconncted architecture, data may be stored in a DataSet. It contains providers for connecting to databases, commands for execution and retrieval of results.
The classes for ADO.NET are stored in the DLL System.Data.dll.

What is a connection object in ADO.NET? How to connect to a database in .Net?
A Connection object in ADO.NET is used to establish a connection between a program (the program may be a windows page, a web page, a windows service, a web service etc.) and the database. The connection is open just long enough to get or update data. By quickly opening, then closing a connection, the server resources are used as little as possible. See code below on how to open a connection between UI and database...

'Code below in VB.NET ...
Dim objectConn as SqlClient.SqlConnection
Dim strConn as String
Try
'First, create a connection object
objectConn=New SqlClient.SqlConnection()

'Next, build the Connection String
strConn &="Data Source=(local
strConn &="Initial Catalog=DatabaseName;"
strConn &= "User ID=admin;"
strConn &= "Password=;"

'Note here that the connection string may also be passed as a parameter
'to the connection string object during instantiation

objectConn.ConnectionString = strConn
objectConn.Open() 'Open the Connection

'The connection is now open
'Write your vb.net code here for operations on the database
objectConn.Close()

Catch Ex As Exception
MessageBox.Show(Ex.Message)
End Try

What are Connection Strings - A connection string has a group of semi-colon-separated attributes. Every .Net Data Provider connection string looks different, depending on the type of .NET Data Provider you need to use and which attributes are set for each different type of database system. An example, the connection string below is an example of what you use to connect to a local SQL Server. See that every parameter is separated by a semicolon.

Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password=;

The connection string shown below is an example of how to connect to a Microsoft Access 2000 database using the OleDbConnection object in System.Data.OleDb.

Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Northwind.mdb

Parameters in a Connection String - The parameters depend on the data provider is being used.
Server - The name of the SQL Server to which connection has to be established through ADO.NET. This is the name of the system that is running SQL server. We may use "local" or "localhost" for local computer. In case we are using named instances of SQL server, then the parameter would contain the computer name, followed by a backslash, followed by a named instance of the SQL server.
Database - The name of the database to which connection is to be established.
User ID - A user ID configured in the SQL Server by the SQL Server administrator.
Password - As the attribute name suggests, this is the password associated with the user id.

Note that connection string may also contain the Windows NT account security settings. This is done by passing the paramater "integrated security=true".

What is a command object in ADO.NET. How to use a command object in .NET?
ADO.NET Command Object
- The Command object is similar to the old ADO command object. It is used to store SQL statements that need to be executed against a data source. The Command object can execute SELECT statements, INSERT, UPDATE, or DELETE statements, stored procedures, or any other statement understood by the database. See sample code...

'Code below in VB.NET ...
Dim ObjCom as SqlClient.SqlCommand
ObjCom.SqlConnection(strCon)
ObjCom.Connection.Open()
ObjCom.CommandText = "Select * from tblSample"
ObjCom.ExecuteNonQuery()

SqlCommand objects are not used much when we use datasets and data adapters. Following are some properties of the SqlCommand class...
Connection Property - This property contains data about the connection string. It must be set on the SqlCommand object before it is executed. For the command to execute properly, the connection must be open at the time of execution.
CommandText Property - This property specifies the SQL string or the Stored Procedure.

objCom.CommandText = "Insert into Employees (empid, empname) values ('EMI0334','Mandy')"

Paramaters Collection - If we want to update values in the Employees table above, but we do not know the values at design time, we make use of placeholders. These are variables prefixed with "@" symbol. Our code will look like this...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)

Next, we have to create parameters that will be used to insert values into the placeholders. For this, we need to add parameters to the parameters collection of the SqlCommand object. This is done so that the values added through the parameters collection & placeholders get i ncluded in the SQL statement. Here, parameters mean the parameters to be passed to the SQL statement/Stored Procedures, not the method's parameters.
In order to add parameters to the SqlCommand object, we write the following code...

objCom.CommandText = "Insert into Employees (empid, empname) values (@empid, @empname)"

objCom.Parameters.Add("@empID", txtempid.text)

objCom.Parameters.Add("@empname", txtempname.text)

ExecuteNonQuery Method - Once the connection is open, we run the query in the SqlCommand object using the ExecuteNonQuery method. This is very simple as shown below...

objConnection.Open()
objCom.ExecuteNonQuery()
objConnection.Close()

What is SelectCommand in ADO.NET?
Select Command Property
- This property is used to hold the SQL command that is used to retrieve data from the data source. The CommandText and Connection are properties of the Select Command propety. CommandType is also a property of Select Command. See example below...

Dim da as new SqlDataAdapter
da.SelectCommand = New SqlCommand( )
With da.SelectCommand
.Connection = objConnection
.CommandText = "select * from employees"
End With

What is a SqlCommandBuilder in ADO.NET
SqlCommandBuilder
class in ADO.NET provides the feature of reflecting the changes made to a DataSet or an instance of the SQL server data. When an instance of the SqlCommandBuilder class is created, it automatically generates Transact-SQL statements for the single table updates that occur. The object of the SqlCommandBuilder acts as a listener for RowUpdating events, whenever the DataAdapter property is set.
The SqlCommandBuilder object automatically generates the values contained within the SqlDataAdapter's InsertCommand, UpdateCommand and DeleteCommand properties based on the initial SelectCommand. The advantage here is that you will not need to write SqlCommand & SqlParameter Types explicitly.
Basically the command builder object builds these objects on the fly. The command builder object actually reads the metadata of the method called. After the builder object reads the underlying schema of the adapter's method, it autogenerates an underlying insert, update & delete command object. See code example below...

//Code below in C#...
DataSet ds = new DataSet();
SqlConnection cn = new SqlConnection("strSomeConnectionString");
//Autogenerate Insert, Update & Delete commands
SqlDataAdapter da = new SqlDataAdapter("Select from t_Something", cn);
SqlCommandBuilder scb = new SqlCommand(da);

//Fill the dataset
da.Fill(ds,"t_Something");

What is a DataView in ADO.NET?
DataView
- Just like we have Views in SQL (in our backend), we have DataView object in ADO.NET. A dataview object represents bindable, customized view of a DataTable object. Operations like Sorting, Filtering, Searching, Editing and Navigation may be performed on a DataView object. In scenarios like retrieval of a subset of data from a Datatable, we may make use of DataViews to get this data. Note that the DefaultView property of a DataTable returns the Default data view for the DataTable. In case a custom view of a DataTable has to be created on a DataView, then the RowFilter property of the DataView is set to the DefaultView.
A dataview may also be used to sort data that resides in it in ascending or descending order. Below is code on how to sort data in a dataview in ascending or descending order...

DataView objdv = new DataView();
objdv.Sort("ColumnName Asc|Desc");

What is DataRelation object in ADO.NET? How to use a DataRelation between two columns in ADO.NET?
In order to set the relationship between two or more than two columns, ADO.NET provides the DataRelation class. When a DataRelation object is created, it assists to enforce some constraints on the relationships between columns. The constraint may be like a Unique constraint that ensures that a column will have no duplicate value in the table. A Foreign Key constraint may be used to enforce Referential Integrity. The Unique property may be set by setting the Unique property of a DataColumn to True. This may also be done by adding an instance of the UniqueConstraint class to the DataRelation object. As a part of the foreign key constraint, we may specify referential integrity rules that are applied at 3 places
1) When a parent record is updated
2) When a parent record is deleted
3) When a change is rejected or accepted.
A DataRelation object permits to establish a parent-child relationship between two or more tables inside a DataSet object. The easiest way to create a DataRelation between two tables in a DataSet is to setup a primary key - foreign key relationship between the columns of a table.
See code example below, where a DataRelation has been setup between the Employee table and the Salary table...
'Code Below in VB.NET
Dim Conn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim RowParent As DataRow
Dim RowChild As DataRow

Conn = New _
SqlConnection(ConfigurationSettings.Appsettings("SomeConnectionStringWrittenInWeb.Config"))
da = New SqlDataAdapter("SELECT * FROM Employees", Conn)
ds = New DataSet()

Try
Conn.Open()
da.Fill( ds,"Employees")
da.SelectCommand = New SqlCommand("SELECT * FROM Salary", Conn)
da.Fill(ds, "Salary")
Catch ex As SqlException
Response.Write(ex.ToString())
Finally
Conn.Dispose()
End Try

'Next, Let us create a Data Relationship
ds.Relations.Add("Employee_Salary", ds.Tables("Employees").Columns("EmployeeID"), _
ds.Tables("Salary").Columns("EmployeeID"))
'Display the Employee and Child Salary in the Form
'Say we have a Label in the form
For each RowParent in ds.Tables("Employees").Rows

lblRelation.Text &= RowParent("Emp_Name")
For each RowChild in RowParent.GetChildRows("Employee_Salary")
lblRelation.Text &= "
" & RowChild("Sal_Amount")
Next
Next

What is Diffgram in ADO.NET? When do we use Diffgram?
A DiffGram is an XML format. It is used to identify current and original versions of data elements. A DataSet may use a DiffGram format to load and persist the contents, and further to serialize its contents for porting across a network connection. Whenever a DataSet is written as a DiffGram, the DataSet populates the DiffGram with all the important information to accurately recreate the contents. Note that schema of the DataSet is not recreated. This includes column values from both the Current and the Original row versions, row error information, and row order.

What is a Typed Dataset in ADO.NET? Why do we use a Typed DataSet? What is the difference between a Typed and an UnTyped DataSet?
Typed DataSet - When a created DataSet derives from the DataSet class, that applies the information contained in the XSD to create a Typed class, this DataSet is said to be a Typed Dataset. Information from the schema whic comprises the tables, columns, and rows is created and compiled to a new DataSet derived from the XSD. The Typed DataSet class features all functionality of the DataSet class. This may be used with methods that take an instance of the DataSet class as a parameter.
Note that an UnTyped DataSet does not have any schema. It is exposed simply as a mere collection.

How to create a Typed DataSet? -
Right click your project in the Solution Explorer.
Click Add New Item.
Select DataSet.
This adds a new XSD to the project. The schema created may be viewed as an XML. When this xsd file is compiled, two files are created by Visual Studio. The first file that contains the .vb or .cs extension contains the information about the proxy class. This class contains methods & properties that are required to access the database data. The second file has an extension xsx and this contains information about the layout of the XSD.

How to run a stored procedure from .NET code?
Use the Command object and its ExecuteNonQuery method to run a DDL or DCL statement of SQL. First, create a connection object and a command object, and configure these objects for the statement you wish to execute. Open the database connection. Call ExecuteNonQuery on the command. Close the connection.
Example
Suppose we have to insert FirstName into a table t_Employees. Our Store procedure is:

Create Procedure dbo.InsertFirstName
(
@FirstName varchar(30)
)
as
Insert Into t_Employees values (@FirstName)

VB.NET code below, to pass FirstName to this Stored Procedure
Dim cmRunProc as New SqlCommand("dbo.InsertFirstName", objCon)
cmRunProc.CommandType = CommandType.StoredProcedure
cmRunProc.Parameters.Add("@FirstName", txtFirstName.Text)
objCon.Open()
cmdRunProc.ExecuteNonQuery()
objCon.Close()

0 comments: