Understanding ASP.NET State management techniques-Part iv

No.of Views2097
Bookmarked0 times
Downloads 
Votes0
By  Vishal Nayan   On  02 Jun 2011 08:06:51
Tag : ASP.NET , 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.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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.

Advantages:

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
2)    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?

<sessionState
      
      mode="InProc"
      stateConnectionString="tcpip=127.0.0.1:42424"
      stateNetworkTimeout="10"
      sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
      sqlCommandTimeout="30" 
      allowCustomSqlDatabase="false"
      useHostingIdentity="true"
      cookieless="UseCookies" 
	cookieName="ASP.NET_SessionId"
      regenerateExpiredSessionId="false"
      timeout="20"
      customProvider="">

    </sessionState>

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.

 

Image Loading

From here you can manually start and stop this servie.
4)    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.

cookieless="UseCookies"
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:

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

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,

timeout="20"
You can also programmatically change the session time-out in code.
Session.Timeout = 10;

Reference read from msdn here:
http://msdn.microsoft.com/en-us/library/ms972429.aspx

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;

            lstItems.Items.Clear();
            lstItems.Items.Add(product1.name);
            lstItems.Items.Add(product2.name);
            lstItems.Items.Add(product3.name);
        }

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

 Image Loading

Download Samples

Download source files -13 kb

This is end of your 4th part of reading Hope you enjoyed it.

 
Sign Up to vote for this article
 
About Author
 
Vishal Nayan
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-02 Apr 2011
Home Page-
Blog Page-http://vishalnayan.wordpress.com
Vishal is a seasoned professional with hand on experience on Microsoft technologies. He always look for challenging assignment that allows him to learn newer technologies while utilizing his experience of project development and software engineering ethics. In spare time vishal can be found reading business and political personalities, acts as critics at columnist , writing poetries, bird watching , singing ,cooking. He have strong interests in Indian business and political arena and want to be an active one someday. He is also a part-time trainer on framework , WCF and Silverlight. reach him at vishalnayan@gmail.com
 
 
Other popularSectionarticles
    Cookie is one of several ways to store data about web site visitors during the time when web server and browser are not connected. They are small files That are created on the client’s hard drive (or, if they’re temporary, in the web browser’s memory).
    Published Date : 02/Jun/2011
    It store global objects that can be accessed by any client.It supports the same types what session state support which are of type objects, retains information on the server, and uses the same dictionary-based syntax. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
    Published Date : 09/May/2011
    Http protocol is stateless, so we need to maintain state on Client side or Server side. For this time I am going to discuss about the maintaining state on Server Side with one programming practice.
    Published Date : 10/Jan/2011
    Now web application framework, no matter how advanced, can change that HTTP is a stateless protocol. So inherently we should also forget our users, but unfortunately we cannot.ASP.Net Framework provides us features by which we can maintain states of your users.
    Published Date : 26/Jun/2010
    There is Lots of ways and Techniques Are available to Manage you State on Web in Aspnet
    Published Date : 06/May/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top