You are on page 1of 76

1. What is Application pooling?

2. How did u deploy application into IIS Server?


3. What is generic list?
4. What is partial class and which .Net feature it is?
5. Difference between UserDefinedFunction and Stored Procedure?
6. How can u call UDF from ADO.NET?
7. What are Triggers?
8. What are views?
9. What are Magic tables and Temporary tables?
10.What is Post Back? What is it drawbacks? How can u handle that?
11.What is stateless ness?
12.How does u kill the Session?
13.What is polymorphism?
14.Did u use Interfaces in Your application?
15.Difference between User control and Custom Control?
16.Features of .Net 4.0?
17.What are the new features of SQL Server 2005?
18.Have u worked with AJAX?
19.What are Nested Master pages?
20.What are sub queries?
21.What is the difference between variable and properties?
22.Can u call the one class constructor in another class?
23.What is Assembly? Types of assemblies?
24.About strong Name and GAC Util?
25.Page Life Cycle?
26.In Which event you will put the code to call the style sheet dynamically?
27.What is XSLT?
28.What are JOINS AND Types of JOINS?
29.Did u face any performance issues with ENTERPRISE LIBRARY?
30.What is sealed class?
31.Did u find any advantage of Telerik RAD Grid over DataGrid control of
ASP.NET?
32.What is Execute. Scalar and Execute.NonQuery ();?
33.How does u handle errors in application?
34.What are Nullables?
35.How can u handle exceptions in UDF?
36.Dataset update changes accept changes and reject changes? How can u
avoid concurrency?
37.Delegates in USER CONTROL?
38.Delegates and events?
39.What is Authentication and Authorization?
40.Why do u use telirik controls?
41.What are the .net 3.5 features used in your project?
42.How do u store image in a database?
43.Procedure to upload a file in asp.net?
44.What are Data binding controls in .net 3.5? Which is better in performance
wise?
45.DataSet Methods and Properties?
46.Boxing and unboxing?
47.Overloading and overriding?
48.What is XSLT?
49.State Management Techniques?
50.Return type of execute. Nonquery(); and execute.scalar?
51.Difference between char,Varchar and nvarchar datatypes?
52.How can u find the value of a textbox using javascript?
53.Difference between normal query and stored procedure?
54.What is base page?
55.Where are session variables stored?
56.What are the events in global asax?
57.Object reference not set to an instance of a object?
58.Difference between client side and server side validations?
59.Drawbacks of client side validation?
60.Difference between String and String Builder?
61.String is value type or reference type?
62.What is static class,static method,static constructor?
63.Difference between Const and Read only?
64.Difference between 3-tier and 3 layered architecture?
65.What is Abstract Class?
66.What is Interface?
67.Can u declare Static method in Abstract class?
68.Difference between Machine and Webconfig?
69.ViewState?
70.Java script Validation for a textbox which is placed in a grid view?

ANSWERS:

DIFFERENCE BETWEEN STRING AND STRING BUILDER IN C#.NET?

Re: What is the Main difference between String and


StringBuilder and why do we use StringBuilder.

Answe String are Immutable (Not Modifiable). If 0 Sande


r you try to modify ep
the string it actually creates a new
# 3 string and the old Soni
string will be then ready for garbage
collection.

StringBuilder when instantiated, creates a


new string with
predefined capacity and upto that capacity
it can
accodomate string without needing to
create a new memory
location for the string....i mean it is
modifiable and can
also grow as and when needed.

When the string needs to be modified


frequently, preferably
use StringBuilder as its optimized for
such situations.

Re: What is the Main difference between String and


StringBuilder and why do we use StringBuilder.

Answe Both String and StringBuilder are classes


r used to
handle the strings.
#4
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.

STATIC CLASS: A static class is basically the same as a non-static class, but there is one
difference: a static class cannot be instantiated. In other words, you cannot use the new keyword
to create a variable of the class type. Because there is no instance variable, you access the
members of a static class by using the class name itself. For example, if you have a static class
that is named UtilityClass that has a public method named MethodA, you call the method as
shown in the following example:

VB
C#
C++
F#
JScript

Copy
UtilityClass.MethodA();
A static class can be used as a convenient container for sets of methods that just operate on
input parameters and do not have to get or set any internal instance fields. For example, in
the .NET Framework Class Library, the static System.Math class contains methods that perform
mathematical operations, without any requirement to store or retrieve data that is unique to a
particular instance of the Math class. That is, you apply the members of the class by specifying
the class name and the method name, as shown in the following example.
Copy
double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

// Output:
// 3.14
// -4
// 3

As is the case with all class types, the type information for a static class is loaded by the .NET
Framework common language runtime (CLR) when the program that references the class is
loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed
to be loaded and to have its fields initialized and its static constructor called before the class is
referenced for the first time in your program. A static constructor is only called one time, and a
static class remains in memory for the lifetime of the application domain in which your program
resides.

Note
To create a non-static class that allows only one instance of itself to be created, see
Implementing Singleton in C#.

The following list provides the main features of a static class:


• Contains only static members.
• Cannot be instantiated.
• Is sealed.
• Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static
members and a private constructor. A private constructor prevents the class from being
instantiated. The advantage of using a static class is that the compiler can check to make sure
that no instance members are accidentally added. The compiler will guarantee that instances of
this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class
except Object. Static classes cannot contain an instance constructor; however, they can contain a
static constructor. Non-static classes should also define a static constructor if the class contains
static members that require non-trivial initialization. For more information, see Static
Constructors (C# Programming Guide).
STATIC METHODS: Are you familiar with OOP? In OOP, static objects or members of a class that can be
accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.

C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-
static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why
instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore
impractical (see below).

In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you
wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

The methods use a similar principle. They should be used for procedures for which it is impractical to do within an
instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require
me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it
is)

However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon
realize, static methods cannot access instance methods or variables within a class. Of course that makes sense
because that static method would not know which instance of the class the get these from unless it were told, since it
is not part of an instance itself)
STATIC CONSTRUCTOR:
A Constructor is usually used to initialize data. However Static Constructor is used to
initialize only static members. Here I am just talking about the Constructors. How they get
initialized and how they behave.

Things to know about Static Constructor

1. It is used to initialize static data members.

2. Can't access anything but static members.

3. Can't have parameters

4. Can't have access modifiers like Public, Private or Protected.


Now once you understand the above points, you can appreciate the difference between
Static Class and Unstatic Class
1. Static Class cannot be instantiated unlike the unstatic class. You should directly
access its Method via the ClassName.MethodName

2. A Program can't tell when it is going to load static class but its definitely loaded
before the call.

3. A Static class will always have the static constructor and its called only once since
after that its in the memory for its lifetime.

4. A Static class can contain only static members. So all the members and functions
have to be static.
5. A Static class is always sealed since it cannot be inherited further. Further they
cannot inherit form any other class (except Object)

ABSTRACT CLASS:
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a
base class of other classes.
Abstract classes have the following features:
• An abstract class cannot be instantiated.
• An abstract class may contain abstract methods and accessors.
• It is not possible to modify an abstract class with the sealed modifier, which means that the
class cannot be inherited.
• A non-abstract class derived from an abstract class must include actual implementations
of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or
property does not contain implementation.
Abstract methods have the following features:
• An abstract method is implicitly a virtual method.
• Abstract method declarations are only permitted in abstract classes.
• Because an abstract method declaration provides no actual implementation, there is no
method body; the method declaration simply ends with a semicolon and there are no
braces ({ }) following the signature. For example:
Copy
public abstract void MyMethod();
• The implementation is provided by an overriding method, which is a member of a non-
abstract class.
• It is an error to use the static or virtual modifiers in an abstract method declaration.
Abstract properties behave like abstract methods, except for the differences in declaration and
invocation syntax.
• It is an error to use the abstract modifier on a static property.
• An abstract inherited property can be overridden in a derived class by including a
property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract
methods. For example:
Copy
interface I
{
void M();
}
abstract class C: I
{
public abstract void M();
}
For more information, see 10.1.1.1 Abstract classes and 10.5.6 Abstract methods.
Example
In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract
class contains an abstract method, MyMethod(), and two abstract properties, GetX() and
GetY().
Copy
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property


{
get;
}

public abstract int GetY // Abstract property


{
get;
}
}

class MyDerivedC: MyBaseC


{
public override void MyMethod()
{
x++;
y++;
}

public override int GetX // overriding property


{
get
{
return x+10;
}
}

public override int GetY // overriding property


{
get
{
return y+10;
}
}

public static void Main()


{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}
Output
Copy
x = 111, y = 161
In the preceding example, if you attempt to instantiate the abstract class by using a statement
like this:
Copy
MyBaseC mC1 = new MyBaseC(); // Error
you will get the following error message:
Copy
Cannot create an instance of the abstract class 'MyBaseC'.

#2
This is a detailed analysis of Abstract classes and methods in C# with some concrete
examples.
The keyword abstract can be used with both classes and methods in C# to declare them as
abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only
partial implementations. But another class can inherit from an abstract class and can create
their instances.
For example, an abstract class with a non-abstract method.
using System;
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
}
class MyClass : MyAbs
{
}
class MyClient
{
public static void Main()
{
//MyAbs mb = new MyAbs();//not possible to create an instance
MyClass mc = new MyClass();
mc.NonAbMethod(); // Displays 'Non-Abstract Method'
}
}

An abstract class can contain abstract and non-abstract methods. When a class inherits
from an abstract, the derived class must implement all the abstract methods declared in the
base class.

An abstract method is a method without any method body. They are implicitly virtual in C#.

using System;
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
public abstract void AbMethod(); // An abstract method
}
class MyClass : MyAbs//must implement base class abstract methods
{
public override void AbMethod()
{
Console.WriteLine("Abstarct method");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.NonAbMethod();
mc.AbMethod();
}
}

But by declaring the derived class also abstract, we can avoid the implementation of all or
certain abstract methods. This is what is known as partial implementation of an abstract
class.

using System;
abstract class MyAbs
{
public abstract void AbMethod1();
public abstract void AbMethod2();
}
//not necessary to implement all abstract methods
//partial implementation is possible
abstract class MyClass1 : MyAbs
{
public override void AbMethod1()
{
Console.WriteLine("Abstarct method #1");
}
}
class MyClass : MyClass1
{
public override void AbMethod2()
{
Console.WriteLine("Abstarct method #2");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.AbMethod1();
mc.AbMethod2();
}
}

In C#, an abstract class can inherit from another non-abstract class. In addition to the
methods it inherited from the base class, it is possible to add new abstract and non-abstract
methods as showing below.

using System;
class MyClass1 // Non-Abstract class
{
public void Method1()
{
Console.WriteLine("Method of a non-abstract class");
}
}
abstract class MyAbs : MyClass1 // Inherits from an non-abstract class
{
public abstract void AbMethod1();
}
class MyClass : MyAbs//must implement base class abstract methods
{
public override void AbMethod1()
{
Console.WriteLine("Abstarct method #1 of MyClass");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method1();
mc.AbMethod1();
}
}

An abstract class can also implement from an interface. In this case we must provide
method body for all methods it implemented from the interface.
using System;
interface IInterface
{
void Method1();
}
abstract class MyAbs : IInterface
{
public void Method1()
{
Console.WriteLine("Method implemented from the IInterface");
}
}
class MyClass : MyAbs//must implement base class abstract method
{
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method1();
}
}
}
}

We can't use the key word abstract along with sealed in C#, since a sealed class can't be
abstract.

The abstract methods are implicitly virtual and hence they can't mark explicitly virtual in
C#.

For example

using System;
abstract class MyAbs
{
public abstract void AbMethod1();
public abstract void AbMethod2();
}
class MyClass1 : MyAbs
{
public override void AbMethod1(){
Console.WriteLine("Abstarct method #1 of MyClass1");
}
public override void AbMethod2()
{
Console.WriteLine("Abstarct method #2 of MyClass1");
}
}
class MyClient
{
public static void Main()
{
MyAbs ma1 = new MyClass1();// Polymorphism
ma1.AbMethod1();
ma1.AbMethod2();
}
}
INTERFACES:
An interface is a structure that declares certain methods and
properties (like a class), but doesn't provide implementations of them.
So, you can (almost) never create an instance of an interface with
'new', as it's meaningless - the resulting object can't actually *do*
anything.

Instead, you define a class that implements the interface - that is,
the interface name is included in its list of base classes, and the
class is then required by the compiler to implement all of the
functions declared in the interface.

The idea is that you can then define functions that take as a parameter
an object of arbitrary type, but which is known to implement the
interface (declaring a variable of interface type means it is a
reference to some object of a class implementing the interface); then,
you can use the methods that you know must exist in the class (those
defined in the interface) to do whatever you want, without concerning
yourself with what other methods/functionality the object may have.

So, for example, the IEnumerable interface in .NET is implemented by


collection classes, and it means that an object of any class
implementing it, regardless of how the collection itself actually
works, can be used as a 'foreach' variable and a few other things, as
the compiler then knows that the object passed is guaranteed to have
certain functionality.

To define your own interface, use the 'interface' keyword, and declare
the members like for a class (but without function bodies). Then, you
could have a function that takes as a parameter an object implementing
the interface, which could actually be an instance of any class you
write that implements the interface. e.g. [syntax may be *slightly*
wrong as I haven't tried compiling this]:

interface ISortable
{
void SortData();
bool IsSorted
{
get;
}
}

class SomethingSortable : ISortable


{
void SortData() // if we don't override this function our class
won't compile
{
[...]
}
bool IsSorted
{
get
{
return ...;
}
}
}
Now we could have a method somewhere like this:

object BinarySearch(ISortable lst)


{
lst.SortData(); // we know this method has to exist in any
object passed
}
This C# Tutorial deals with interfaces in C# .Net. An Interface is a reference type and it contains only
abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the
interface contains only declaration for its members. Any implementation must be placed in class that
realizes them. The interface can't contain constants, data fields, constructors, destructors and static
members. All the member declarations inside interface are implicitly public.

Defining an Interface:
Let us look at a simple example for c# interfaces. In this example interface declares base functionality of
node object.

interface INode
{
string Text
{
get;
set;
}
object Tag
{
get;
set;
}
int Height
{
get;
set;
}
int Width
{
get;
set;
}
float CalculateArea();
}
The above INode interface has declared a few abstract properties and function which should be
implemented by the derived classes.
//Sample for Deriving a class using a C# .Net interface - c# tutorial

public class Node : INode


{
public Node()
{}
public string Text
{
get
{
return m_text;
}
set
{
m_text = value;
}
}
private string m_text;
public object Tag
{
get
{
return m_tag;
}
set
{
m_tag = value;
}
}
private object m_tag = null;
public int Height
{
get
{
return m_height;
}
set
{
m_height = value;
}
}
private int m_height = 0;
public int Width
{
get
{
return m_width;
}
set
{
m_width = value;
}
}
private int m_width = 0;
public float CalculateArea()
{
if((m_width<0)||(m_height<0))
return 0;
return m_height*m_width;
}
}
Now the above code has created a c# class Node that inherits from INode c# interface and implement
all its members. A very important point to be remembered about c# interfaces is, if some interface is
inherited, the program must implement all its declared members. Otherwise the c# compiler throws an
error.
The above code was a simple example of c# interface usage. Now this has to be followed with some
advanced details of interface building in C# .Net. The previous example used only names of methods or
properties that have the same names as in interface. But there is another alternative method for writing
the implementation for the members in class. It uses full method or property name e.g.
INode.CalculateArea () {// implemetation}.

Example of Polymorphism in .Net

What is Polymorphism?
Polymorphism means same operation may behave differently on different classes.
Example of Compile Time Polymorphism: Method Overloading
Example of Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism

Method Overloading
- Method with same name but with different arguments is called method
overloading.
- Method Overloading forms compile-time polymorphism.
- Example of Method Overloading:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}
Example of Run Time Polymorphism

Method Overriding
- Method overriding occurs when child class declares a method that has the same
type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual”
explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent


{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()


{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

What is Polymorphism?
• Polymorphism is one of the primary characteristics (concept) of object-oriented
programming.

• Poly means many and morph means form. Thus, polymorphism refers to being
able to use many forms of a type without regard to the details.

• Polymorphism is the characteristic of being able to assign a different meaning


specifically, to allow an entity such as a variable, a function, or an object to
have more than one form.

• Polymorphism is the ability to process objects differently depending on their


data types.
• Polymorphism is the ability to redefine methods for derived classes.

Types of Polymorphism
• Compile time Polymorphism

• Run time Polymorphism

Compile time Polymorphism


• Compile time Polymorphism also known as method overloading

• Method overloading means having two or more methods with the same name
but with different signatures

Example of Compile time polymorphism

Run time Polymorphism


• Run time Polymorphism also known as method overriding
• Method overriding means having two or more methods with the same name ,
same signature but with different implementation

Example of Run time Polymorphism

You can find source code at the bottom of this article.

What is an Abstraction?

. Abstraction is thinking about something a certain way


. Abstraction is the representation of only the essential features of an object and hiding
un essential features of an object.
. Through Abstraction all relevant data can be hide in order to reduce complexity and
increase efficiency
. Abstraction is simplifying complex reality by modeling classes appropriate to the
problem
. Abstraction-outer layout, used in terms of design
. Encapsulation protects abstraction.
. It taking required data and hiding the unwanted data.
In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car.

Abstraction shows only required data and hides unwanted data.

Difference between Encapsulation and Abstraction

1. Abstraction solves the problem 1. Encapsulation solves the problem in the


in the design level implementation level

2. Abstraction is used for hiding 2. Encapsulation means hiding the code


the unwanted data and giving and data in to a single unit to protect the
relevant data data from outside world

3. Abstraction is a technique that 3. Encapsulation is the technique for


helps to identify which specific
packaging the information in such a way
information should be visible and
as to hide what should be hidden, and
which information should be
make visible what is intended to be visible.
hidden.

In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car
Abstraction shows only required data and hides unwanted data .
In above example which shows encapsulated detail of a car which is not necessary to
expose to outside world and make visible what is intended to be visible.

What is Encapsulation?
• Encapsulation is one of the fundamental principles of object-oriented
programming.

• Encapsulation is a process of hiding all the internal details of an object from the
outside world

• Encapsulation is the ability to hide its data and methods from outside the world
and only expose data and methods that are required

• Encapsulation is a protective barrier that prevents the code and data being
randomly accessed by other code or by outside the class

• Encapsulation gives us maintainability, flexibility and extensibility to our code.

• Encapsulation makes implementation inaccessible to other parts of the program


and protect from whatever actions might be taken outside the function or class.

• Encapsulation provides a way to protect data from accidental corruption


• Encapsulation hides information within an object

• Encapsulation is the technique or process of making the fields in a class private


and providing access to the fields using public methods

• Encapsulation gives you the ability to validate the values before the object user
change or obtain the value

• Encapsulation allows us to create a "black box" and protects an objects internal


state from corruption by its clients.

Two ways to create a validation process.


• Using Accessors and Mutators

• Using properties
In this example _employeeid and _salary is private fields and providing access to the
fields using public methods (SetEmployeeID,GetEmployeeID,SetSalary,GetSalary)

In this example _employeeid and _salary is private fields and providing access to the
fields using public methods (EmployeeID,Salary)

Benefits of Encapsulation
• In Encapsulation fields of a class can be read-only or can be write-only

• A class can have control over in its fields

• A class can change data type of its fields anytime but users of this class do not
need to change any code

What is Access Modifier?


Access modifiers determine the extent to which a variable or method can be accessed
from another class or object
The following five accessibility levels can be specified using the access modifiers
• Private

• Protected

• Internal

• Protected internal

• Public

1. What is Private access modifier?


In OOP Attributes, Methods, Properties, Constructors declared with "private" access
modifier get access or visible only to members of current class
For e.g.: Let's take class BankDetail with access modifier "private"
class BankDetail
{

private string _employeename;


private int _accountnumber;
private double _balanceamount;

private string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}

private int AccountNumer


{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}

private double BalanceAmount


{
set { _balanceamount = value; }
get { return _balanceamount; }
}

private void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename +
"Account Number " + _accountnumber
+ " with Balance Amount is " + _balanceamount);
}

}
Create another class "clsShowDetails"
Now inside class "clsShowDetails" create object of class BankDetail
BankDetail objBank = new BankDetail();
Fron Object objBank if we are trying to access methods,properties of class BankDetail
we cannot access them due to the protction level of "private" access modifier
public class clsShowDetails
{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class "clsShowDetail"
public void getDetails()
{
objBank.DisplayDetail();
}
We will get error message
(BankDetail.DisplayDetail() is inaccessible due to protection level)
This means we cannot access Attributes, Methods, Properties, Constructors declared
with "private" access modifier outside of class but can get access or visible only to
members of current class

2. What is protected access modifier?


In OOP Attributes, Methods, Properties, Constructors declared with "protected" access
modifier get access or visible only to members of current class as well as to members
of derived class.
For e.g.: Let's take class BankDetail with access modifier "protected"
class BankDetail
{

protected string _employeename;


protected int _accountnumber;
protected double _balanceamount;

protected string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
protected int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}
protected double BalanceAmount
{
set { _balanceamount = value; }
get { return _balanceamount; }
}
protected void DisplayDetail()
{
Console.WriteLine("BankDetail for " + _employeename +
"Account Number " + _accountnumber
+ " with Balance Amount is " + _balanceamount);
}

}
Create another class "clsShowDetails"
Now inside class "clsShowDetails" create object of class BankDetail
BankDetail objBank = new BankDetail();

public class clsShowDetails:BankDetail


{

public void getDetails()


{
DisplayDetail();
}

}
From class "clsShowDetail"
public void getDetails()
{
DisplayDetail();
}
We will get no error message
This means we can access Attributes, Methods, Properties, Constructors declared with
"protected" access modifier in derived class

3. What is internal access modifier?


In OOP Attributes, Methods, Properties, Constructors declared with "internal" access
modifier get access or visible only to members of current project or in current
namespace
For e.g.: Let's take class BankDetail with access modifier "internal"
class BankDetail
{

internal string _employeename;


internal int _accountnumber;
internal double _balanceamount;

internal string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}

internal int AccountNumer


{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}

internal double BalanceAmount


{
set { _balanceamount = value; }
get { return _balanceamount; }
}

internal void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename +
"Account Number " + _accountnumber
+ " with Balance Amount is " + _balanceamount);
}
}
Add New Item in the same project
Create another class "clsShowDetails" in Class2.cs file
Now inside class "clsShowDetails" create object of class BankDetail
BankDetail objBank = new BankDetail();

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

From class "clsShowDetails"


public void getDetails()
{
DisplayDetail();
}
We will get no error message
This means we can access Attributes, Methods, Properties, and Constructors declared
with "internal" access or visible only to members of current project or in current
namespace

4. What is protected internal access modifier?


In OOP Attributes, Methods, Properties, Constructors declared with "protected internal"
access modifier get access or visible only to members of current project or in current
namespace and also to members of derived class
5. What is public access modifier?
In OOP Attributes, Methods, Properties, Constructors declared with "public" access
modifier get access or visible to all members of classes and projects
class BankDetail
{
public string _employeename;
public int _accountnumber;
public double _balanceamount;
public string EmployeeName
{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
public int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}
public double BalanceAmount
{
set { _balanceamount = value; }
get { return _balanceamount; }
}

public void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename +
"Account Number " + _accountnumber
+ " with Balance Amount is " + _balanceamount);
}

}
Create another class "clsShowDetails"
Now inside class "clsShowDetails" create object of class BankDetail
BankDetail objBank = new BankDetail();

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class "clsShowDetail"
public void getDetails()
{
objBank.DisplayDetail();
}
We will get no error message
Let's try to access "public" access modifier with another example
Add New Item in the same project

Create another class "clsShowDetails"


Now inside class "clsShowDetails" create object of class BankDetail
BankDetail objBank = new BankDetail();

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class "clsShowDetail"
public void getDetails()
{
objBank.DisplayDetail();
}
We will get no error message
This means "public" access modifier is access or visible to all members of classes and
projects.
DIFFERENCE BETWEEN VIRTUAL METHOD AND ABSTRACT METHOD?

VIRTUAL METHOD CAN BE OVERRIDDEN IN ANY OF ITS DERIVED CLASS AND ABSTRACT METHOD MUST
BE OVERRIDDEN IN ANY OF THE NON ABSTRACT CLASS

STRUCT IS VALUE TYPE AND CLASS IS REFERENCE TYPE.

Difference between Const and ReadOnly:

Const:

1. Cannot be static
2. The value is evaluated at compile time
3. It is initialized at declaration only
4. The const keyword is used for compile-time constant
ReadOnly:
1. Can be either instance-level or static
2. Value is evaluated at runtime
3. Readonly keyword is used for runtime constants .

State Management Techniques in ASP.NET

This article discusses various options for state management for web applications developed
using ASP.NET. Generally, web applications are based on stateless HTTP protocol which
does not retain any information about user requests. In typical client and server
communication using HTTP protocol, page is created each time the page is requested.

Developer is forced to implement various state management techniques when developing


applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state
management techniques in their applications. Broadly, we can classify state management
techniques as client side state management or server side state management. Each
technique has its own pros and cons. Let's start with exploring client side state management
options.
Client side State management Options:

ASP.NET provides various client side state management options like Cookies, QueryStrings
(URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of
client side state management options.
Bandwidth should be considered while implementing client side state management options
because they involve in each roundtrip to server. Example: Cookies are exchanged between
client and server for each page request.
Cookie:

A cookie is a small piece of text stored on user's computer. Usually, information is stored as
name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user
visits a website, cookies are retrieved from user machine and help identify the user.

Let's see an example which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our
website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on
bandwidth
• Inappropriate for sensitive data
Hidden fields:

Hidden fields are used to store data at the page level. As its name says, these fields are not
rendered by the browser. It's just like a standard control for which you can set its
properties. Whenever a page is submitted to server, hidden fields values are also posted to
server along with other controls on the page. Now that all the asp.net web controls have
built in state management in the form of view state and new feature in asp.net 2.0 control
state, hidden fields functionality seems to be redundant. We can still use it to store
insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field


Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size.
Disadvantages:
• Inappropriate for sensitive data
• Hidden field values can be intercepted(clearly visible) when passed over a network
View State:

View State can be used to store state information for a single user. View State is a built in
feature in web controls to persist data between page post backs. You can set View State
on/off for each control using EnableViewState property. By default, EnableViewState
property will be set to true. View state mechanism poses performance overhead. View state
information of all the controls on the page will be submitted to server on each post back. To
reduce performance penalty, disable View State for all the controls for which you don't need
state. (Data grid usually doesn't need to maintain state). You can also disable View State for
the entire page by adding EnableViewState=false to @page directive. View state data is
encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be
taken to ensure view state for a page is smaller in size. View State can be used using
following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewState


Response.Write(ViewState["myviewstate"]);

Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are
passed along with URL in clear text. Now that cross page posting feature is back in asp.net
2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on
URL length. We can only pass smaller amounts of data using query strings. Since Query
strings are sent in clear text, we can also encrypt query values. Also, keep in mind that
characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid
that goes to a product detail page, it would be an ideal use of the Query String to include
the product ID in the Query String of the link to the product details page (for example,
productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by
using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings
of View State. Control state can be used to store critical, private information across post
backs. Control state is another type of state container reserved for controls to maintain their
core behavioral functionality whereas View State only contains state to maintain control's
contents (UI). Control State shares same memory data structures with View State. Control
State can be propagated even though the View State for the control is disabled. For
example, new control Grid View in ASP.NET 2.0 makes effective use of control state to
maintain the state needed for its core behavior across post backs. Grid View is in no way
affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session,
Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large
number of concurrent users, usage
of sessions object for state management can create load on server causing performance
degradation
Application object:
Application object is used to store data which is visible across entire application and shared
across multiple user sessions. Data which needs to be persisted for entire life of application
should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to
store data which changes infrequently. We should write to application variable only in
application_Onstart event (global.asax) or application.lock event to avoid data conflicts.
Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to
particular user. Session data persists for the duration of user session you can store session's
data on web server in different ways. Session state can be configured using the <session
State> section in the application's web.config file.
Configuration information:

<sessionState mode = <"inproc" | "sqlserver" | "stateserver">


cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:

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

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a
cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's
session is active. Note that the session timeout is a sliding value; Default session timeout
value is 20 minutes

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

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

Port:

This identifies the port number that corresponds to the server setting for mode State
Server. Note that a port is an unsigned integer that uniquely identifies a process running
over a network.
You can disable session for a page using EnableSessionState attribute. You can set off
session for entire application by setting mode=off in web.config file to reduce overhead for
the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters
including scalability, maintainability and availability
• In process mode (in-memory)- State information is stored in memory of web server
• Out-of-process mode- session state is held in a process called aspnet_state.exe that
runs as a windows service.
• Database mode – session state is maintained on a SQL Server database.
In process mode:

This mode is useful for small applications which can be hosted on a single server. This
model is most common and default method to store session specific information. Session
data is stored in memory of local web server
Configuration information:
<sessionState mode="Inproc"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Fastest mode
• Simple configuration
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):

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

<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
• Supports web farm and web garden configuration
• Session data is persisted across application domain recycles. This is achieved by
using separate worker process for maintaining state
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL
Server offers resilience that can serve sessions to a large web farm that persists across IIS
restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET
Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a
database which will manage the session state.
Configuration Information:
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Supports web farm and web garden configuration
• Session state is persisted across application domain recycles and even IIS restarts
when session is maintained on different server.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various
factors including available server resources, scalability and performance. We have to
leverage both client side and server side state management options to build scalable
applications.
When leveraging client side state options, ensure that little amount of insignificant
information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including
size of application, reliability and robustness. Smaller the application, In process is the
better choice. We should account in the overheads involved in serializing and deserializing
objects when using State Server and Database based session state. Application state should
be used religiously.
ASP.NET Session state provides a place to store values that will persist across page requests. Values stored
in Session are stored on the server and will remain in memory until they are explicitly removed or until the
Session expires.
Storing and retrieving a value in the Session is as simple as:
VB
Session("Name") = "John Doe"'orSession.Add("Name","John Doe")'retrieving
Dim Name As String = Session("Name")
C#
Session["Name"] = "John Doe";//orSession.Add("Name","John Doe");//retrievingstring
Name = (string)Session["Name"];
By default the Session will be created within the same process that your web site runs in (InProc). This is
controlled by a setting in the web.config file:
<sessionState mode="InProc" />
Although running the Session In Process is very convenient, it does mean that all Session values will be lost
whenever the application recycles (such as when deploying updates) . There are alternate modes you can
use that will allow the Session state to survive even when the application recycles. The available options
are:
• Off - No session state will be stored
• InProc - (The Default) Session state exists within the process the web is using
• StateServer - Session data is sent to the configured stateserver service
• SQLServer - Session data is store in the configured sql server database
Both the StateServer mode and the SQLServer mode allow Session state to survive an application recycle.
But, when storing reference type objects (such as class instances), they can only be stored to StateServer
or SQLServer if they have been marked with the Serializable attribute.
An important consideration for using Session state is that the Session does expire. By default, if a user does
not access their Session data within 20 minutes (by default), the Session will expire and all items that had
been stored in the Session will be discarded. Because of this, it is important to check the object that
is returned from the Session to see if it exists or if it is null before you try to work with it. For example:
object sessionObject = Session["someObject"];
if (sessionObject != null) {
myLabel.Text = sessionObject.ToString();
}
The Session Timeout is adjustable through a web.config setting but increasing the timeout value can put
memory pressure on your server that may be undesirable.
<sessionState timeout="number of minutes" />
Other commonly used Session methods are:
• Session.Abandon() - removes the Session and all items that it contains
• Session.Clear() - removes all items from the Session
• Session.RemoveAll() - removes all items from the Session
• Session.Remove("itemName") - removes the item that was stored under the name "itemName"


• 7,353,985 members and growing! (22,713 online)
• Top of Form
MenuBarForm Sign in

• Email Password Remember me?


Lost password?
• Bottom of Form


Home Top of Form
Articles Search
Chapters and Sections
Search within:

Articles

Quick
Search Answers
Latest Articles
Latest Tips/Tricks Messages
Top Articles
Beginner Articles
Technical Blogs Jobs
Post an Article
Post Tip & Trick Product
Post your Blog Catalog
Posting/Update Bottom of Form
Guidelines
Article Competition
Questions & Answers
Ask a Question about this
article
Quick Answers
Ask a Question
View Unanswered
Questions
View All Questions...
C# questions
ASP.NET questions
VB.NET questions
C++ questions
C#3.0 questions
Programming Discussions
All Message Boards...
Application Lifecycle>
Design and Architecture
Running a Business
Sales / Marketing
Collaboration / Beta
Testing
Work & Training Issues
C / C++ / MFC>
ATL / WTL / STL
Managed C++/CLI
C#
Database
IT & Infrastructure>
Hardware & Devices
System Admin
Java
.NET Framework
Mobile
Sharepoint
Silverlight / WPF
Visual Basic
Web Development>
ASP.NET
CSS
Javascript
PHP
Site Bugs / Suggestions
Other Languages>
General Indian Topics
General Chinese Topics
Learning Zones
The Commerce Zone
The Mobile Zone
The Cloud Zone
The Hardware Zone
The Parallelism Zone
The SQL Zone
WhitePapers / Webcasts
Jobs
Latest
Search
Post a Job
FAQ and Pricing
Features
Who's Who
CodeProject MVPs
Company Listings
Component & Service
Catalog
Competitions
News
Newsletter archive
Press Releases
Surveys
CodeProject Stuff
CodeProject VS Addin
Help!
What is 'The Code
Project'?
General FAQ
Post a Question
Bugs and Suggestions
Site Directory
Advertise with us
About Us
The Lounge The
Soapbox


4.76 / 5, 275
votes

1 2 3 4 5

• Print Article

• Twitter

• Digg

• Facebook

• Del.icio.us

• Reddit

• Stumbleupon

• Newsvine

• Technorati

• Mr. Wong

• Yahoo!

• Google

• Windows Live

• Send as Email
• Add to your CodeProject bookmarks


• Discuss this article

• 204
• Report this article as inappropriate

Article Browse Code Stats Revisions (25)

First Posted 15 Jan 2009

Views 252,603

Bookmarked 498 times


Licence CPOL
C#1.0, C#2.0, C#3.0, C#, ASP.NET, Windows,
Architect, Dev ...


• » Web Development » ASP.NET » General
• Exploring Session in ASP.Net
• By Abhijit Jana | 23 Jan 2009 | Unedited contribution
• This article describe about session in ASP.Net 2.0 .
Different Types of Session , There Configuration . Also
describe Session on Web Farm , Load balancer , web
garden etc.
Prize winner in Competition "Best ASP.NET article of
January 2009"
• Top of Form
/w EPDw UKMTAy


• Download Session_SampleApplication.zip - 2.85 KB
• Table of Content
• Introduction
• What is Session ?
• Advantages and Disadvantages of Session.
• Storing and Retrieving values from Session
• Session ID
• Session Mode and State Provider
• Session State
• Session Event
• Session Mode
• InProc Session Mode
• Overview of InProc Session Mode
• When should we use InProc Session Mode ?
• Advantages and Disadvantages
• StateServer Session Mode
• Overview of StateServer Session Mode
• Configuration for State Server Session Mode
• How StateServer Session Mode Works?
• Example Of StateServer Session Mode
• Advantages and Disadvantages.
• SQL Server Session Mode
• How SQL Server Session Mode Works?
• When should we use SQL Server Session Mode ?
• Configuration for SQL Server Session Mode
• Advantages and Disadvantages.
• Custom Session Mode
• How custom session mode works?
• When should we use custom session mode ?
• Configuration for custom session mode
• Advantages and disadvantages
• Overview of Production Deployment
• Application Pool
• Identity of Application Pool
• Creating and Assign of Application Pool
• Web Garden
• How to create web garden
• How Session Depends on Web Garden
• Web Farm and Load Balancer
• Handling Session in Web Farm and Load Balancer
Scenarios
• Session And Cookies
• What is Cookie-Munging?
• How Cookie-Munging Works in ASP.Net ?
• Removing Session From Session Variable
• Enabling and Disabling Session
• Summary
• Introduction
• First of all I would like to thank all the readers who read
and vote for my article. In Beginner's Guide series, I have
written some articles on state management. Probably this
is my last article on state management. Now coming back
to the topic of this article "Exploring Session in ASP.Net" .
This article will give you a very good understanding of
session. In this article I have covered basic of session,
different types of storing session object, Session behavior
in web farm scenarios , Session on Load Balancer etc. I
have also explained details of Session Behavior in a Live
production environment. Hope you will enjoy this article
and provide your valuable suggestion and feedback.
• What is Session ?
• Web is Stateless, which means a new instance of the web
page class is re-created each time the page is posted to
the server. As we all know HTTP is a stateless protocol, it
can't hold the client information on page. If user inserts
some information, and move to the next page, that data
will be lost and user would not able to retrieve the
information. So what we need? we need to store
information. Session provides that facility to store
information on server memory. It can support any type of
object to store along with our custom object. For every
client Session data store separately, means session data
is stored as per client basis. Have a look at the following
diagram.


• Fig : For every client session data store separately
• State Management using session is one of the asp.net
best features, because it is secure, transparent from users
and we can store any kind of object with in it. Along with
advantages, some times session can causes performance
issue for heavy traffic sites because its stored on server
memory and clients read data from the server itself. Now
lets have a look at the advantages and disadvantages of
using session in our web application.
• Advantages and Disadvantages of Session ?
• Following are the basic advantages and disadvantages of
using session. I have describe in details with each type of
session at later point of time.
• Advantages :
• It helps to maintain user states and data to all over the
application.
• It can easily be implemented and we can store any kind of
object.
• Stores every client data separately.
• Session is secure and transparent from user.
• Disadvantages :
• Performance overhead in case of large volume of user,
because of session data stored in server memory.
• Overhead involved in serializing and De-Serializing
session Data. because In case of StateServer and
SQLServer session mode we need to serialize the object
before store.
• Besides these, there are many advantages and
disadvantages of session that are based of session Types.
I have Discussed all of them.
• Storing and Retrieving values from Session
• Storing and Retrieving values in session are quite similar
with ViewState. We can interact with Session State with
System.Web.SessionState.HttpSessionState class,
because this provides built in Session Object with Asp.Net
Pages.
• Following code is used for storing a value to session
• Collapse | Copy Code
• //Storing UserName in Session
• Session["UserName"] = txtUser.Text;
• Now, let see how we can retrieve values from Session
• Collapse | Copy Code
• //Check weather session variable null or not
• if (Session["UserName"] != null)
• {
• //Retrieving UserName from Session
• lblWelcome.Text = "Welcome : " +
Session["UserName"];
• }
• else
• {
• //Do Something else
• }
• we can also store some other object in Session. Following
Example shows how to store a DataSet in session.
• Collapse | Copy Code
• //Storing dataset on Session
• Session["DataSet"] = _objDataSet;
• and following code shows how we can retrieve that
dataset from the session
• Collapse | Copy Code
• //Check weather session variable null or not
• if (Session["DataSet"] != null)
• {
• //Retrieving UserName from Session
• DataSet _MyDs = (DataSet)Session["DataSet"];
• }
• else
• {
• //Do Something else
• }
• Ref & for more Information: Read Session Variable Section
• Session ID
• Asp.Net use 120 bit identifier to track each session. This is
secure enough and can't be reverse engineered. When
client communicate with server, only session id is
transmitted, between them. When client request for data,
ASP.NET looks on to session ID and retrieves
corresponding data. This is done in following steps,
• Client hits web site and some information is stored in
session.
• Server creates a unique session ID for that clients and
stored in Session State Provider .
• Again client request For some information with that
unique session ID from Server.
• Server,looks on Session Providers, and retrieve the
serialized data from state server and type cast the object
.
• Just have a look on the pictorial flow,


• Fig : Communication of Client, web server, and State
Provider
• Ref. & for more Information: SessionID in MSDN
• Session Mode and State Provider
• In ASP.NET there are following session mode available,
• InProc
• StateServer
• SQLServer
• Custom
• For every session State, there is Session Provider.
Following diagram will show you how they are related.


• Fig : Session State Architecture
• we can choose the session State Provider based on which
session state we are selecting. When ASP.NET request for
any information based on session ID, session state and its
corresponding provider are responsible for sending the
proper information based on user. Following tables show,
the session mode along with there provider Name.
Session
State State Provider
Mode
In-Memory
InProc
Object
StateServe Aspnet_state.
r exe
SQLServer DataBase
CustomProvid
Custom
er
• apart from that, there is another mode, "Off". If we select
this option the session will be disabled for the application.
But our objective is to use session, so we will look into
that four session State Mode.
• Ref. & for more Information: Session State Providers
• Session States
• If we consider about session state, It means all the
settings that you have made for your web application for
maintaining the session. Session State, it self is a big
thing, It says all about your session configuration, Either
in web.config or from code behind. In web.config,
<SessionState> elements used for setting the
configuration of session. Some of them are Mode,
Timeout, StateConnectionString, Custom provider etc. I
have discussed about each and ever section of connection
string. Before I discussed Session Mode, just take a brief
overview of Session Event
• Session Event
• There are two types of session events available in
asp.net
• Session_Start
• Session_End
• you can handle both this event in global.asax file of
your web application. When a new session initiate
session_start event raised and Session_End event raised
when a session is abandoned or expired.
• Collapse | Copy Code
• void Session_Start(object sender, EventArgs e)
• {
• // Code that runs when a new session is started

• }

• void Session_End(object sender, EventArgs e)
• {
• // Code that runs when a session ends.

• }
• Ref. and for more Information : Application and Session
Events
• Session Mode
• I have already discussed about the session mode in
ASP.NET, Following are the different types of session
modes available in ASP.Net.
• Off
• InProc
• StateServer
• SQLServer
• Custom
• If we set Session Mode="off" in web.config, Session will
be disabled to all over the application. For this we need to
configure web.config in following way



• InPorc Session Mode :
• This is the default session mode in Asp.Net. Its stores
session Information in Current Application Domain. This is
the best session mode which is based on web application
Performance. But main disadvantage is that, It will lose
the data if we restart the server. There are some more
advantages and disadvantages of InProc session mode. I
will come to those points again .
• Overview of InProc Session Mode :
• As I have already discussed InProc mode session data will
be stored on the current application domain. So It is easily
and quickly available.

• So, InProc session mode store its session data in a
memory object on that application domain. This is
handled by worker process in application pool. So If we
restart the server we will lose the session data. If Client
request for the data , state provide read the data from In-
Memory Object and return it to the client. In web.config
we have to mention Session mode and also we have to
set the Timeout.


• This Session TimeOut Setting keeps session alive for 30
minute. This can be configurable from Code behind too.
• Collapse | Copy Code
• Session.TimeOut=30;
• There are two type of session events available in asp.net
Session_Start() and Session_End. It is the only mode that
supports the Session_End() event. These events will call
after the session timeout period is over. The general flow
for the InProc Session State is some thing like this.

• Now, when the Session_End() will call that depends on
Session Time Out. This is a very fast mechanism because
no serialization occurs for storing and retrieving data, and
data are staying inside the same application domain.
• When Should we use InProc Session Mode ?
• InProc is the default session mode. It can be very helpful
for a small web sites and where the number of user are
very less, We should avoid InProc in case of Web Garden
(I will come to this topic in details) Scenario .
• Advantages and Disadvantages
• Advantages :
• It store Session data in memory object of current
application domain. So accessing data is very fast and
data is easily available.
• There is not requirements of serialization to store data in
InProc Session Mode.
• Implementation is very easy, just similar to using View
State.
• Disadvantages :
• although InProc Session is fastest, common and default
mechanism, It has lots of limitation.
• If the worker Process or application domain recycles all
session data will be lost.
• Though its fastest, but more session data and more users
can affects performance, because of memory.
• we can't use it in web Garden scenarios .
• This session mode is not suitable for web farm scenarios
also.
• So as per above discussion, we can conclude InProc is
very fast session storing mechanism but suitable for small
web application. InProc Session Data will get lost if we
Restart the server, application domain recycles It is also
not suitable for Web Farm and Web Garden Scenarios.
• Now have a look that what are the other option available
to overcome these problem. First Come to StateServer
Mode.
• StateServer Session Mode :
• Overview of StateServer Session Mode :
• This is also called Out-Proc session mode. StateServer
uses a stand-alone Windows Services, which is
Independent to IIS and can also run on a separate server.
This session state is totally managed by aspnet_state.exe.
This server may runs on the same system, but it's out side
of that main application domain where your web
application is running. This allow if you restart your
asp.net process restarted your session data will be alive.
This approaches has several disadvantages due to the
overhead of serialization and de-serialization, its also
increases the cost of data access because of every time
when user retrieves session data, our application hits a
different process.


• Configuration for StateServer Session Mode
• In StateServer the Session data is stored in a separate
Server which is Independent to IIS and Its handled by
aspnet_state.exe. This process is run as windows
Services. you can start this service from windows MMC or
from command prompt.

• By default "Startup Type" of ASP.NET state service is set
to manual, we have to set it as "Automatic" startup type.


• from command from just typing "net start aspnet_state".
By default this services listen TCP Port 42424 , but we can
change the port from registry editor as given in below
picture .

• Now have a look on the web.config configuration for
StateServer Setting. For State Server Setting we need
have to specify the stateConnectionString. This will
identify the system that is running state server. By default
stateConnectionString used ip as 127.0.0.1 (localhost)
and Port 42424.


When we are using StateServer, we can configure
stateNetworkTimeOut attributes to specify the maximum
number of seconds to wait for the service to respond
before canceling the request. Default time is 10 seconds.

• For using StateServer, the object which we are going to


store that should be serialized and at the time of
retrieving we need to De-Serialize. I have described it
with an Example.
• How StateServer Session Mode Works?
• We used StateServer Session Mode to avoid unnecessary
session data loss during restart of web Server.
StateServer is maintained by process aspnet_state.exe as
a windows Services. This process maintains the all the
session data. But need to serialize the data before storing
it in StateServer Session Mode.


• As shown in above figure, that client request to the web
server, then web server stores the session data on state
server. StateServer may be the current system or may be
the different system. But it is totally independent of IIS.
Destination of StateServer will depend on the web.config
stateConnectionString attribute settings. If we set it as
127.0.0.1:42424, It will store data on that local system
itself. For change the StateServer destination, we need to
change the IP. and make sure, aspnet_state.exe is up and
running on that system. other wise you will get the
following exception while trying to store data on session.


• When we are storing any object on session, that should be
serialized. That data will be stored to StateServer system
using State Provider. and at the time of retrieving the
data, State provider will return the data. The complete
flow is given in the below picture.

• Example Of StateServer Session Mode :
• Here is one simple example of using StateServer Session
mode. I have created this sample web application directly
on the IIS so that we can easily understand its usage.
• Step 1 : Open Visual Studio > File > New > Web Sites .
Choose Location as HTTP and create the web application .


• Now if you open the IIS you will see a Virtual Directory
created with the name of your web application , as in my
case it is StateServer.

• Step 2 : Create s simple UI that will take Roll No and
Name of a student . We will store the name and roll in a
state server session. I have also create one same class
"StudentInfo" . This class is given below
• Collapse | Copy Code
• [Serializable]
• public class StudentInfo
• {
• //Default Constructor
• public StudentInfo()
• {

• }
• /// <summary>
• /// Create object of student Class
• /// </summary>
• /// <param name="intRoll">Int
RollNumber</param>
• /// <param name="strName">String
Name</param>
• public StudentInfo(int intRoll, string strName)
• {
• this.Roll = intRoll;
• this.Name = strName;
• }

• private int intRoll;
• private string strName;
• public int Roll
• {
• get
• {
• return intRoll;
• }
• set
• {
• intRoll = value;
• }
• }

• public string Name
• {
• get
• {
• return strName;
• }
• set
• {
• strName = value;
• }
• }
• }
• Now , have a look on the code behind code. I have just
added two button one for storing session and another for
retrieving session.
• Collapse | Copy Code
• protected void btnSubmit_Click(object sender, EventArgs
e)
• {

• StudentInfo _objStudentInfo = new
StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);
• Session["objStudentInfo"] = _objStudentInfo;
• ResetField();
• }
• protected void btnRestore_Click(object sender,
EventArgs e)
• {
• StudentInfo _objStudentInfo = (StudentInfo)
Session["objStudentInfo"];
• txtRoll.Text = _objStudentInfo.Roll.ToString();
• txtUserName.Text = _objStudentInfo.Name;

• }
• Step 3 : Please Configure your web.config for state server.
As I have already discussed. And Please make sure
aspnet_state.exe is up and running on that configured
server.
• Step 4 : Run the Application


• Enter the data, Click on Submit.
• Now there are following Test that I have made which will
totally clear your doubts that how exactly StateServer is
useful.
• First :Remove the [ Serializable ] key word from the
studentinfo class and try to run the application. When you
will click on Submit Button you will get following error


• Which clearly says that you should have to serialize the
object before store.
• Second: Run the Application, Store data by clicking on
Submit Button. Restart IIS

• Now, In case of InProc, you have already lost your session
data, But Its StateServer, Click on Restore Session, You
will get your original data. Because State server data does
not depend on IIS. Its keeps it separately.
• Third : Stop the aspnet_state.exe from the Windows
Services MMC and Submit the Data. You will get following
error,


• Because your State Server Process is not running.
• So, Please keep in mind about those three points .
• Advantages and Disadvantages.
• So based on the above discussion
• Advantages :
• Its keeps the data separate from IIS so, any Issue with IIS
does not hamper Session data.
• It is useful in web farm and web garden scenarios.
• Disadvantages :
• Process is slow due to Serialization and De-Serialization
• State Server always need to be up and running.
• Now, I am stopping here on StateServer, You will find
some more interesting points on Load balancer, Web
Farm, Web Garden Section.
• Ref & for more Information:
• State Server Session Mode
• Asp.Net Session State
• SQL Server Session Mode :
• Overview of SQL Server Session Mode :
• This session mode provide us more secure and reliable
Session management in asp.net. In this session mode,
the Session data is serialized and stored in the SQL Server
database. Main disadvantages of this session storage
methods is overhead related with Data Serialization and
De-Serialization. It is the best option for using in the web
farms.


• To setup SQL Server we need to take help of two sql
Script.
• For Installing: InstallSqlState.sql
• For Un-Installing: UninstallSQLState.sql
• The most easiest way to configure SQL Server, is using
aspnet_regsql command.
• I have explained the detailed use of these file in
configuration section. This is the most useful state
management in the web farm scenario.
• When should we use SQL Server Session Mode ?
• SQL Server Session mode is more reliable and secure
session state management.
• Its keeps data in a centralized location (database).
• We should use SQL server session mode when we need to
implement Session with some more security.
• If there happens to be frequent server Restart we can
implement SQL server.
• This is perfect mode that fits in web farm and web garden
scenarios (I have explained in details later) .
• we can use SQL server Session mode when we need to
share session between two different application .
• Configuration for SQL Server Session Mode
• In SQL Server Session mode, we are storing session data
in a SQL Server, so we need to first provide the database
connection string in web.config . sqlConnectionString
attribute is used to provide the connection string in
web.config.
• After setup the connection string we need to configure the
SQL Server. I am explaining how to configure your your
SQL server using aspnet_regsql command.
• Step 1: From Command prompt, Go to your Framework
Version Directory
• E.g :c:\windows\microsoft.net\framework\<version>.
• Step 2 : Run aspnet_regsql command with following
parameters


• Have a look on the parameter and there uses
Parameters Description
Add support for SQLServer mode
-ssadd
session state.
P is stands for Persisted. Its persist the
-sstype p
session data on server
-S Specify Server Name
-U Specify User Name
-P Specify Password
• After run you will get the following message,


• that's all .
• Step 3 : Open SQL Server Management Studio, Check, A
new database ASPState has been created and there
should be two tables,
• ASPStateTempApplications
• ASPStateTempSessions

• Now, Just change the configuration string of the State
Server Example and Run the same application that I have
explained in State Server.
• Just store Roll and User Name and Click on Submit button,
and open ASPStateTempSessions Table from SQL Server
Management Studio.. WoW... here is your session data,


• Now. do the following Test that I have already explained
in State Server Mode.
• Remove The Serialize Key word from StydentInfo Class
• Reset IIS and Click on Restore Session
• Stop the SQL Server Services
• I think I have explained the SQL Server Session mode
well.
• Advantages and Disadvantages
• Advantages :
• Session data do not affected if we restart the IIS.
• It is the most reliable and secure session management.
• It keeps data located centrally , It can be easily
accessible from other application.
• It is very useful in web farm and web garden scenarios.
• Disadvantages :
• Processing is very slow in nature.
• Object serialization and de-serialization creates overhead
for application.
• As the session data is handled in different server, so we
have to take care of SQL server. It should be always up
and running.
• Ref & for more Information : Read SQL Server Mode
• Custom Session Mode
• Overview of Custom Session Mode :
• Generally we use either of InProc, StateServer or SQL
Server Session mode for our application, but we also
need to know the fundamental of Custom Session mode.
This session mode is quite interesting, because Custom
session gives full control to us to create every thing even
session ID. you can write your own algorithm to generate
session ID.
• You can implement custom providers that store session
data in other storage mechanisms simply by deriving from
SessionStateStoreProviderBase Class. You can also
Generate New Session Id by Implementing
ISessionIDManager.
• This are the following methods are called during
implementation of Custom Session


• In Initialize methods we can set the Custom Provider. This
will initialize the connection with that specified provider.
SetItemExpireCallback used to set SessionTimeOut, we
can register any methods that will call at the time of
session expire. InitializeRequest is called on every request
and CreateNewStoreData used to create a new instance
of SessionStateStoreData .
• When should we use Custom Session Mode ?
• we can use custom session mode in following of the
cases,
• We want to store session data rather than SQL Server.
• When we have to use some Existing table to store session
data.
• When we need to create our own session ID.
• What configuration do we need for it?
• We need to configure our web.config like below,


• If you want to Explore some thing more please Check
Further study section
• Advantages and Disadvantages
• Advantages :
• We can use some existing Table for the store session
data, It is useful when we have to use some old database
rather than SQL Server.
• It's not depending on IIS , So Restarting web server does
not make any effects on session data.
• We can crate our own algorithm for generating Session ID.
• Disadvantages :
• Processing of Data is very slow.
• Creating a custom state provider is a low-level task that
needs to be handled carefully to ensure security.
• Its always recommended to use any third party provider
rather than creating your own.
• Ref and More Information : Custom Mode
• If you want to know more about details session Mode
please Read this MSDN Article
• Overview of Production Deployment
• Generally Production environments means when we
deploy the application on our live production server. This
is a major and Big Challenge for the web developer to
deploy there application on Live Server. because in a Big
production environment there are no of user and its not
possible to handle the load of so many users by a single
server. Here the concepts came of Web Farm, Load
Balancer , Web Garden etc.
• Just few month back I have deployed one of our web
application In a live production environment which is
accessible by million of user and there were more than
10 Active Directory, more than 10 Web Server Over Load
Balancer and Many DB Server, Exchange Server, LCS
Server etc. If we look at the number of web server, this is
multiple. The major risk involves in multiple server is
Session Management. Following picture shows the general
diagram for a Production environments.


• I will try to explain the different scenario that you need to
keep in mind while deploying your application.
• Application Pool :
• This is one of the most important thing that you should
create for your own application in Production
environment. Application pools used to separate sets of
IIS worker processes that share the same configuration.
Application pools enable us to isolate our web application
for better security, reliability, and availability. The worker
process serves as the process boundary that separates
each application pool so that when one worker process or
application is having an issue or recycles, other
applications or worker processes are not affected.


• Identity Of Application Pool
• Application pool identity configuration is an important
aspect of security in IIS 6.0 and IIS 7.0, because it
determines the identity of the worker process when the
process is accessing resource. This Settings comes from
IIS 6.0 In IIS 7.0 there are Three predefine Identity , that
are same with IIS 6.0.
Applicationpool Identity Description
LocalSystem is a built-in account that
has administrative privileges on the
server. It can access both local and
LocalSystem remote resources. For any kind
accessing of server files or resources
we have to set the Identity of
application pool to Local System.
LocalServices Built-in account has
privileges of an authenticated local
LocalServices
user account. It does not have any
network access permission
This is the default Identity of
Application Pool NetworkServices has
NetworkServices
privileges of authenticated local user
account.

• Creating and Assigning Application Pool
• Open IIS Console, Right Click on Application Pool Folder >
Create New


• Give the Application Pool ID and Click Ok.

• Now, Right Click on the Virtual Directory (I am using
StateServer Web sites) and assign the
StateServerAppPool to StateServer Virtual Directory.


• So, this StateServer Web sites will run independently with
StateServerAppPool. So any problem related with other
application does not affects your Application. This is the
main advantages of creating application pool separately.
• Web Garden
• By default Each Application Pool runs with a Single Worker
Process (W3Wp.exe). We can Assign multiple Worker
Process With a Single Application Pool. An Application Poll
with multiple Worker process called Web Gardens. Many
worker processes with same Application Pool can
sometimes provide better throughput performance and
application response time. And Each Worker Process
Should have there own Thread and Own Memory space.

• As Given in Picture, in IIS Server there may be multiple
Applicationpool and each application pool having at least
a single Worker Process. Web Garden should contain
multiple Worker process.
• There are some Certain Restriction to use Web Garden
with your web application. If we use Session Mode to "in
proc", our application will not work correctly because
session will be handled by different Worker Process. For
Avoid this Type of problem we should have to use Session
Mode "out proc" and we can use "Session State Server" or
"SQL-Server Session State".
• Main Advantage : The worker processes in a Web garden
share the requests that arrive for that particular
application pool. If a worker process fails, another worker
process can continue to process requests.
• How To Create Web Garden ?
• Right Click on the Application Pool > Go To Performance
Tab > Check Web Garden Section (Highlighted in Picture )

• By default it would be 1 , Just change it to more than one .
• How Session Depends on Web Garden ?
• I have already discuss that, InProc is handled by Worker
Process. Its keeps data insides its memory object. Now If
we have multiple Worker Process, then It would be very
difficult to handled the session . because, Each and every
Worker process has it own memory, so If my first request
goes to WP1 and its keep my session data and Second
Request goes to WP2 and I am trying to retrieve session
data, it will not able to return . Which will throw error. So
please avoid Web Garden in InProc Session Mode.
• we can use StateServer or SQLServer Session mode in
case of Web Garden , because I have already explained
these two session mode does not depends on Worker
Process . In my example, I have also explain, If you restart
the IIS then also you are able to get session data.
• In Short ,
Session Mode Recommended
InProc No
StateServer Yes
SQLServer Yes
• Web Farm and Load Balancer:
• This is the most common term that is used in production
deployment . This terms comes, when we are using
Multiple Web Server for deploying our product. The main
reason behind the scene is to distribute the load over the
multiple server. Load balancer is used to distribute the
load on those server.

• If we check the diagram, Client request the url and it will
hit a Load Balancer, which decides which server to
access. Load balancer will distribute the traffic over the
all web server.
• Now how does it affects session
• Handling Session in Web Farm and Load Balancer
Scenarios
• Handling session is one of the most challenging job in web
farm .
• InProc : In InProc session mode, session data stored in In-
Memory Object of worker process. So each and every
server have its own Worker process and they keep
session data inside the memory.


• If One server is down in time and request come to
different server, user is not able to get session data. So, it
is not recommended to use InProc in Web Farm .
• StateServer :I have already explained that what a state
server is, how to configure a StateServer etc. Now From
this Web farm scenarios you can easily understand that
how much it is important, because all session data will be
stored in a Single location .


• Remember, In a web farm, make sure you have the same
<machinekey> in all your web servers. and Other things
are all same as I have describe earlier. All web.config
having the same configuration (stateConnectionString) for
Session State.
• SQL Server : This is another approach even best one that
we can use in web farm. We need to configure the data
base first. The steps I have already covered .


• as shown in the above picture, all web server session data
will be stored in a single SQL Server Database. And it can
be easily accessible. Keep one thing in mind, you should
serialize object in both state server and SQL Server mode.
Any time if one of the web server goes down, Load
balancer distribute the loads to other server and that user
can able to read session data from server, because data is
stored in a centralized DB server.
• In summary, we can use either of state server or SQL
server session mode in web farm . We should avoid the
InProc
• Session And Cookies
• Clients use cookies to work with session. because the
client needs to present the appropriate session ID with
each request. we can do it in following ways
• Using cookies: ASP.NET creates a special cookies named
ASP.NET_SessionId automatically when the session
collection is used. This is the default. Session ID is
transmitted through that cookies .
• Cookie Munging : Some older browser doest not support
cookies or user may disable cookies in there browser, in
that case ASP.Net transmitted session ID in a specially
modified (or “munged”) URL.
• How Cookie Munging Works ?
• When user request for a page on a server, Server
encoded the session id and add it with every href link in
page. When user click any links ASP.NET decodes that
session id and passes it to the page that user requesting.
Now the requesting page can retrieve any session
variable. This all happens automatically, if ASP.NET
detects that the users browser does not support cookies.
• How to Implement Cookie Munging ?
• For that we have to make session state Cookie less.

• Removing Session From Session Variable


• Following are the list of methods that are used to
removing the session .
Method Description
Session.Remove(strSessionName); Remove an Item from Session State Collection
Session.RemoveAll() Remove all items from session collection
Remove all items from session collection Note:
Session.Clear() There is no difference between Clear and
RemoveAll. RemoveAll() calls Clear(), internally.
Session.Abandon() Cancels the Current Session
• Enabling and Disabling Session :
• For performance optimization we can enable or disable
session. because each and every page read and write
access of the page, and this involves some performance
overhead. So its always better to enable and disable
session based on requirements rather than make it enable
always. we can enable and disable the session State in
two ways:
• Page Level
• Application Level
• Page Level :
• we can disable session state in page level using
EnableSessionState attributes with in Page directive.


• This will disable the session activities for that particular
page
• Same way we can make it read only also , It will permit to
access session data, but it will not allow writing data on
session.


• Application Level :
• Session state can be disabled for all over the web
application using EnableSessionState property in
Web.Config .


• Generally we are use Page level, because some of page
may not require any session data or may be only read the
session data.
• Ref. & for more Information : How To Disable ASP.Net
Session State in ASP.NET
• Summary
• Now hope you are familiar with Session, Use of it, how to
apply it in web farms etc in ASP.NET 2.0. So as a
summary,
• The In-Process(InProc) Session provider is the fastest
method, because of everything stored inside the
memory. Session data will be loss if we restart web
server or if Worker Process Recycles. You can use in
small web application where number of users are less. Do
not use InProc in Web Farm.
• In StateServer Session modes Session data maintain by
aspnet_state.exe. Its keeps session data out of Web
server. So any issue with web server does not affect
session data. You need to Serialized object before storing
data in StateServer Session. we can use it in web farm
also.
• SQLServer Session modes store data in SQL Server, we
need to provide the connection string. Here we also need
to serialize the data before storing it to session. This is
very useful in production environment with web farm
mode.
• we can use Custom provider for custom data source or
when we need to use some existing table to store session
data. We can also create our custom sessionID in Custom
mode. But it is not recommended to create your own
custom provider. Its recommended to use any third party
provider.

Disadvantages of Client side validation:

• The disadvantage of javascript validation is that users can have javascript turned
off and therefore can submit invalid data.

So even if you do have javascript validation you still need server-side validation
too.

You might also like