Thursday, April 12, 2012

Session in Asp.net Part -1

 
What is mean by term session?

     Whenever a person goes to a website by typing name of site into his browser, web server assign him an id many time referred as session id, subsequent request of user to same server through same browser bounces this sessionid to and fro in request response cycle, Through this id, web server identifies that user has already visited few pages from his sites.
       Once a sessionid is assigned and time lag between any two subsequent requests exceeds the specified time the old session id is expired and new one is generated and passed into response.
      The timespan in which a request & response cycle shares a common session id can be considered as a session.

What MSDN says about session?

A session is defined as the period of time that a unique user interacts with a Web application.

How Session Id Look Like?

A session ID is a unique identification string usually a long, random and alpha-numeric string.
  
What is Session State ?

Session state is a feature of asp.net (also asp) which utilizes the session id to retain data for unique user sessions. Session state is hash table like mechanism to store. Key-value pairs. Key-value pair stored in session state can be read or written. Session State data is stored on web server in the form of a file and accurately retrieved and manipulated using session id bounced to and fro in request response cycle.

Comparing ASP Session and ASP.NET session

Sr. No.

Classic Asp

ASP.NET

1
Process dependent-ASP session state exists in the process that hosts ASP hence the process is recycled or fails, session state is lost.
Process independent-ASP.NET session state is able to run in a separate process from the ASP.NET host process.
2
Server farm limitations: As users move from server to server in a Web server farm, their session state does not follow them. ASP session state is machine specific. Each ASP server provides its own session state, and unless the user returns to the same server, the session state is inaccessible.
Support for server farm configurations-By moving to an out-of-process model, ASP.NET also solves the server farm problem. The new out-of-process model allows all servers in the farm to share a session state process. You can implement this by changing the ASP.NET configuration to point to a common server.
3
Cookie dependent. Clients that don't accept HTTP cookies can't take advantage of session state. Cookieless state management in asp is complex.
Cookie independent. ASP.NET allows cookieless session state by mere configuration setting.


ASP.NET Session State configuration?

Session state behavior can be customized by using web.config file.
session state settings for the current application is stored in <sessionState> element of web.config. <sessionState> lies nested inside <configuration><System. web> elements
i.e. this part look like bellow
<configuration>
<System. web>
<sessionState>
</System. web>
</configuration>

<sessionState> element  contain attributes listed bellow
a) mode
b) Cookieless
c) Timeout
d) stateConnectionString
e) sqlConnectionString
f) stateNetworkTimeout

The Mode attribute used to where session state should be stored.

Attribute
Option
Description
mode
   
Specifies where to store the session state.
   
Off
Indicates that session state is not enabled.
   
InProc
Indicates that session state is stored locally in same process as asp.net just like classic asp. In-process mode is the default session state mode
   
StateServer
Indicates that session state is stored on a remote server so asp.net process & session state are in two different processes. useful in web farm
   
SQLServer
Indicates that session state is stored on the SQL Server(the server on which it is stored is specified using another attribute sqlConnectionString discussed bellow)

Custom
This enables you to specify a custom storage provider?
 Optional Attributes
Attribute
Option
Description
cookieless
   
Specifies whether sessions without cookies should be used to identify client sessions.
   
true
Indicates that sessions without cookies should be used.
   
false
Indicates that sessions without cookies should not be used. The default is false.
timeout
   
Specifies the number of minutes a session can be idle before it is abandoned. The default is 20.
stateConnectionString
   
Specifies the server name and port where session state is stored remotely. For example, "tcpip=127.0.0.1:42424". This attribute is required when mode is StateServer.
sqlConnectionString
   
Specifies the connection string for a SQL Server. For example, "data source=localhost;Integrated Security=SSPI;Initial Catalog=northwind". This attribute is required when mode is SQLServer.
stateNetworkTimeout
   
When using StateServer mode to store session state, specifies the number of seconds the TCP/IP network connection between the Web server and the state server can be idle before the session is abandoned. The default is 10.

InProc is the only mode that supports the Session_OnEnd event.
To use StateServer mode

Configure the State Service on the ASP.NET State Server (IIS 6.0)

The ASP.NET state service is used to manage session state on a computer. The ASP.NET state service is installed by default when Microsoft® Windows® Server 2003 is installed. The file aspnet_state.exe is installed on the remote server that will store session state information; the default location is systemroot\Microsoft.NET\Framework\version\aspnet_state.exe.

How to configure the ASP.NET state service ?


1.
 On the remote server that will store session state information, open Administrative    Tools, and then click Services.
2.
In the details pane, right-click ASP.NET State Service, and then click Properties.
3.
On the General tab, in the Startup type list box, click Automatic.
4.
Under Service status, click Start, and then click OK. The state service starts automatically when the Web server is restarted.

  1. Make sure ASP.NET state service is running on the remote server that will store session state information. This service is installed with ASP.NET and is located by default at <Drive>:\systemroot\Microsoft.NET\Framework\version\aspnet_state.exe.
  2. In the application's Web.config file, set mode=StateServer and set the stateConnectionString attribute. For example, stateConnectionString="tcpip=dataserver:42424".
Bellow is an example of session state element in StateServer mode
<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=SampleStateServer:42424"
      cookieless="false"
      timeout="20"/>
  </system.web>
</configuration>
 

How to use SQLServer mode?

This mode stores session state in a SQL Server database. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
Point to note is “Objects stored in session state must be serializable if the mode is SQL Server.”
To install the ASP.NET session state database the Aspnet_regsql.exe tool located in the systemroot\Microsoft.NET\Framework\versionNumber folder on the Web server is used.

By default, the Aspnet_regsql.exe tool will create a database named ASPState containing stored procedures that support SQLServer mode. Session data itself is stored in the tempdb database by default. One can optionally use the -sstype option to change the storage location of session data. The possible values for the -sstype option are

Option
Description
t Stores session data in the SQL Server tempdb database. This is the default. If you store session data in the tempdb database, the session data is lost if SQL Server is restarted.
p Stores session data in the ASPState database instead of in the tempdb database.
c Stores session data in a custom database. If you specify the c option, you must also include the name of the custom database using the -d option.
For example,
a)      aspnet_regsql.exe -S SampleSqlServer -E -ssadd -sstype p
b)      aspnet_regsql.exe -S SampleSqlServer -E -ssadd -sstype c –d some_db_name
Bellow is an example of session state element in SQLServer mode
<configuration>
  <system.web>
    <sessionState mode="SQLServer"
      sqlConnectionString="Integrated Security=SSPI;data
        source=SampleSqlServer;" />
  </system.web>
</configuration>

How to use custom mode?

   Custom mode specifies that we want to store session state data using a custom session state store provider. Here we need to specify the type of the session state store provider using the providers sub-element of the sessionState configuration element.
The <providers> element look like
       
     <providers><add name="OdbcSessionProvider"
          type="Samples.AspNet.Session.OdbcSessionStateStore"
          connectionStringName="OdbcSessionServices"
          writeExceptionsToEventLog="false" />
      </providers>
The following example shows elements from a Web.config file that specify that ASP.NET session state use a custom session state store provider:
<configuration>
  <connectionStrings>
    <add name="OdbcSessionServices"
      connectionString="DSN=SessionState;" />
  </connectionStrings>

Bellow is an example of session state element in Custom mode

  <system.web>
    <sessionState
      mode="Custom"
      customProvider="OdbcSessionProvider">
      <providers>
        <add name="OdbcSessionProvider"
          type="Samples.AspNet.Session.OdbcSessionStateStore"
          connectionStringName="OdbcSessionServices"
          writeExceptionsToEventLog="false" />
      </providers>
    </sessionState>
  </system.web>
</configuration>

In latter parts of this article ,We will delve deep into practical usages of session  ,events linked to session & relation between session and authentication further we will explore custom provider for session state using a practical examples.

 References:
           1)     http://msdn.microsoft.com/en-us/library/ms972429.aspx
           2)     http://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.71%29.aspx
           3)     http://msdn.microsoft.com/en-us/library/ms178586.aspx
           4)     http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library   
                 /IIS/0d9dc063-dc1a-46be-8e84-f05dbb402221.mspx?mfr=true
            5)     http://msdn.microsoft.com/en-us/library/ms178583.aspx
6)     http://msdn.microsoft.com/en-us/library/ms178587.aspx
7)   http://abhijitjana.net/2011/06/04/asp-net-internals-clearing-asp-net-session-variables-a-in-depth-look/



No comments:

Post a Comment