In this article I am trying to explain about state management in Here I cover all most all concepts include in State Management like ViewState, serialization and de-serialization ,Cookies, Applications, sessions, cache and User controls. Statemanagement: statemanagement:

1) Why Statemanagement…?
A) Web is stateless because of HTTP.

2) What is stateless environment..?
A) In stateless environment Application & client will not maintain any status of there process. Every request of client is identified as a new request. Application that we develop required lot of statefull behaviour. So,we have to implement statemanagement options provided by making our Application statefull.. statemanagement options: provides almost all statemanagement options in a simplified method. Starting from Control level till Application level it procides all state support. As a web developer it is very important to understand the state requirement properly and apply the available options. To start with statemanagement first we have to manage controls and objects ( varriables ) with in the date to retain their values. provides a logic or concept called " VIEWSTATE" for providing controls and varriables state.

Controls level:
For controls by default provides state using EnableViewState & ViewStateMode properties we can control the statemanagement options.

Varriables level:
For varriables we have to explicitly maintain State using ViewStateObject provided by

3) How maintains state for it's Controls..?
How ViewState for controls work…?

A) -> client makes a request for page
-> Server process the page and concatenates all the result into a string.
-> This string is converted into base64 encoding format. Which is not encrypted and secured format.
-> This data is now stored In HiddenField. Which is created by implicitly.
-> Now, the page is returned to client along with user created control and also HiddenFields.
-> Now client modify & re-submit the page to server.
-> Server first off all now reads the hidden fields data. So, that it retains its previously given result. Then start processing the page where old result and new values.
-> It repeats this cycle for every client as long as client is working with current page.
-> This result in statefull behaviour of page related to controls.

1) In a new form drag & drop a textBox , HTML TextBox, label , Button controls.
2) And in code behind write the below code.
3) Declare a global varriable

Ex: int a;

4) Write a below code on button click event.


Protected void btn_Click(object sender,EventArgs e)

5) Then see the output.


1) To maintain state for our varriables & objects defind in page code window we have a viewstate property of a page. This property is a reference to a class called "StateBag".
2) This class is responsible for maintaining viewstate concept. So, when we use viewstate object then our data will also be stored as part of " StateBag".
3) Viewstate object can store any type of data, because StateBag class is of Type Object.
4) The only condition for viewstate Data is data should be in Serializable format. Because server has to Serialize& DeSerialize data between request & response.
5) By default viewstate data is not secure, but to make it secure we have a property called EnableViewStateMac is to be true.
Attribute as a part of <%page directive%>.


6) When secure more ustomize in encryption can be perform using MachineKey in web.config.
We can also perform these settings from IIS.
7) With all about consideration viewstate can be use effectively for statemanagement as well as performance.


1) Declare a statebag class, under satebag class write below lines of code.


2) Create a new page and declare label and button control.
3) Write a below lines of code in code behind.

Page Load event:


Button Click Event:

ViewState["a"]= Convert.ToInt32(ViewState["a"])+1;

1) What type of Data store in ViewState…?
1) Primitive ---- int,bool……
2) Complex ---- DataSet,List<> …



ViewState --> StateBag --> Object --> any value.

Store any type of data but serialization.

2) What is Serialization…?
A) The process of converting in- memory form of data into byte format is called Serialization.

3) Why Serialization..?
A) 1) To transfer Data over network.
2) To make object persist.

Note: By default DataSet is serializable object.

Normal class:
Class Employee
Serializable class:
Class Employee

Note: more complex type in ViewState will reduce the performance of Application. Because server has to perform more Serialization & DeSerialization process.

Multiple Page State:

Using ViewState and some other concepts like QueryString,Server.Transfer we get state in a single page (or) state in 2 pages.
If we want to maintain state for multiple pages of the website we have to use other concepts provided by and also by HTTP.
HTTP provides a concept called COOKIES which are supported by all web development coding, using COOKIES we maintain state for small amount of information.

HTTP Cookies:

A Cookie is _name, value pair just like a variable but which travel automatically between every request and response. Cookies are maintained by browser and we have to understand how they are maintained and consume them in our Application.
COOKIES are maintained by Browser a standard limitations are imposed by W3 and Browser. Every Cookie is created by Browser based on the Domain or based on the specific path given by Cookie.
20 COOKIEs per domain are allowed, and upto 4KB of data is restricted. These are W3 standards and Browsers like IE7 and above have higher limits than these.
COOKIES can store only simple form of data like strings.
A complex type cann't be directly stored in a Cookie.
Browser can allow (or) deny cookies for security, personalization and other reasons. In IE "@" we can configure this restriction in security & privacy options.

How to create COOKIE in….?

System.web.HTTPCookie is the class using which we can create, cookie in classical method or aother method of creating cookie is using
Ex: Response.Cookies[""].Value="10";
Prefered is using HTTPCookie class because it is type safe method.


1) In a form drag & drop a ListBox and Button controls.
2) In ListBox add a Country names in static manner.
3) On Button click event write a below code.

Protected void btn_click(Object sender,EventArgs e)
HTTPCookie obj=new HTTPCookie("Ckctry");


1) In a form drag & drop label and LinkButton controls.
2) On load event write a below lines of code.

Protected void Page_Load(object sender,EventArgs e)
3) On button click event write the below lines of code.

Protected void lnkbtn_Click(Object sender,EventArgs e)

How to search COOKIE in system..?

Goto Browser --> Tools --> internet options --> settings --> View files

MultiValued COOKIEs:

A multivalued cookie means like aan array of COOKIE where we can store multiple values in a single Cookie. The advantage of multi valued cookie is we can create more values in the form of cookie and also save space in saving disk storage of 4 KB. To create multi valued cookie provides values collections.

How to create multiple cookies..?

HTTPCookie obj=new HTTPCookie("UserDetails");

How to Read multiple Cookies….?

HTTPCookie ck=Request.Cookies["UserDetails"];

Limitations of COOKIEs…?

1) Size limitation ( 4 kb)
2) Type of data limitations ( string)
3) No.of cookies ( 20 cookies / domain)
4) Not secured
a) Client side - dependent on Browser
b) Travel in plain Textual format. (HTTP Headers)
c) Remote site – Access client Resources.

How to make COOKIES secured….?

By default cookies are not secured to make it secure we have to follow 2 things.

1) Encrypt values using some encryption algorithms supported by .net (or) which are provided by third party for .net( RS Algorithem), and store them as part of cookie.

2) Use secure property of cookie and communicate using HTTPS. For this server should be enabled (or) installed with SSL certificates. HTTPS communication mode means entire page data will be encrypted and used in Request / Response.


Browser --> tools --> Advanced --> Browser --> Use SSL3.0

For multiple page state only but with all functionality which is missing in cookies and also with more required features we have to use server side state management options.

Ex:, DataBase, Services, Cloud. options:

1) Application
2) Sessions
3) Cache

a) Server side statemanagement will have load on server because we will use server for processing our data. Advantage of server side state management is we get security with unlimited storage options.

b) provides Applications & sessions objects has key objects for storing data. Apart from state usage these objects also represents the process of and IIS.

c) Application object is used to represent the entire application process memory and we can use it for storing Application wide accessable data.

d) Session object represents the process which is created by exclusively for particular user. We can use it to store users specific information. Both these process are automatically started and stop. They are managed by server and it is important to consume them properly by a developer.

Application/ session – start up / shut down:

Because Application / session represents process their StartUp & ending is important to understand as well as to perform some Applications tasks.

An Application is automatically started by IIS. When first user makes a request for resources. Application shutdown will happen when all the users leave the Application & Application idel time out expire.

Session is started Automatically by for every new user. Every session is provided with session Id which is internally a COOKIE created by Session Id will travel between every request & response. A session is enabled by based on idle timeout. By default session idle timeout is 20min. which means if user doesn't request for server for 20min, then server will destroy the session. we can change this time in web.config as well as programatically using session object.

Note: from IIS 6.0 every Application is created in another process called Application pool. Which is collection of Applications. By maintaining Application with Application pool concept we get lot of benefits like scallable, recoverable and maintainability. We have to manage Application pool at IIS level not in project(or)

When Application starts…..?
Application started automatically when first user make a request
When Session starts….?
When new user make a request session will starts.
When Pool starts…?
When IIS will starts pool started.
When pool ends…?
When IIS will end pool ended.
When Session ends….?
Idel time 20 mins session will end.
When Application ends…?
All sessions are ended then Application end.

Consuming Application / Session objects of….:

As a developer we can consume both these objeccts in the form of events and varriables. Events for interpriting our project related tasks with process start up & shutdown like when Application starts go to DataBase and get the required values. To do this task we require Application start event so that we can write iur retrieval code another use is for state management we can create Application & session Data which provide global and individual access for all pages of site. Any type of data with no conditions can be stored as part of Application and session object.

1) Create a page user.aspx
2) Drag & Drop a label,textbox,button controls and the name of the label is "UserName" and Button name is "Submit".
3) Write a below lines of code on button click event.

Protected void btnSubmit_Click (Object sender,EventArgs e)
4) Create another page online.aspx.
5) Drag & Drop a label control.
6) Wrote a below lines of code on load event of the page.

Protected void Page_Load(object sender,EventArgs e)
Lbl.Text="Hi ,"+Session["User"].ToString();

Application / Session Events:

Application / session events are return in a separate file or special file called global.asax . this file is called as Active Server Application file. Because for every request first this file is executed and then the requested file.

A Project can have only one global.asax file and it should be placed in Root folder of our Application. By default Global.asax might not be present as part of some project templates. In such cases we have to add explicitly using AddNewItem option. Some events are already provided as empty procedure and we can additionally add other events. Some concepts like MVC, dynamic data are built on depending global.asax. In those projects global.asax file is automatically added. This file is configure by itself to reject any direct request which means user can't directly request global.asax file.

1) Open your global.asax file and write the following code in the specified location itself.
2) On your Application_Start of your global.asax wrtie below lines of code.


3) On your Session_starts of your global.asax write below lines of code.


4) On your Session_End of your global.asax write a belowlines of code.


5) Create a new page Status.aspx, drag & drop 2 label and button contrtols.
6) On load event of status page write a below lines of code.

Protected void Page_Load(Object sender,EventArgs e)
Session.TimeOut=1; // programtically mentioned session timeout.
7) On button click evetnt of status page write a below lines of code.

Protected void btn_click(Object sender,EventArgs e)
Label1.Text="Total Users: "+Application["TotlaUsers"].ToString();
Label2.Text="Online Users:"+Application["OnlineUsers"].ToString();
} Caching:

Caching is used to improve performance of Application like consistency & looking. We can virtually provide results to user and run the Application more faster. Cache means programmed memory Area. supports caching in different concepts but the important areas. Where user has to involve and produce results are 3 types.

1) Page output caching
2) Data Caching
3) Fragment Caching

All these caching methods objective is same but the only diff is what they cache.

1) In page output caching entire processed page request is cache. So , that for every request we provide output to uses from cacheinstead of performing process it.

2) It is also important to understand page life cycle with caching & without caching . User has to explicitly add cahcing support in order to cache the page. Different directives are provided to implement page output cache.

Page Output Caching:

Design the page with all content regularly and write code according to requirement.
Go to directives section and add

<%@OutPutCache Duration="n sec" VaryByParam="none/*/param"%> to the page.

Here ,

Duration specifies the amount of time we want to Cache the page OutPut Results.

VaryByParam is used to specify parameter based Caching when not required we specify none.

1) In a new page drag & drop label, textbox, button controls
2) On button click evetn write below lines of code.

Protected void btn_Click(Object sender,EventArgs e)
3) Go to directives section and add
<%@ OutPutCache Duration="60" VaryByParam="none"%>.

If we specify any parameter for VaryByParam attribute then store different cache results for different values. But the load to maintain values will also increase. Parameter can be any control or QueryString value.


In Data Caching we will Cache only the Data which we process with ours statement. It can be a simple varriable or it can be a complex type. Cache object of is used to create DataCaching this object is provided to overcome the drawbacks of Application object. Like consistency and looking and some programatic issues. Apart from this Cache obj has exclusive advantages like Time Based Expiry, Dependence Base Expiry, Managed By Runtime.

1) In a new form drag & drop button , link button name as Refresh and GridView controls.
2) On your button click event write the below lines of code.

DataSet ds;
Protected void btn_click (Object sender,EventArgs e)
ds=new DataSet();
ds=//Bind Data;

3) On your link button click event write below lines of code.

Protected void lnkbtn_Clck(Object sender,EventArgs e)
ds=new DataSet();
ds=//Bind Data;

The reason to provide Refresh button to our page is to make or generate consistence output. Without refresh button if we want to manage consistency logically. Then we can create admin page in order to update the Cache Data apart from doing logically we can also use TimeBased or DependencyBased features to provide consistency result.

The timebased Expire in Data Caching:

When we cache data by default it will be available as long as our Application is running apart from logical methods another updations methods that we can useare time based & dependency based expiry.

Time Based Expire:

In time based expire we will cache data and provide time for expire. So that we can reload over data from original datasource.
Cache object has insert method for creating time waste and dependence base expire object.

ds=//Bind Data;
//Time Based Expire

Note: After 1 min data will be loss. Why because here we add minutes 1.

Dependency Based Expiry:

To create dependency base expiry we use some insert method but with cache dependence class which will perform dependence based expiry. Some time we can't have logical update to our Cache Data and also time base expiry may not be better solution. In such cases we will go for dependency based Expire.
Note: We do either time based (or) dependency based not both at a time

Cache.Insert("ds",ds,new System.Web.Caching.CacheDependency(MapPath(.xml)));

Fragment Caching:

In this method we will Cache some part of our webpage unlike page output caching where entire data is Cache. Fragment caching is implemented with a concept but not with any new command or directive. Fragment caching is very important as we use web user control concept in it.

In user defined control vis created in 2 ways

--> Using web User Control
--> Using Custom control.

For any project user defind controls are required and it is very important to create new property and consume it with web user control we can create user defind controls with in the project and consumed it in the same project.

Web User Control:

• Add a new item --> web user control
A file with extension .ascx( Active Server control).
This file is created with< %@Control.....%>
Directive instead of <%@Page....%>
No default content like HTML, head are present in this file.
• Add <%@ OutPut Cache directive to the control.
• Go to Page and register to the control as it is compulsory to consuming a control.

Custom Control:

with custom control also we can create user defined control. Most of the standard controls are like custom controls. Unlike web user control. A custom control is prepared as .net library assembly . i.e. .dll. a custom control is created using the base control called web control. Which doesn't provide any functionality for a control. All content should be created and managed by developer only provides a separate project template for creating a custom control. We can use that and build a .net dll containing control.
The following steps are followed fro developing custom control.
• Start file --> new project --> web --> server control.
• A .cs file is created where a clas will be extending "web Control" class. Which is base class for all controls. Sample property & a method for displaying the control initial or processed output is also provided.
• User has to add all control functionality here i.e. in a class required for preparing a best control.
• We can add more controls to our project using add new item and server control template. Every cotrol is designed with same component building style.
• After preparing all these controls we have to just build our project and the result will be a .dll file containing all these controls.

Consuming the .dll file:

• Start a web site and create a tab in toolbox. So , that controls are not mixed up with other categories.
• Right click on the created tab and select choose items which will result in displaying of window showing all controls components that we can add / remove to our project.
• Browse our .dll file which is created and deserve how they are displayed in toolbox.
• From toolbox we can simply drag & drop automatically register created a control in pages.


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: