Thursday, August 6, 2009

Session/State Management

State Management
No web application framework, no matter how advance, can change that HTTP is a stateless protocol. This stateless protocol makes our live easy and inherently we should also forget our users, but unfortunately we cannot. There is a lot at stake if we forget our user.
ASP.Net Framework provides us features by which we can maintain states of your beloved users. We do it by the 2 options provided to us. They are Client Side State Management and Server Side State Management.
There are many techniques that we can apply to management states both at Client or Server sides.
Client Side State Management
• Cookies
• View State
• Hidden Fields
• Control State
• Query String
Server Side State Management
• Session State
• Application State

• Profile Properties
In this article we will be discussing Session based State Management and how to do InProc, State and SQL Server State Management.
Session
Sessions are stored server side and are unique to every user. Every user accessing the application is given a unique Session Id when the application is first accessed by him or her. For every other request that the user posts to the server, the Session Id is shared by the user and server can recognize who the user is.
In its simplest form, session can be created as
Session[“mySession”] = “some data”;
And can be retrieved as string data = Session[“mySession”].ToString();
Modes of Sessions
In-Process also known as In-Proc
Out-of-Process also known as State Server,
SQL Server
In-Process

This model is the fastest, most common and the default behavior of Sessions. Session information is stored inside IIS (Internet Information Service). Please make a note that what ever model you use there will be no change in assigning or retrieving information from sessions. However there few details that you need to look for when working with In-Process Sessions Model:
1. If you change Web.config, Global.asax, application restarts itself and as a result session information is lost.
2. Your information also lost if you change your code files in your App_Code folder.
3. If your IIS restarts, this results in the same.
4. Handy events Session_Start and Session_End in Global.asax file (effective only in In-Process).
5. Web.config file timeout attribute
To configure your application for in-proc session management, the most common and basic set up of your web.config file is in the following manner
Timeout attribute takes numeric values and the unit is Minutes. In this case user’s session will expire in 20 minutes time.
Out-Of-Process
Out-Of-Process State Sessions are stored in a process which runs as a Windows Service called ASP.NET State Service. This service is not running by default and of the many, 2 options to run this service are:
1. Click Start>Run. Type cmd to open Command Prompt. Type net starts aspnet_state. If the service is already not running, this command will start the service.
2. Right click My Computer and select Manage. Expand Services and Application, click Services. In the right panel look for ASP.NET State Service and start by right clicking it and selecting Properties option from the context menu. Select Start up Type as Automatic and start the service by clicking the Start Button.
Each model has its benefits and drawbacks. You as a designer of the application have to take this decision of what model to adopt. You have to decide between speed, reliability and expansion.
There are other things that you need to know about this model.
1. Using this model, it is not necessary that the service in running on the same server on which your application is running/deployed. Session information can be stored on any server/physical machine on which this service is running and is accessible to your Application Server.
2. timeout attribute applies to this model as well.
3. Session_End Event in Global.asax file is not fired using this model.
4. Objects must be Seriablizable before they can be stored in Session.
To configure your application for out-proc session management, the most common and basic set up of your web.config file is in the following manner
stateConnectionString attribute holds the server name where you want to maintain out session information. 127.0.0.1 is your local host, the current machine on which your application is running and 42424 is the port on which State Service listens.
SQL Server
Session information can also be stored in SQL Server. To configure this most reliable option to maintain session information, perform the following step.
Open Visual Studio Command Prompt and run the query aspnet_regsql –S [localhost] –U [user id] –P [password] –ssadd –sstype p
This command will configure Sql Server based Session State Management on your machine. The configuration is not yet completed. There are other things that you need to know about this model.
1. Sql Server based session management is the slowest but reliable of all.
2. Sql Server based session management is not effected by web farming or web gardening issues.
3. You can explore other command line arguments by running aspnet_regsql -?
4. The table created after running the above command is ASPStateTempSessions.
To configuration your application for Sql Server session management, the most common and basic set up of your web.config file is in the following manner
sqlConnectionString attribute holds connection string of the location of your database and user id and password to connect to it. There are other multiple options that can be used with aspnet_regsql statement.

1. Understanding Session State Modes
Storage location
InProc - session kept as live objects in web server (aspnet_wp.exe)
StateServer - session serialized and stored in memory in a separate process aspnet_state.exe). State Server can run on another machine
SQLServer - session serialized and stored in SQL server
Performance
InProc - Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.
StateServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 15% slower than InProc. However, the cost of serialization/deserialization can affect performance if you're storing lots of objects. You have to do performance testing for your own scenario.
SQLServer - When storing data of basic types (e.g. string, integer, etc), in one test environment it's 25% slower than InProc. Same warning about serialization as in StateServer.
Performance tips for Out-of-Proc (OOP) modes
If you're using OOP modes (State Server or SQL Server), one of your major cost is the serialization/deserialization of objects in your session state. ASP.NET performs the serialization/deserialization of certain "basic" types using an optimized internal method. ("Basic" types include numeric types of all sizes (e.g. Int, Byte, Decimal, String, DateTime, TimeSpan, GUID, IntPtr and UIntPtr, etc)
If you have a session variable (e.g. an ArrayList object) that is not one of the "basic" types, ASP.NET will serialize/deserialize it using the BinaryFormatter, which is relatively slower.
So for performance sake it is better to store all session state data using one of the "basic" types listed above. For example, if you want to store two things, Name and Address, in session state, you can either (a) store them using two String session variables, or (b) create a class with two String members, and store that class object in a session variable. Performance wise, you should go with option (a).
Robustness
InProc
- Session state will be lost if the worker process (aspnet_wp.exe) recycles, or if the AppDomain restarts. It's because session state is stored in the memory space of an AppDomain. The restart can be caused by the modification of certain config files such as web.config and machine.config, or any change in the \bin directory (such as new DLL after you've recompiled the application using VS) For details, see KB324772. In v1, there is also a bug that will cause worker process to restart. It's fixed in SP2 and in v1.1.
If you're using IIS 6.0, you may want to go to IIS Manager, go to Application Pools/DefaultAppPool, and see if any of the parameters on the Recycling and Performance tabs are causing the IIS worker process (w3svc.exe) to shutdown.
StateServer - Solve the session state loss problem in InProc mode. Allows a webfarm to store session on a central server. Single point of failure at the State Server.
SQLServer - Similar to StateServer. Moreover, session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster.
Caveats
InProc
- It won't work in web garden mode, because in that mode multiple aspnet_wp.exe will be running on the same machine. Switch to StateServer or SQLServer when using web garden. Also Session_End event is supported only in InProc mode.
StateServer
- In a web farm, make sure you have the same in all your web servers.
- Also, make sure your objects are serializable. .
- For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical (case sensitive) in all the web servers in the web farm.
SQLServer
- In v1, there is a bug so that if you specify integrated security in the connection string (e.g. "trusted_connection=true”, or "integrated security=sspi"), it won't work if you also turn on impersonation in asp.net.
- Also, make sure your objects are serializable. Otherwise, your request will hang. The SQLServer mode hanging problem was fixed in v1.1. The QFE fix for KB 324479 also contains the fix for this problem. The problem will be fixed in v1 SP3 too.
- For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical (case sensitive) in all the web servers in the web farm. See KB 325056 for details

No comments: