you're reading...

Hour 4: Understanding 5 ASP.NET State management techniques in 5 hours

Session State Management: It is a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state.


1)    Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit. 

2)    Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information. 

3)    Raise appropriate session management events. In addition, you can write application code leveraging these events. 

How and where ASP.NET session state stores data: We know how ASP.NET handles an HTTP request; actually it flows through a HTTP pipeline of different modules that can react to application events. One of the modules in this chain is the SessionStateModule (in the System.Web.SessionState namespace). The job of this module SessionStateModule is to generate the session ID, retrieves the session data from external state providers, and binds the data to the call context of the request. But actually SessionStateModule doesn’t actually store the session data. Instead, the session state is persisted in external components, which are named state providers.

These state provider are below;

1)    In-Memory objects.

2)    Windows Service (aspnet_state.exe)

3)    Tables in ASPState database.

What is role of session id: Session state is menained by Session ID which is the only piece of information that is transmitted between the web server and the client. When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the serialized data from the state server, converts it to live objects, and places these objects into a special collection so they can be accessed in code. This process takes place automatically.

How session state works: For session state to work, the client needs to present the appropriate session ID with each

request. The final ingredient in the puzzle is how the session ID is tracked from one request to the next. You can accomplish this in two ways:

1)    Using cookies: In this case, the session ID is transmitted in a special cookie (named ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is used. This is the default

1)    Using modified URLs: In this case, the session ID is transmitted in a specially modified (or “munged”) URL

How to use Session State:

Class Name: System.Web.SessionState.HttpSessionState

Storing dataset in session variable,

Session[“ProductsDataSet”] = dsProducts;

Retrieving value from session variable;

dsProducts = (DataSet)Session[“ProductsDataSet”];

When session variable value will be lost:

1)    If browser is closed and restarted by user.

2)    If same page is accessed or browsed via a different browser window

3)     If the user accesses the same page through a different browser window, although the session

Will still exist if a web page is accessed through the original browser window. Browsers        differ on how they handle this situation.

4)     If the session times out because of inactivity. By default, a session times out after 20 idle minutes.

5)     If the programmer ends the session by calling Session.Abandon().

6)    When application domain will be recreated.

How to configure Session State in web.config

Below is a sample config.web file used to configure the session state settings for an ASP.NET application?





sqlConnectionString=”data source=;Integrated Security=SSPI”










What are Session Modes:

1) InProc:

1.1)        ASP.NET to store information in the current application domain.

1.2)        Once the server is restarted, the state information will be lost. i.e. session state is managed in process and if the process is re-cycled, state is lost.

1.3)        Its default option

1.4)        High performance because  the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process

2)    Off:

2.1) This setting disables session state management for every page in the application.

2.2) it can provide a slight performance improvement for websites that are not using                                  session state.

3)    StateSever:

3.1) the objects you store in session state must be serializable.

3.2) ASP.NET will use a separate Windows service for state management

3.3) the problem is that increased time is delay imposed when state information is transferred       between two processes. If you frequently access and change state information, this can make          for a fairly unwelcome slowdown.

To use this in your application, you need to start it

Browse this path:

Select Start ➤ Programs ➤ Administrative Tools➤ Computer Management➤ Services and Applications➤service node; Find the service called ASP.NET State Service in the list.

From here you can manually start and stop this servie.

1) Custom:

4.1) while using custom mode, we need to indicate what session state store provider to use by      supplying the customProvider attribute.

4.2) we use custom mode when we need to store session information in a database other than      SQL Server or to use an existing table in a database that has a specific schema.

4.3) the customProvider attribute directs to the name of a class that’s part of web application         in the App_Code directory, or in a compiled assembly in the Bin directory or the GAC.

What is CookieLess attribute in session state configuration setting.


This feature with which we can configure for ASP.NET session state is cookieless session state. Essentially this feature allows sites whose clients choose not to use cookies to take advantage of ASP.NET session state.

How it works: ASP.NET will modify relative links found within the page and embed this ID. Thus, as long as the user follows the path of links the site provides, session state can be maintained. This is done by modifying the URL with an ID that uniquely identifies the session:


Lets us understand about these attributes in details

1)    useCookie: Cookies are always used, even if the browser or device doesn’t support cookies or they are disabled. This is the default

2)    useURI: Cookies are never used, regardless of the capabilities of the browser or device. Instead, the session ID is stored in the URL.

3)    UseDeviceProfile: ASP.NET chooses whether to use cookieless sessions by examining the BrowserCapabilities object. The drawback is that this object indicates what the device should support

4)    AutoDetect: ASP.NET attempts to determine whether the browser supports cookies by attempting to set and retrieve a cookie

How to control timeout for session state: Timeout specifies the number of minutes that ASP.NET will wait, without receiving a request, before it abandons the session,


You can also programmatically change the session time-out in code.

Session.Timeout = 10;

Reference read from msdn here:


Session Example: The idea here is to create product detail class and save the items in session and bind it to listbox. On selecting product from listbox we provide full detail for that product. Here we also show and use session attribute to show session id , mode, cookieless etc.

Product class:

public class Product


public string name;

public string description;

public double cost;

public Product(string sname, string sdescription, double scost)


name = sname;

description = sdescription;

cost = scost;



Creating product object , storing them in session variable and adding it in listbox

protected void Page_Load(object sender, EventArgs e)


if (!Page.IsPostBack)


Product product1 = new Product(“laptop”, “Apple”, 1234);

Product product2 = new Product(“camera”, “Sony”, 5433);

Product product3 = new Product(“watch”, “Omega”, 6789);

Session[“product1”] = product1;

Session[“product2”] = product2;

Session[“product3”] = product3;






// Display some basic information about the session.

// This is useful for testing configuration settings.

lblSession.Text = “Session ID: ” + Session.SessionID;

lblSession.Text += “<br>Number of Objects: “;

lblSession.Text += Session.Count.ToString();

lblSession.Text += “<br>Mode: ” + Session.Mode.ToString();

lblSession.Text += “<br>Is Cookieless: “;

lblSession.Text += Session.IsCookieless.ToString();

lblSession.Text += “<br>Is New: “;

lblSession.Text += Session.IsNewSession.ToString();

lblSession.Text += “<br>Timeout (minutes): “;

lblSession.Text += Session.Timeout.ToString();


On More information click , we are retriving more details from session variable and displaying.

protected void cmdMoreInfo_Click(object sender, EventArgs e)


if (lstItems.SelectedIndex == -1)


lblRecord.Text = “You have not seleected any product”;




string key = “product” + (lstItems.SelectedIndex + 1).ToString();

Product p = (Product)Session[key];

if (p != null)


lblRecord.Text = “Name: ” + p.name;

lblRecord.Text += “<br>Description: “;

lblRecord.Text += p.description;

lblRecord.Text += “<br>Cost: $” + p.cost.ToString();




This is end of your 4th hour of reading Hope you enjoyed it.Click to go on 5th  hour of reading


About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.


2 thoughts on “Hour 4: Understanding 5 ASP.NET State management techniques in 5 hours

  1. Hi, Neat post. There is an issue together with your website in internet explorer, might check this?
    IE still is the market chief and a large component of people will leave out
    your excellent writing due to this problem.

    Posted by steel shooting targets | 2013/08/18, 12:01 AM
  2. You could definitely see your skills in the
    work you write. The arena hopes for more passionate writers such as you who are not afraid to mention how they believe.

    Always go after your heart.

    Posted by omega juicer model 8005 | 2013/09/10, 6:47 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


Follow Vishalnayan on WordPress.com

Blog Stats

  • 217,514 hits


%d bloggers like this: