ASP.NET, Coding

Web Session Management

  1. Introduction:

    Session is the process of interactive information between communication devices that is established at a certain time and torn down at a later time. This semi-permanent interaction between devices is also known as communication session.

    Communication sessions can be implemented as part of protocols and services either at the application, or at session or at transport layers (as in OSI – Open Systems Interconnection – Basic Reference Model). In computing login session is the period of activity between a user logging in and logging out of an application/system. To a very high-level, sessions can be categorized as:

    • Stateful session
    • Stateless session

    Stateful sessions are those where the communication history is saved in order to be able to communicate. Hence the system can easily identify the user as an existing one. For example, maintaining the user details when he/she logs into the system.

    Stateless sessions are those where the history is irrelevant for the system to process. Each and every request/communication from the user will be considered as the request from the new user and there will not be anything that will be stored in the history.

  2. Session Management:

    Session Management is the process of keeping track of a user’s activity across sessions of interaction with the computer system by the user. Typical information maintained in the session across requests is called session state. Session state may include both:

    • Information visible to the user (shopping carts, etc)
    • Invisible application control information (user preferences and settings, etc)

    The session is controlled by a service called the session manager and the applications participating in the session are called session clients.In a typical computer application, we normally consider the desktop and web environments. Following sections describes more on these areas:

    1. Desktop Environment

      Typical tasks in this environment includes:

      • Keeping track of which applications are open
      • Which documents each application has opened
      • User preferences on last used document
      • Any shared mapping that’s been created
      • User Profile which stores the user login/logout information

      These data will be stored in the session so that when the same user logs in back at a later time, all of the user settings can be restored.

    2. Web Environment

      In a web environment, HTTP will be the first thing that will come to our mind (of course, next to your browser). HTTP is a stateless protocol where each requests (GET or POST) establishes a new TCP connection to the server.

      Session management is the technique used by the web developer to make the stateless HTTP protocol support session state. For example, once a user has authenticated to the web server, next HTTP request should not cause the web server to ask for credentials again.

      The session information is stored in the web server using the unique identifier named Session ID (Session Identifier), which is generated from the first request from the user in the application (say by authentication process). These Session IDs and other session information (authentication details, etc) are stored on the web server using different techniques like local memory, flat files and, databases.

      There are basically three techniques of managing sessions in a ASP.Net application as:

      1. InProc
      2. OutProc with State Server
      3. OutProc with SQL Server database
  3. Session Types

    Web applications are by nature stateless. This is considered as both advantage and a disadvantage. When resources are not being consumed, scalability is tremendously improved in stateless; while the lack of state reduced functionality severely hence a disadvantage.

    ASP.Net’s session object makes it easy for developers to maintain state in a Web application. As mentioned above, in .Net technology InProc and OutProc are the two session management techniques.

    1. In-Proc technique

      This is the most used and commonly used technique to manage session as it is very simple and easy to maintain. Here all session data will be stored within the managed memory of the same web server where the application runs i.e., the same ASP.Net process (aspnet_wp.exe).

      This is the ASP.Net default session management technique, and it offers the fastest response time, but does not work in a Web Farm.

      There is not extra session required on your application to use the basic In-Proc sessions as it is supported by default in all web application until unless explicitly specified in the web.config as:

              <sessionState mode="Off">
              

      You can add or assigning values to the session variables as below. You do not need to declare any session variables like your application variable, simple assign values to it. If there is an already existing value, it will overwrite the previous data.

          Session["<variable name>"] =<data>
          

      You can use the following syntax to retrieve the session data. Make sure that you should typecast it to the respective object before use. Also if you try to refer an object before assigning a value, it will throw NOR (Null Object Reference Exception)

          Session["<variable name>"].ToString() // for string object
          
          (<Object Type>) Session["<variable name>"] // type case to the associated object
          

      In Web farm, any request from the users will be directing to any one server in the web farm, so that the total load will be equally managed by all these servers which improves the application overall performance. But because of this farm, a new issue arises, when a request from the user been authenticated and processed by one server, the users, second request may go to another server in the farm as part of load balancing and because of that the session been lost and the user will be keep on prompting for credentials. This is a major limitation of In-Proc session management technique.

    2. Out-Proc technique
      As the name states, this technique resembles the storage of session data out side the ASP processor memory. When more and more users start using the web application, normally the load on the web server went up which resulted in poor performance. In order to survive from the issues related to this scenario, the concept of web farm/garden been invented.

      Analysis went on and finally the idea of storing these session information in an external device came up and these are known as Out-Proc techniques. There are two version of this – one saving the data on a separate server and in the other type saving the data in a SQL database. Both these processes are explained below:

      1. State Server Session Management
        In this, all the session data are serialized and stored in memory in a separate process (aspnet_state.exe). This process can either reside on any one of the web server or can be run as a separate stand alone server. Hence a dedicated session state server is shared by all servers in a web farm and provides scalability of the session objects across the servers.

        This also have some limitations or disadvantages as, it cannot store data persistently. If a dedicated session state server goes down for any reason, all session data is lost.

        Also, when you go for this technique in a web farm, make sure that you have considered the following facts. This can also be said as the limitations or constraints of State Server Session Management technique.

        • All web servers should have the same machine key
        • All session objects must be serializable
        • Application path of the website should be identical in all web server

        For using State server for session management require the following changes in your web.config file:

                
                <sessionState   mode                               = ”StateServer”
                                               stateConnectionString = ”tcpip=XXX.XXX.XXX.XXX:XXXX” 
                                               cookieless                      = ”false” 
                                               timeout                            = ”20” />
                
                where;
                Mode                               : specifying to use StateServer
                StateConnectionString: Connection string to locate State Server
                Cookieless                    : False mean, application will be using client-side cookies to store data
                Timeout                          : session timeout after 20 minutes
                
                
      2. SQL Server Session Management
        SQL Server is another alternative for storing session state for all of the servers in a web farm. Here, the session data is serialized and stored in the SQL Server.

        This also cannot store data persistently even though it is stored in the SQL Server. If the SQL Server is stopped, the session data is lost. But by making some changes, state can be stored persistently but not permanently. If the SQL Server is configured to store state persistently and is down for a longer than the ASP.Net session timeout interval (which is set in web.config), the session state data is lost.

        For using State server for session management require the following changes in your web.config file:

                 <sessionState   mode                               = ”SqlServer”
                                               stateConnectionString = ”data source=;user id=UID;password=xxx” 
                                               cookieless                      = ”false” 
                                               timeout                            = ”20” />
                
                where;
                Mode                            : specifying to use SQL Server
                SqlConnectionString: Connection string to the SQL Server. Instead of specifying the credentials in the connection string,
                                                        you could even use the integrated security
                Cookieless                 : False mean, application will be using client-side cookies to store data
                Timeout                       : session timeout after 20 minutes
                

        Limitations or constraints in using SQL Server for session management are listed below. Make sure that you have planned for these:

        • All session objects must be serializable
        • Application path of the website should be identical in all web server
        • Both integrated security in SQL State and impersonation in ASP.Net will not go in sync. They are mutually exclusive.
      3. Summarizing
        Session Type Storage Location Performance Robust
        In Proc Live session on web server Fastest, but lower in performance if more data in memory Lesser, as data will be lost if recycles the server
        Out-Proc with State Server Serialized session data and stored in another server 15% slower and lower performance if more data are serialized In web farm, store in a single server. But risk in single point of loss
        Out-Proc with SQL Server Serialized session data and stored in SQL Server 25% slower and lowest performance if more data are serialized/td>

        Better than State Server as it has the option of persistence, but have the risk of being single point of loss
  4. How to create SQL database for managing the session?
    As mentioned in the earlier sections, you should have a SQL Server setup for the SQL State session management. But don’t worry; ASP.Net itself can build it for you. Please locate the tool named aspnet_regsql.exe under C:WINNTMicrosoft.NETFrameworkv2.0.50727 (in XP)

    It also provides a lot of options to create or setup the SQL server for sessions. Some of them are mentioned below (note that all these are case sensitive):

    -ssadd Tells the tool to create SQL database for session storage
    -sstype following are the three acceptable values

    t: Temporary: session data will be stored in ‘tempdb’ database and Stored Proc for managing session data will be stored in another database ‘ASPState’. Data won’t be persistent while using this approach. Restarting the DB will clear all session values.

    p: Persisted: both session data and Stored Proc to manage these data are stored in the single database ‘ASPState’. All session data will be persisted to disk

    C: Custom: both session data and Stored Proc to manage these data are stored in a single database but with a custom name (i.e., user database). If you specify this, then the below option –d must be provided.

    -S Specifies the Server name where the SQL instance resides
    -d Specifies the custom database name. Only required when you specify custom option for –sstype
    -U User Id to login to the SQL server. Not required of –E is specified.
    -P Password for the above user id to login to the SQL server. Not required of –E is specified .
    -E Specifying the usage of Windows Authentication when connecting to the SQL Server. Use instead of –U & -P options.

    Below are some examples on how to define/create the SQL State Session:

    C:WINNTMicrosoft.NETFrameworkv2.0.50727> aspnet_regsql.exe –ssadd –sstype t –S [SQL Server Name] -E
    
    C:WINNTMicrosoft.NETFrameworkv2.0.50727> aspnet_regsql.exe –ssadd –sstype c –S [SQL Server Name] –d [Database Name] –U [SQL User Name] –P [SQL User Password]
    

    In above two cases, web.config will appear as

     <sessionState   mode                               = ”SqlServer”
                                   sqlConnectionString    = ”data source=[server];initial catalog=[database];user id=[user id];password=[password]” 
                                   cookieless                     = ”false” 
                                   timeout                            = ”20” />
    
     <sessionState   mode                               = ”SqlServer”
                                   sqlConnectionString    = ”data source=[server];initial catalog=[database];trusted_connection=true”
                                   cookieless                      = ”false” 
                                   timeout                            = ”20” />
    
  5. Conclusion

    If your application is deployed in a single server, it is recommended to use In-Proc Session Management approach. By default all environments will support this approach and there is not additional task that needs to be considered.

    If you are considering going for a Web Farm, where multiple server holds your application, things will go a little tricky. Either session sticky should be allowed in the load balancer or else the only approved approach would be to go with SQL State Session Management.

    Single Server Environment : In-Proc Session Management
    Web Farm                       : Session Sticky or SQL State Session Management
    

    In either case – when you are using Integrate Services or SQL Authentication – make sure that those users have the access to this new database.