03 June 2016

Session State Modes in Asp.Net

Session


Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server.


HTTP is a stateless protocol, it can't hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information.


What do we need here? We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis


Advantages:




  • It helps maintain user state and data all over the application.

  • It is easy to implement and we can store any kind of object.

  • Stores client data separately.

  • Session is secure and transparent from the user.


Disadvantages:




  • Performance overhead on large volumes of data/user, because session data is stored in server memory.

  • Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.


Storing and retrieving values from Session


Session["UserName"] = txtUser.Text; //Storing UserName in Session


DataSet _MyDs = (DataSet)Session["DataSet"]; //Retrieving Dataset from Session


Session ID




  • Client hits the web site and information is stored in the session.

  • Server creates a unique session ID for that client and stores it in the Session State Provider.

  • The client requests for some information with the unique session ID from the server.

  • Server looks in the Session Providers and retrieves the serialized data from the state server and type casts the object.


Session Mode and State Provider


In ASP.NET, there are the following session modes available:




  • InProc

  • StateServer

  • SQLServer

  • Custom


When ASP.NET requests for information based on the session ID, the session state and its corresponding provider are responsible for sending the proper information




























Session State ModeState Provider
InProcIn-memory object
StateServerAspnet_state.exe
SQLServerDatabase
CustomCustom provider

Apart from that, there is another mode Off. If we select this option, the session will be disabled for the application.



<system.web>
    <sessionState cookieless="UseCookies" mode="Off"
stateNetworkTimeout="10800" timeout="10"/>
</system.web>

Or from server side: Session.TimeOut=30;


InProc Session Mode


This is the default session mode in ASP.NET. This is the best session mode for web application performance. It can be very helpful for a small web site and where the number of users is very less.


Advantages:




  • It stores session information in the current Application Domain So it is easily and quickly available.

  • There is not requirement of serialization to store data in InProc session mode.

  • Implementation is very easy, similar to using the ViewState.


Disadvantages:




  • If the worker process or application domain/server is recycled/restarted, all session data will be lost.

  • Though it is the fastest, more session data and more users can affect performance.

  • We can't use it in web garden scenarios, and not suitable for web farm scenarios.


StateServer Session Mode


This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Service (aspnet_state.exe) which is independent of IIS and can also be run on a separate server.


This server may run on the same system, but it's outside of the main application. So, if you restart your ASP.NET process, your session data will still be alive. It is useful in web farm and web garden scenarios.


You can start this service from the command prompt just by typing "net start aspnet_state".


This approach has several disadvantages due to serialization of the data before storing in StateServer session mode and de-serialization, it also increases the cost of data access.


For the StateServer setting, we need to specify the stateConnectionString. This will identify the system that is running the state server. By default, stateConnectionString used the IP 127.0.0.1 (localhost) and port 42424. And require stateNetworkTimeout.



<sessionState cookieless="UseCookies" mode="StateServer" 
sqlConnectionString="data source=127.0.0.1; Trusted_Connection=yes"
stateConnectionString="tcpip=127.0.0.1:42424" stateNetworkTimeout="10800"
timeout="10"/>

SQLServer Session Mode


To setup SQL Server, we need these SQL scripts:




  • For installing: InstallSqlState.sql

  • For uninstalling: UninstallSQLState.sql


Advantages:




  • This session mode provides us more secure and reliable session management in ASP.NET.

  • session data is serialized and stored in A SQL Server database (centralized location), is easily accessible from other applications.

  • Provides more security

  • Session data not affected if we restart IIS.

  • Very useful in web farms and web garden scenarios.

  • We can use SQLServer session mode when we need to share session between two different applications.


Disadvantages:




  • Processing is very slow in nature.

  • session storage method is the overhead related with data serialization and de-serialization.

  • As the session data is handled in a different server, we have to take care of SQL Server. It should be always up and running.


Configuration for SQLServer Session Mode


Step 1: From command prompt, go to your Framework version directory. E.g.:c:\windows\microsoft.net\framework\<version>.


Step 2: Run the aspnet_regsql command with the following parameters:
































ParametersDescription
-ssaddAdd support for SQLServer mode session state.
-sstype pP stands for Persisted. It persists the session data on the server.
-SServer name.
-UUser name.
-PPassword.

aspnet_regsql -d <SQLDATABASENAME> -S <SQLSERVERNAME> -U <USERNAME> -P <PASSWORD> -ssadd -sstype c


Step 3: Open SQL Server Management Studio, check if a new database ASPState has been created, and there should be two tables:




  • ASPStateTempApplications

  • ASPStateTempSessions


Custom Session Mode


Custom session gives full control to us to create everything, even the session ID. You can write your own algorithm to generate session IDs.


We can use Custom session mode in the following cases:




  • We want to store session data in a place other than SQL Server.

  • When we have to use an existing table to store session data.

  • When we need to create our own session ID.


What configuration do we need for it?


We need to configure our web.config like this:



<sessionState mode=”Custom” customProvider=”AccessProvider”>
<providers>
       <add name=”AccessProvider” type=”CustomDataType”/>
</providers>
</sessionState>

Advantages:




  • We can use an existing table for storing session data. This is useful when we have to use an existing database.

  • It's not dependent on IIS, so restarting the web server does not have any effect on session data.

  • We can crate our own algorithm for generating session ID.


Disadvantages:




  • Processing of data is very slow.

  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.


It is always recommended to use a third party provider rather than create your own.


Session Event


These are events in the global.asax file of your web application. When a new session initiates, the session_start event is raised, and the Session_End event raised when a session is abandoned or expires.



void Session_Start(object sender, EventArgs e)
{
    // Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
    // Code that runs when a session ends.
}

Removing Session




























MethodDescription
Session.Remove(strSessionName);Removes an item from the session state collection.
Session.RemoveAll()Removes all items from the session collection.
Session.Clear()Remove all items from session collection. Note: There is no difference between Clear and RemoveAll. RemoveAll()callsClear() internally.
Session.Abandon()Cancels the current session.

Enabling and disabling Session


For performance optimization, we can enable or disable session. We can enable and disable session state in two ways:




  • Page level

  • Application level


Page level


We can disable session state in page level using the EnableSessionState attribute in the Page directive.


<% Page Language="C#" EnableSessionState="False"


This will disable the session activities for that particular page.


The same way, we can make it read-only also. This will permit to access session data but will not allow writing data on session.


<% Page Language="C#" EnableSessionState="ReadOnly"


Application level


Session state can be disabled for the entire web application using the EnableSessionState property inWeb.Config.


<system.web>
<pages enableSessionState="false"/>
</system.web>


Generally we use page level because some pages may not require any session data or may only read session data.


Summary




  • The in-process (InProc) session provider is the fastest because of everything being stored inside memory. Session data will be lost if we restart the web server or if the worker process is recycled. You can use this in small web applications where the number of users is less. Do not use InProc in web farms.

  • In StateServersession mode, session data is maintained by exe. It keeps session data out of the web server. So any issues with the web server does not affect session data. You need to serialized an object before storing data in StateServer session. We can use this safely in web farms.

  • SQLServersession modes store data in SQL Server. We need to provide the connection string. Here we also need to serialize the data before storing it to session. This is very useful in production environments with web farms.

  • We can use a Customprovider for custom data sources or when we need to use an existing table to store session data. We can also create custom session IDs in Custom mode. But it is not recommended to create your own custom provider. It is recommended to use a third party provider.


 

No comments: