Session ASP .Net

ASP .Net Session

The session is a technique for state management. A session can store the server's value. It can support any kind of object that can be stored together with our own custom objects. A session is one of the best state management techniques because it manages the data as client-based, i.e., the information is stored separately for each user and the data is also protected as it is on the server. This interface is called the Session object. The Session object stores information about, or change settings for a user session.

Session

The Session object is available throughout the application's lifecycle. You can store in the Session object any number of key-value pairs. So you can store a value in the Session object on any page through the code line given below.

Session["Key"]=value

In a Session object, it stores the value and the ' key ' component is used to give a name to the value. It makes it possible to obtain the value at a later point in time. You may issue the statement below to retrieve a value.

Session["Key"]

Example:-

We will use the Session object in our example to store the name entered in the page's textbox name field.  Then we will retrieve the value and display it accordingly on the page. Let's add the code below to the directory Demo.aspx.cs.

protected void btn_Click(object sender,EventArgs e)
 {
                Session["Name"] = txt.Text;
                Response.Write(Session["Name"]); 
                lblName.Visible = false; 
                txt.Visible = false; 
                Lb.Visible = false;
                Chck1.Visible = false; 
                Chck2.Visible = false;  
                rbmale.Visible = false;
                rbfmale.Visible = false;
                btn.Visible = false;
 } 

Code Explanation

  • The first line of code takes the name from the control of the textbox and stores it in the object of the Session. By specifying the Session code["Name "], we give the property a name called" Name. "It becomes easier to return it at a later point in time by specifying a name for the property.
  • The next line of code retrieves the Session object's stored value. It then writes this value back to the user using the ' Response. Write ' process.
  • Finally, they make all the form controls invisible. If we don't do this, all the controls will be shown together with our response values.

Output:-

Session2

ASP.NET Session Events


In ASP.NET  There are 2 types of events available. We can handle both sessions in a global.asax file.

  1. Session_Start(): When the new session is initialized, then the session_start event is raised.
  2. Session_end(): When the session is Expired, then the Session_End event is raised.

Off:- Used to disable sessions on the website.

ASP.NET Session Mode

There is 4 types mode available in ASP.NET:

  1. InProc
  2. StateServer
  3. SQL Server
  4. Custom
Session State Mode State Provider
InProcIn memory object
StateServer Aspnet_state.exe
SQLServer Database
Custom Custom provider
Session3

Off - Used to disable sessions on the website.

1. InProc:- In the same process as a calling application, an inproc client runs. It is similar to a normal call on a dll function. In-process stores the web server's session in memory. The ASP.NET worker thread handles the location of the memory. To manage these, it only involves a significant overhead for the worker thread. Also, as this is in the server's memory, large session information would likely lead to more memory usage and thus lower performance. It allows the "sticky-server" (or no load-balancing) to re-connect the user to the same web server.

The advantages of the InProc mode:

  • Inproc session mode is very easy to configure, they only require sessionState mode="InProc."

Example:-

<system.web>
 <!-- Inproc Session in Application -->
 <SessionState               mode="Inproc"          timeout="30"/>
 </system.web> 
  • It will store session data in a current application domain memory object. Accessing data is therefore very fast and it is easy to access data.
  • Serialization is not required to store data in InProc session mode.

Disadvantages

  • If the process or application domain of the worker is recycled, all session data is lost.
  • In web garden scenarios, we can't use this.
  • For web farm scenarios, this session mode is not suitable.

2.  StateServer

This session mode is also called out-proc. StateServer uses a stand-alone, IIS-independent Windows Service that can also run on a separate server. Asp.Net state.exe fully manages this session state. This server may run on the same system, but your web application is running outside of the main application domain.

Configuration for StateServer session mode:

  • Session data is stored in a separate server in StateServer mode that is independent of IIS and is handled by Asp.Net state.exe.  As a Windows system, this process is running. You can use the Windows MMC or the command prompt to begin this operation. 
Session4
  • The ASP.NET state service's "Startup Mode" is set to Manual by default; we 

need to change it to Automatic.

Session5
  • Type "net start aspnet state" on the command prompt. By default, this service listens to TCP port 42424, but from the Registry editor, we can change the port.
  • Now take a look at the StateServer setting for the web.config configuration. We need to define the stateConnectionString for the StateServer configuration. It will classify the state database running process. IP 127.0.0.1 (localhost) and port 42424 were used by stateConnectionString by definition.
<system.web>
 <!-- Inproc Session in Application -->
 <SessionState               mode="StateServer"  StateConnectionString="tcpip=127.0.0.1:42424"/>
 </system.web>   

Advantages:-

  • It holds data independent from IIS, and session data will not be affected by any issues with IIS.
  • It is useful in scenarios for cloud farming and web gardening.

Disadvantages:

·         Process is slow due to serialization and de-serialization.
  • State Server always needs to be up and running.

SQLSERVER:-

This mode of session provides us with a more secure and reliable ASP.NET session management. User data are serialized in this user mode and stored in the server of A SQL Server. The main drawback of this method of session processing is the overhead associated with serialization and de-serialization of data. It is the best option for using in web farms though.

 We need these SQL scripts to setup SQL Server:

  • For installing: InstallSqlState.sql
  • For uninstalling: UninstallSQLState.sql

Configuration for SQLServer Session Mode:-


Step 1: From the command prompt, go to your Framework version directory

  • Example: c:\windows\microsoft.net\framework\<version>. and search for the aspnet_regsql.exe in which version these files are present and execute the file in the command prompt.
Session6

Parameter Description:

  1. ssadd: Add support for SQLServer mode session state.
  2. sstype p : P stands for Persisted. It persists the session data on the server.
  3. S: Server name.
  4. U: User name.
  5. P: Password.
  6. E: Authentication using the windows credential of the currently logged on users.

Step 2: After executing the command, open the database:

Session7

Step 3: Now for configuration we need to write the connection string in the web.config file:

<sessionState mode="SQLServer" sqlConnectionString="Server=DIVS\SQLEXPRESS;Integrated Security=true">

Step 4: And the webfrom1.aspx and webform2.aspx code are the same.

Step 5: Now, after sending a request to the server, open the database, and here the session id is stored, and by default, its expiration time is 20 minutes.

Session8

Advantages and Disadvantages

Advantages
  • Session data does not get affected if we restart IIS
  • The most efficient and stable control of sessions. 
  •  Keeps data located and is easily accessible by other applications.
Disadvantages
  • Processing is very slow.
  • Object serialization and de-serialization create the application overhead.
  • We have to take care of SQL Server as the session data is handled on another server. It should be up and running all the time.

Custom Session Mode:- For our application, we usually use InProc, StateServer, or SQLServer session modes, but we also need to know the basics of custom session mode. This session mode is quite interesting, as we are given full control by custom sessions to build anything, including the session ID. To create session IDs, you can write your own algorithm. 

Session9
  1. We can set up a custom provider in the Initialize process. This will initialize that provider's connection. To set SessionTimeOut.
  2. SetItemExpireCallback is used. We can register a method called at the time of the expiration of the session.
  3. InitializeRequest is called on every request.
  4. CreateNewStoreData is used to create a new instance of SessionStateStoreData.

When should we use Custom Session Mode?

  • We want session data to be stored in a location other than SQL Server. 
  • When using an existing table to store session data.
  • When we need our own session ID to be established.

Configuration of Custom Mode Session:

<sessionState
mode=”custom”           customProvider=”AccessProvider”>
 <Providers>
 <add name= “AccessProvider”            type=”CustomDataType”/>
 </providers>
 </sessionState> 

Advantages and Disadvantages

Advantages:
  1. For storing session data, we can use an existing table. This is useful if an existing database is to be used. 
  2. It is not based on IIS, so restarting the webserver does not affect the information of the session.
  3. We can create our session ID algorithm.

Disadvantages:

  1. Data processing is slow. 
  2. It is a low-level task to create a custom state provider that needs to be handled carefully to ensure security.