Monday, December 27, 2010

State Management Techniques

State Management in ASP.Net

Ø Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol.

Ø It means that web server does not have any idea about the requests from where they coming i.e from same client or new clients. On each request web pages are created and destroyed.

Ø So, how do we make web pages in ASP.Net which will remember about the user, would be able to distinguish b/w old clients(requests) and new clients(requests) and users previous filled information while navigating to other web pages in web site?

Solution of the above problem lies in State Management.

ASP.Net technology offers following state management techniques.

Client side State Management

o 1)Cookies

o 2)Hidden Fields

o 3)View State

o 4)Query String

Ø Cookies

Ø A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session.

Ø Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server.

Example for cookies

Step 1

Ø Open web application using visual studio

Open default.aspx file and write below code

<html>

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

CookiName <asp:TextBox id="TextBox1" runat="server">asp:TextBox>

<br />

<asp:Button id="Button1" runat="server" Text="set cookie" onclick="Button1_Click">asp:Button>

<asp:Button id="Button2" runat="server" Text="clear cookie" onclick="Button2_Click">asp:Button>

<br />

<br />

<asp:Label id="Label1" runat="server" ForeColor="Red">cookie statusasp:Label><br />

<br />

<asp:Button id="Button3" runat="server" Text="check cookie" onclick="Button3_Click">asp:Button>

<asp:TextBox id="TextBox2" runat="server">asp:TextBox>

div>

form>

body>

html>

Step 2:

Write the below code in code behind file(default.asp.cs)

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Button1_Click(object sender, System.EventArgs e)

{

////////////SET THE COOKIE//////////////

Response.Cookies["test"].Value = TextBox1.Text;

Response.Cookies["test"].Expires = DateTime.Now.AddYears(30);

////////////END SET THE COOKIE//////////////

}

protected void Button2_Click(object sender, System.EventArgs e)

{

Response.Cookies["test"].Expires = DateTime.Now.AddYears(-30);

}

protected void Button3_Click(object sender, System.EventArgs e)

{

/////////check to see if cookie presented//////////

if (Request.Cookies["test"] == null)

TextBox2.Text = "No cookie found";

else

TextBox2.Text = Request.Cookies["test"].Value;

/////////END check to see if cookie presented//////////

}

}

Step 3:

Run the application

Ø You can verify this path in your computer C:\Documents and Settings\Administrator\Cookies

Cookies will be creating and Expiring

Example for Hidden fields

Step1) Write below code in the .aspx file

<html>

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:HiddenField ID="HiddenField1" runat="Server" Value="This is the Value of Hidden field" />

<asp:Button ID="Button1" runat="Server" OnClick="ChangeLabelText" Text="Change Label Text to Hiidden Field Value" />

<p id=p1 runat="server" />

div>

form>

body>

html>

Step2 Write below code in the code behind(i.e Default.aspx.cs file)

protected void ChangeLabelText(object sender, EventArgs e)

{

p1.InnerText = HiddenField1.Value;

}

Step 3: Run the application

It will display the hidden field value in label control.

Server side State Management

o Session State

o Application State

These state management techniques can be understood and by following simple examples and illustrations of the each techniques.

Ø .

Server Side State Management

Session State

Ø Session state is used to store and retrieve information about the user as user navigates from one page to another page in ASP.Net web application.

Ø Session state is maintained per user basis in ASP.Net runtime.

Ø It can be of two types in-memory and out of memory.

Ø In most of the cases small web applications in-memory session state is used.

Ø Out of process session state management technique is used for the high traffic web applications or large applications.

Ø It can be configured with some configuration settings in web.config file to store state information in ASPNetState.exe (windows service exposed in .Net or on SQL server.

Advantages of Client – Side State Management:

1. Better Scalability:

With server-side state management, each client that connects to the Web server consumes memory on the Web server.

If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

Session State Architecture

What is Session ?

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

Ø As we all know HTTP is a stateless protocol, it can't hold the client information on page.

Ø If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information.

Ø So we need to store information SOME WHERE. Session provides that facility to store information on server memory.

Ø It can support any type of object to store along with our custom object. For every client Session data store separately, means session data is stored as per client basis.

Have a look at the following diagram.

explor2.jpg

Fig : For every client session data store separately

Ø State Management using session is one of the asp.net best features, because it is secure, transparent from users and we can store any kind of object with in it.

Ø Along with advantages, some times session can causes performance issue for heavy traffic sites because its stored on server memory and clients read data from the server itself.

Now lets have a look at the advantages and disadvantages of using session in our web application.

Advantages and Disadvantages of Session ?

Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages :

  • It helps to maintain user states and data to all over the application.
  • It can easily be implemented and we can store any kind of object.
  • Stores every client data separately.
  • Session is secure and transparent from user.

Disadvantages :

  • Performance overhead in case of large volume of user, because of session data stored in server memory.
  • Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Besides these, there are many advantages and disadvantages of session that are based of session Types.

Storing and Retrieving

Storing and Retrieving values from Session

Ø Storing and Retrieving values in session are quite similar with ViewState.

Ø We can interact with Session State with System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.

Following code is used for storing a value to session

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

Session ID

Asp.Net use 120 bit identifier to track each session. This is secure enough and can't be reverse engineered.

When client communicate with server, only session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data.

This is done in following steps,

  • Client hits web site and some information is stored in session.
  • Server creates a unique session ID for that clients and stored in Session State Provider .
  • Again client request For some information with that unique session ID from Server.
  • Server, looks on Session Providers, and retrieve the serialized data from state server and type cast the object.

Just have a look on the pictorial flow,

Fig : Communication of Client, web server, and State Provider

Session Modes and State Provider

In ASP.NET there are following session mode available,

· Off

· InProc

· StateServer

· SQLServer

· Custom

For every session State, there is Session Provider. Following diagram will show you how they are related.

Fig : Session State Architecture

Ø we can choose the session State Provider based on which session state we are selecting.

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

Following tables show, the session mode along with there provider Name.

Session State Mode

State Provider

InProc

In-Memory Object

StateServer

Aspnet_state.exe

SQLServer

DataBase

Custom

CustomProvider

apart from that, there is another mode, "Off". If we select this option the session will be disabled for the application. But our objective is to use session, so we will look into that four session State Mode.

Session States

Ø If we consider about session state, It means all the settings that you have made for your web application for maintaining the session.

Ø Session State, it self is a big thing, It says all about your session configuration, Either in web.config or from code behind.

Ø In web.config, <SessionState> elements used for setting the configuration of session. Some of them are Mode, Timeout, StateConnectionString, Custom provider etc. I have discussed about each and ever section of connection string. Before I discussed Session Mode, just take a brief overview of Session Event

Session Event

There are two types of session events available in asp.net

  • Session_Start
  • Session_End

you can handle both this event in global.asax file of your web application.

When a new session initiate session_start event raised and Session_End event raised when a session is abandoned or expired.

 
 
 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. 
 
    }

Session Mode

Following are the different types of session modes available in ASP.Net.

  • Off
  • InProc
  • StateServer
  • SQLServer
  • Custom

If we set Session Mode="off" in web.config, Session will be disabled to all over the application. For this we need to configure web.config in following way

InPorc Session Mode :

Ø This is the default session mode in Asp.Net. Its stores session Information in Current Application Domain.

Ø This is the best session mode which is based on web application Performance.

Ø But main disadvantage is that, It will lose the data if we restart the server.

Ø There are some more advantages and disadvantages of InProc session mode..

Overview of InProc Session Mode :

Ø As we have already discussed InProc mode session data will be stored on the current application domain. So It is easily and quickly available.

Ø So, InProc session mode store its session data in a memory object on that application domain.

Ø This is handled by worker process in application pool. So If we restart the server we will lose the session data.

Ø If Client request for the data , state provide read the data from In-Memory Object and return it to the client.

Ø In web.config we have to mention Session mode and also we have to set the Timeout.

explor3.gif

This Session TimeOut Setting keeps session alive for 30 minute. This can be configurable from Code behind too.

Session.TimeOut=30; 

There are two type of session events available in asp.net

Session_Start() and Session_End. .. The general flow for the InProc Session State is some thing like this.

Ø Now, when the Session_End() will call that depends on Session Time Out. This is a very fast mechanism because no serialization occurs for storing and retrieving data, and data are staying inside the same application domain.

Example for Inporc mode:

Step1::

Drag and drop one textbox control and two button controls and one lable control

Change properties of textbox control name as txtUserName

Change button control text property as session_create

Change button1 control text property as session_Retrieve

Change label control name as lblUserName.

OR

Write below code in .aspx file

<html>

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtUserName" runat="server" Width="263px">asp:TextBox>

<asp:Label ID="lblUserName" runat="server" Text="Label" Width="80px">asp:Label><br />

<asp:Button ID="Button1" runat="server" Text="Session_Create" OnClick="Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Session_Retrieve" OnClick="Button2_Click"/><br />

<br />

div>

form>

body>

html>

Step2:

Add web.config file to your application

Goto àwebsiteàAddNewItemàWebConfiguration file-àok

Open the web.config file

Write this code:

Step3:

Write the below code in code behind file

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Button1_Click(object sender, EventArgs e)

{

// Storing Data in Session objects

Session["username"] = txtUserName.Text;

}

protected void Button2_Click(object sender, EventArgs e)

{

// Retrieving Data in Session Objects

lblUserName.Text = Session["username"].ToString();

}

}

What can be stored in a session?



The above examples show storing and retrieving simple strings in session.

But you can store complex datatypes like Dataset also into session. Many websites retrieve lot of user data from database

And store into session so that it can be accessed faster from memory (session) rather than retrieving from database.

However, it is not reccommded to store lot of data into session for large websites. Session data is stored in memory and if there are thousands of online users at the same time, server may run out of memory.

When Should we use InProc Session Mode ?

Ø InProc is the default session mode. It can be very helpful for a small web sites and where the number of user are very less, We should avoid InProc in case of Web Garden.

Advantages and Disadvantages

Advantages :

· It store Session data in memory object of current application domain. So accessing data is very fast and data is easily available.

· There is not requirements of serialization to store data in InProc Session Mode.

· .

Disadvantages :

although InProc Session is fastest, common and default mechanism, It has lots of limitation.

· If the worker Process or application domain recycles all session data will be lost.

· Though its fastest, but more session data and more users can affects performance, because of memory.

· we can't use it in web Garden scenarios .

· This session mode is not suitable for web farm scenarios also.

StateServer Session Mode :

Overview of StateServer Session Mode :

Ø This is also called Out-Proc session mode.

Ø StateServer uses a stand-alone Windows Services, which is Independent to IIS and can also run on a separate server.

Ø This session state is totally managed by aspnet_state.exe.

Ø This server may runs on the same system, but it's out side of that main application domain where your web application is running.

Ø This allow if you restart your asp.net process restarted your session data will be alive.

Ø This approaches has several disadvantages due to the overhead of serialization and de-serialization, its also increases the cost of data access because of every time when user retrieves session data, our application hits a different process.

Configuration for StateServer Session Mode

Configuration for StateServer Session Mode

Ø In StateServer the Session data is stored in a separate Server which is Independent to IIS and Its handled by aspnet_state.exe.

Ø This process is run as windows Services. you can start this service from windows MMC or from command prompt.

Ø The Microsoft Management Console (MMC) is a component of Windows 2000 and later Windows NT-based operating systems that provides system administrators and advanced users with a flexible interface through which they may configure and monitor the system

By default "Startup Type" of ASP.NET state service is set to manual, we have to set it as "Automatic" startup type.

from command from just typing "net start aspnet_state". By default this services listen TCP Port 42424 , but we can change the port from registry editor as given in below picture .

Ø Now have a look on the web.config configuration for StateServer Setting.

Ø For State Server Setting we need have to specify the stateConnectionString. This will identify the system that is running state server. By default stateConnectionString used ip as 127.0.0.1 (localhost) and Port 42424.

Ø explor9.gif
When we are using StateServer, we can configure
stateNetworkTimeOut attributes to specify the maximum number of seconds to wait for the service to respond before canceling the request. Default time is 10 seconds.

explor10.gif

For using StateServer, the object which we are going to store that should be serialized and at the time of retrieving we need to De-Serialize. I have described it with an Example.

How StateServer Session Mode Works?

Ø We used StateServer Session Mode to avoid unnecessary session data loss during restart of web Server. StateServer is maintained by process aspnet_state.exe as a windows Services.

Ø This process maintains the all the session data. But need to serialize the data before storing it in StateServer Session Mode.

Ø As shown in above figure, that client request to the web server, then web server stores the session data on state server. StateServer may be the current system or may be the different system.

Ø But it is totally independent of IIS. Destination of StateServer will depend on the web.config stateConnectionString attribute settings.

Ø If we set it as 127.0.0.1:42424, It will store data on that local system itself. For change the StateServer destination, we need to change the IP. and make sure, aspnet_state.exe is up and running on that system. other wise you will get the following exception while trying to store data on session.

Ø When we are storing any object on session, that should be serialized. That data will be stored to StateServer system using State Provider. and at the time of retrieving the data, State provider will return the data.

Ø The complete flow is given in the below picture.

Example Of StateServer Session Mode :

. Example for State server mode:

Step1:starting windows service Setting the ASP.NET State Service to Run Automatically

Ø Go to: Control Panel | Administrative Tools | Services

Ø Set Startup type to: "Automatic".

Ø Click "Start", if the "ASP.NET State Service" is not started.

Ø Click OK.

OR

You can start from the command prompts using below command

C:\net start aspnet_state

Step2:

Open new web application using visual studio

Add web.config file

WebsiteàAddNew itemàselect Web configuraion fileàok

It will add web.config file into your application solution explorer.

Ø Open web.config file and write below code.

stateConnectionString=”tcpip=127.0.0.1:42424”/>

What is 127.0.0.1?

127.0.0.1 is the standard IP address used for a loopback network connection.

This means that if you try to connect to 127.0.0.1, you are immediately looped back to your own machine.

Step3::

Drag and drop one textbox control and two button controls and one lable control

Change properties of textbox control name as txtUserName

Change button control text property as session_create

Change button1 control text property as session_Retrieve

Change label control name as lblUserName.

OR

Write below code in .aspx file

<html>

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtUserName" runat="server" Width="263px">asp:TextBox>

<asp:Label ID="lblUserName" runat="server" Text="Label" Width="80px">asp:Label><br />

<asp:Button ID="Button1" runat="server" Text="Session_Create" OnClick="Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Session_Retrieve" OnClick="Button2_Click"/><br />

<br />

div>

form>

body>

html>

Step4:

Write the below code in code behind file

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Button1_Click(object sender, EventArgs e)

{

// Storing Data in Session objects

Session["username"] = txtUserName.Text;

}

protected void Button2_Click(object sender, EventArgs e)

{

// Retrieving Data in Session Objects

lblUserName.Text = Session["username"].ToString();

}

}

if u want to know ip address of your system:

Go to command prompt and execute below command:

C:\>ipconfig

.

Advantages and Disadvantages of State server mode

So based on the above discussion

Advantages :

· Its keeps the data separate from IIS so, any Issue with IIS does not hamper Session data.

· It is useful in web farm and web garden scenarios.

Disadvantages :

· Process is slow due to Serialization and De-Serialization

· State Server always need to be up and running.

You will find some more interesting points on Load balancer, Web Farm, Web Garden Section.

SQL Server Session Mode :

Overview of SQL Server Session Mode :

Ø This session mode provide us more secure and reliable Session management in asp.net.

Ø In this session mode, the Session data is serialized and stored in the SQL Server database.

Ø Main disadvantages of this session storage methods is overhead related with Data Serialization and De-Serialization. It is the best option for using in the web farms.

Ø To setup SQL Server we need to take help of two sql Script.

· For Installing: InstallSqlState.sql

· For Un-Installing: UninstallSQLState.sql

Ø The most easiest way to configure SQL Server, is using aspnet_regsql command.

I have explained the detailed use of these file in configuration section. This is the most useful state management in the web farm scenario.

When should we use SQL Server Session Mode ?

  • SQL Server Session mode is more reliable and secure session state management.
  • Its keeps data in a centralized location (database).
  • We should use SQL server session mode when we need to implement Session with some more security.
  • If there happens to be frequent server Restart we can implement SQL server.
  • This is perfect mode that fits in web farm and web garden scenarios (I have explained in details later) .
  • we can use SQL server Session mode when we need to share session between two different application .

Configuration for SQL Server Session Mode

Ø In SQL Server Session mode, we are storing session data in a SQL Server, so we need to first provide the database connection string in web.config .

Ø sqlConnectionString attribute is used to provide the connection string in web.config.

Ø After setup the connection string we need to configure the SQL Server. I am explaining how to configure your your SQL server using aspnet_regsql command.

Step 1: From Command prompt, Go to your Framework Version Directory

E.g :c:\windows\microsoft.net\framework\<version>.

Step 2 : Run aspnet_regsql command with following parameters

Have a look on the parameter and there uses

Parameters

Description

-ssadd

Add support for SQLServer mode session state.

-sstype p

P is stands for Persisted. Its persist the session data on server

-S

Specify Server Name

-U

Specify User Name

-P

Specify Password

After run you will get the following message,

that's all .

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

  • ASPStateTempApplications
  • ASPStateTempSessions

Now, Just change the configuration string of the State Server Example and Run the same application that I have explained in State Server.

Just store Roll and User Name and Click on Submit button, and open ASPStateTempSessions Table from SQL Server Management Studio.. WoW... here is your session data,

Now. do the following Test that I have already explained in State Server Mode.

1. Remove The Serialize Key word from StydentInfo Class

2. Reset IIS and Click on Restore Session

3. Stop the SQL Server Services

Example for SQL Server session mode

Step 1:

Ø The most easiest way to configure SQL Server, is using aspnet_regsql command.

Have a look on the parameter and there uses

Parameters

Description

-ssadd

Add support for SQLServer mode session state.

-sstype p

P is stands for Persisted. Its persist the session data on server

-S

Specify Server Name

-U

Specify User Name

-P

Specify Password

Ø

Go to command prompt:

· C:\>WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql –S -U sa –P -ssadd –sstype p

After run the above command it will display

Start adding session state.

……….

Finished.

Step1:

Open previous web application using visual studio

Open web.config file and update below code.

 
 
 
  mode="SQLServer"
  sqlConnectionString="data source=server;user id=sa;password=sa" server=”127.0.0.1” port=”42424”




   />

Step3::

Drag and drop one textbox control and two button controls and one lable control

Change properties of textbox control name as txtUserName

Change button control text property as session_create

Change button1 control text property as session_Retrieve

Change label control name as lblUserName.

OR

Write below code in .aspx file

<html>

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="txtUserName" runat="server" Width="263px">asp:TextBox>

<asp:Label ID="lblUserName" runat="server" Text="Label" Width="80px">asp:Label><br />

<asp:Button ID="Button1" runat="server" Text="Session_Create" OnClick="Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Session_Retrieve" OnClick="Button2_Click"/><br />

<br />

div>

form>

body>

html>

Step4:

Write the below code in code behind file

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Button1_Click(object sender, EventArgs e)

{

// Storing Data in Session objects

Session["username"] = txtUserName.Text;

}

protected void Button2_Click(object sender, EventArgs e)

{

// Retrieving Data in Session Objects

lblUserName.Text = Session["username"].ToString();

}

}

Step 5: Configuration for SQL Server Session Mode

Ø The most easiest way to configure SQL Server, is using aspnet_regsql command.

Ø From Command prompt, Go to your Framework Version Directory

E.g :c:\windows\microsoft.net\framework\<version>.

Have a look on the parameter and there uses

Parameters

Description

-ssadd

Add support for SQLServer mode session state.

-sstype p

P is stands for Persisted. Its persist the session data on server

-S

Specify Server Name

-U

Specify User Name

-P

Specify Password

Ø

Go to command prompt:

· C:\>WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql –S -U sa –P -ssadd –sstype p

After run the above command it will display

Start adding session state.

……….

Finished.

Run the application

Step 5

Open SQL Server Management Studio, Check, A new database ASPState has been created and there should be two tables,

  • ASPStateTempApplications
  • ASPStateTempSessions

Now, Just change the configuration string of the State Server Example and Run the same application that I have explained in State Server.

Just store Roll and User Name and Click on Submit button, and open ASPStateTempSessions Table from SQL Server Management Studio.. WoW... here is your session data,

Now. do the following Test that I have already explained

I think I have explained the SQL Server Session mode well.

Advantages and Disadvantages

Advantages :

  • Session data do not affected if we restart the IIS.
  • It is the most reliable and secure session management.
  • It keeps data located centrally , It can be easily accessible from other application.
  • It is very useful in web farm and web garden scenarios.

Disadvantages :

  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead for application.
  • As the session data is handled in different server, so we have to take care of SQL server. It should be always up and running.

Where it stores

• 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

Custom Session Mode

Overview of Custom Session Mode :

Ø Generally we use either of InProc, StateServer or SQL Server Session mode for our application, but we also need to know the fundamental of Custom Session mode.

Ø This session mode is quite interesting, because Custom session gives full control to us to create every thing even session ID. you can write your own algorithm to generate session ID.

Ø You can implement custom providers that store session data in other storage mechanisms simply by deriving from SessionStateStoreProviderBase Class. You can also Generate New Session Id by Implementing ISessionIDManager.

This are the following methods are called during implementation of Custom Session

Ø In Initialize methods we can set the Custom Provider. This will initialize the connection with that specified provider.

Ø SetItemExpireCallback used to set SessionTimeOut, we can register any methods that will call at the time of session expire.

Ø InitializeRequest is called on every request and CreateNewStoreData used to create a new instance of SessionStateStoreData .

When should we use Custom Session Mode ?

we can use custom session mode in following of the cases,

· We want to store session data rather than SQL Server.

· When we have to use some 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 below,

Advantages and Disadvantages

Advantages:

· We can use some existing Table for the store session data, It is useful when we have to use some old database rather than SQL Server.

· It's not depending on IIS , So Restarting web server does not make any effects 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.

Overview of Production Deployment

Ø Generally Production environments means when we deploy the application on our live production server.

Ø This is a major and Big Challenge for the web developer to deploy there application on Live Server. because in a Big production environment there are no of user and its not possible to handle the load of so many users by a single server. Here the concepts came of Web Farm, Load Balancer , Web Garden etc.

.Internet services manager utility[inetmgr.exe]:

Ø inetmgr.exe provides information of websites mainatained by IIS

Ø To display IIS info

Startàrunàinetmgr.exeàok

Ø ASP.Net_wp.exe(worker process) can be called as asp.net runtime/engine “,this will do all the required processing for asp.net page execution.

App domain”

Ø This worker process will load applications(websites) related files into memory block is called “appdomain”

Application Pool :

Ø All non-static pages and applications (static: "HTML only" pages, images, etc.) are interpreted and executed by the server.

Ø Application pools (AppPools) were introduced in IIS 6 as a way of keeping the effects from the code executed by
different virtual servers as encapsulated as possible.




Ø Each application pool gets it own worker process on the system. By doing this, each application in a pool will never have an effect on applications in other pools.

Ø If an application causes a process to crash, for example, this only affects the pool in which it is in. The Web server and other pools continue to run normally.





Ø You can create as many application pools as you want. The number is limited only by the resources on the server.

Ø Note however, that each running pool consumes system
resources for process management (overhead). Your system easily supports around 25 application pools without noticeable performance loss.

Ø The exact number depends on:

1. Your server's memory and CPU load
2. The number and type of applications in the pools
3. The number of requests for these applications
4. The resource needs of other applications/programmes running on the server


Ø Applications can be assigned to a specific pool in their properties. You can assign
an application pool at the bottom of the "Home Directory" tab (or a "directory" if it is a lower-level application).

Ø New pools can be created by right-clicking
on "Application Pools".

Ø This is one of the most important thing that you should create for your own application in Production environment.

Ø Application pools used to separate sets of IIS worker processes that share the same configuration.

Ø Application pools enable us to isolate our web application for better security, reliability, and availability

Ø The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.

Web Garden

Ø By default Each Application Pool runs with a Single Worker Process (W3Wp.exe).

Ø We can Assign multiple Worker Process With a Single Application Pool.

Ø An Application Poll with multiple Worker process called Web Gardens.

Ø Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time.

Ø And Each Worker Process Should have there own Thread and Own Memory space.

Ø As Given in Picture, in IIS Server there may be multiple Applicationpool and each application pool having at least a single Worker Process.

Ø Web Garden should contain multiple Worker process.

Ø There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process.

Ø For Avoid this Type of problem we should have to use Session Mode "out proc" and we can use "Session State Server" or "SQL-Server Session State".

Main Advantage : The worker processes in a Web garden share the requests that arrive for that particular application pool. If a worker process fails, another worker process can continue to process requests.

How To Create Web Garden ?

Right Click on the Application Pool > Go To Performance Tab > Check Web Garden Section (Highlighted in Picture )

By default it would be 1 , Just change it to more than one .

How Session Depends on Web Garden ?

Ø I have already discuss that, InProc is handled by Worker Process. Its keeps data insides its memory object.

Ø Now If we have multiple Worker Process, then It would be very difficult to handled the session . because, Each and every Worker process has it own memory, so If my first request goes to WP1 and its keep my session data and Second Request goes to WP2 and I am trying to retrieve session data, it will not able to return . Which will throw error.

Ø So please avoid Web Garden in InProc Session Mode.

Ø we can use StateServer or SQLServer Session mode in case of Web Garden , because I have already explained these two session mode does not depends on Worker Process .

Ø In my example, I have also explain, If you restart the IIS then also you are able to get session data.

In Short ,

Session Mode

Recommended

InProc

No

StateServer

Yes

SQLServer

Yes

Web Farm and Load Balancer:

Ø This is the most common term that is used in production deployment .

Ø This terms comes, when we are using Multiple Web Server for deploying our product.

Ø The main reason behind the scene is to distribute the load over the multiple server.

Ø Load balancer is used to distribute the load on those server.

If we check the diagram, Client request the url and it will hit a Load Balancer, which decides which server to access. Load balancer will distribute the traffic over the all web server.

Now how does it affects session

Handling Session in Web Farm and Load Balancer Scenar111ios

Handling session is one of the most challenging job in web farm .

Ø InProc : In InProc session mode, session data stored in In-Memory Object of worker process.

Ø So each and every server have its own Worker process and they keep session data inside the memory.

Ø If One server is down in time and request come to different server, user is not able to get session data. So, it is not recommended to use InProc in Web Farm .

Ø StateServer :I have already explained that what a state server is, how to configure a StateServer etc. Now From this Web farm scenarios you can easily understand that how much it is important, because all session data will be stored in a Single location .

Ø Remember, In a web farm, make sure you have the same <machinekey> in all your web servers. and Other things are all same as I have describe earlier. All web.config having the same configuration (stateConnectionString) for Session State.

SQL Server : This is another approach even best one that we can use in web farm. We need to configure the data base first. The steps I have already covered .

explor37.jpg

Ø as shown in the above picture, all web server session data will be stored in a single SQL Server Database.

Ø And it can be easily accessible. Keep one thing in mind, you should serialize object in both state server and SQL Server mode.

Ø Any time if one of the web server goes down, Load balancer distribute the loads to other server and that user can able to read session data from server, because data is stored in a centralized DB server.

In summary, we can use either of state server or SQL server session mode in web farm . We should avoid the InProc

What is diff. between ASP State Management and ASP..Net state management?

In Distributed network architecture ASP has only one Type of Session Management which can be expressed as InProcess Session State Where as in .NET architecture ASP.NET Session Management can be done is different ways as 1. In-Process Session Management2. Out-Process Session Management3. Sql-Server Session ManagementIn In-Process Session Management both the Application and the Session will run under the Same Process where as in Out-Process Session Management Application and the Session will run in different processes. Advantage of Out-Process is that event though the Application is Restared due to any reason the Sessions Assosiated with that application will not be destructed but where as in In-Process Session Management the Session State will be Lost along with the Application.In Sql-Server Session Management the Session is Maintained in SQLSERVER Database.

No comments:

Post a Comment