Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere


Server Side State Management

In server side statement management technique the information is stored on server,because the information is available on server so there is no need to sent it to server while making a request to server.
Server side state management technique are-
1-Session-ASP.NET session enables you to store and retrieve values for a user when the user navigates in pages in a Web application.Session provides a way to store information on server memory. ASP.NET session helps you to identify that the requests are coming from the same browser.By default,ASP.NET session is enabled for all ASP.NET applications. You can store any type of data on server using session.State management using session is secure, transparent from users, and you can store any type of object in it. some times session can cause performance issues because it is stored in server memory.
ASP.NET uses SessionID an 120 bit identifier to track each session.When a client sends a request to server, only the session ID is transmitted between them. When the client requests for data, ASP.NET looks for the session ID and retrieves the corresponding data. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie but you can configure the application to store SessionID values in the URL of request with "cookieless" session.
A session is considered active till the requests are coming with the same SessionID value.
If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.
SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious user could get access to the session of another user by obtaining the SessionID value and including it in requests to the server. Hence is it not a wise approach to store sensitive infomation in session.
if we set session Mode="off" in web.config, session will be disabled in the application.
In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name.
To add data in session- Session["LoggedInUser"] ="Virtual Classes";
To Retrive data from session- String loggedInUser= Session["LoggedInUser"].tostring();
When we use session some events gets fire, below are the list of events those gets fire-
1-Session_Start:-This event is called when a new session for a client is created(when a new user requests a page).
void Session_Start(object sender, EventArgs e)
{
// Code that will be executed when a new session is started
}
2-Session_End :-This event is called after the session timeout period is over or when a session is abandoned or expires. A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes.
void Session_End(object sender, EventArgs e)
{
// Code that will be executed when a session ends.
}
You can handle both these events in the global.asax file of your web application.
If you want remove or clear session folloing methods provided by ASP.NET:
Session.Remove(SessionName)-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.
Session.Abandon()-Cancel the current session.
There is no difference between Clear and RemoveAll. RemoveAll() calls Clear() internally.
For performance optimization, we can enable or disable session because each and every page read and write access of the page involves some performance overhead. So it is always a better approach to disable session if not required.
you can also set the timeout interval so that the session will get expire after a certain period of time.

Session.Timeout=30 //sesion will expire after 30 min.
Use the Abandon method to end a session immediately: Session.Abandon
In ASP.NET, there are the following session modes available:


1-InProc Session Mode-This is the default session mode in ASP.NET. Its stores session information in Application Pool memeroy. This is the best session mode for web application performance. But the main disadvantage is that, it will lose data if we restart the server. If the client request for data, the state provider read the data from an in-memory object and returns it to the client. It can be very helpful for a small web site and where the number of users is very less. We should avoid InProc in a Web Garden scenario.the memory space of the ASP.NET worker process.
Advantages:

1-It store session data in a memory of the current application domain.So accessing data is very fast.
2-There is not requirement of serialization to store data in InProc session mode.
Disadvantages:
1-If the worker process or application pool is recycled, all session data will be lost.
2-Though it is the fastest but if the session data is more then it can affect performance.
3-In Proc session mode is not suitable for web farm and web garden scenarios.


2-StateServer Session Mode-StateServer uses a stand-alone Windows Service which can be run on a separate server so it is independent of IIS. This is also called Out-Proc session mode.This session state is managed by a service called aspnet_state.exe. This server may run on the same system, but it's outside of the main application domain where your web application is running. This means if you restart your ASP.NET process, your session data will still be alive. This approaches has several disadvantages due to the overhead of the serialization and de-serialization involved, it also increases the cost of data access because every time the user retrieves session data, our application hits a different process. In StateServer session mode, session data is maintained by aspnet_state.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.
Advantages:

1-It keeps data separate from IIS so any issues with IIS will not hamper session data.
2-It is useful in web farm and web garden scenarios.
Disadvantages:
1-Process is slow due to serialization and de-serialization.
2-State Server always needs to be up and running.
3-SQL Server Session Mode-This session mode provide us more secure and reliable session management in ASP.NET. This is also called Out-Proc session mode. In this session mode, session data is serialized and stored in A SQL Server database. It keeps data in a centralized location (database). It is the best option for using in web farms though.We should use the SQLServer session mode when we need to implement session with more security. If there happens to be frequent server restarts, this is an ideal choice. We can use SQLServer session mode when we need to share session between two different applications. To setup SQL Server, we need below SQL scripts:
For installing: InstallSqlState.sql
For uninstalling: UninstallSQLState.sql
The easiest way to configure SQL Server is using the aspnet_regsql command.
SQLServer session 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 Custom provider 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. Configuration for SQLServer Session Mode-In SQLServer session mode, we store session data in SQL Server, so we need to first provide the database connection string in web.config. The sqlConnectionString attribute is used for this. After we setup the connection string, we need to configure the SQL Server.
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:
Parameters-
-ssadd- Add support for SQLServer mode session state.
-S Server name.
-U User name.
-P Password.
Step 3: Open SQL Server Management Studio, check if a new database ASPState has been created, and there should be two tables:
ASPStateTempApplications
ASPStateTempSessions
sessionState mode="SQLServer" cookieless="true " regenerateExpiredSessionId="true " timeout="30" sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" stateNetworkTimeout="30"
Advantages:
1-Session data not affected if we restart IIS.
2-The most reliable and secure session management.
3-It keeps data located centrally, is easily accessible from other applications.
4-Very useful in web farms and web garden scenarios.
Disadvantages:
1-Processing is very slow in nature.
2-Object serialization and de-serialization creates overhead for the application.
3-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.
4- Custom Session Mode-Commonly we use the InProc, StateServer, or SQLServer session modes for our application, but we also need to know the fundamentals of the 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. You can implement custom providers that store session data in other storage mechanisms simply by deriving from the SessionStateStoreProviderBase class. You can also generate a new session ID by implementing ISessionIDManager. In the Initialize method, we can set a custom provider. This will initialize the connection with that provider. SetItemExpireCallback is used to set SessionTimeOut. We can register a method that will be called at the time of session expiration. InitializeRequest is called on every request and CreateNewStoreData is used to create a new instance of SessionStateStoreData.
Advantages:
1-We can use an existing table for storing session data. This is useful when we have to use an existing database.
2-It's not dependent on IIS, so restarting the web server does not have any effect on session data.
3-We can crate our own algorithm for generating session ID.
Disadvantages:
1-Processing of data is very slow.
2-Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.
3-It is always recommended to use a third party provider rather than create your own.

Application Variables

Application variables are the variables which remains common for all the application users. Application variable's value can be used across the whole application and they die only when the application stops. You can think of the Application object as a global container for information that is available to all pages of your ASP application. The Application object is instantiated when the first page of your application is requested and remains available until the Web service is shut down. Application variable can be accessed through the property of HTTPContext Object. All HTTPModules and Handlers have access to this property. Use of Application variable is same as Session,but these value are shared for all users. Application State is stored in the memory of the the server and it is faster than storing and retrieving information in a database.
Application State does not have a default expiration period. When we close the worker process the application object will be lost.Application state is not thread safe.
How to use Application object in an ASP.NET-
To Store value in application variable- Application["AppValue"] = value
One thing to keep in mind is that application variable stores the data as of Object type, so we need to convert it in the appropriate type while reading value.

To retrieve value from application variable- string value=(string)Application["AppValue"]

A classic example of Application variable is to show the number of user currently online in a website. This can be done in the following steps:
Add an onLineUser counter variable on ApplicationStart method of Global.asax file:
protected void Application_Start(object sender, EventArgs e)
{
//this event is execute only once when application start
Application["onLineUser"] = 0; //application variable initialized to 0 as there will be no logged in user at this point.

}
protected void Session_Start(object sender, EventArgs e)
{
//application variable is increased by 1 when session in starts
Application.Lock();
Application["onLineUser"] = (int) Application["onLineUser"]+1;
//we know whenever a new user opens the website, a new session is created and Session_Start method of Global.asax is called. So we can increase the counter in this method.

Application.UnLock();
}
protected void Session_End(object sender, EventArgs e)
{
//application variable is decrease by 1 when session in ends
Application.Lock();
Application["onLineUser"] = (int)Application["onLineUser"] - 1;
Application.UnLock();
}
Now, we can fetch the value of Application["onLineUser"] and display on web page.
We should use the Locks, else we may get the wrong result because this may be updated at the same time and updated data is not correct.
Let's say we currently have Application["onLineUser"] is 3 and at the same time, two sessions read the value 3 and make an increment to 4 and updated it. Application state as 4. So although two users are logged in, the counter is increased by one only. So to avoid this, we should use the locks.
Application state is stored in memory on the server, so a large amount of data in application state can fill up server memory quickly.
Application state is not shared between multiple servers within a Web farm or between worker processes in a Web garden.
Application events are only triggered when a client requested for a ASP.NET web page, they are not triggered when an HTML page,ISAPI and Common Gateway Interface (CGI) scripts. So make sure that these applications do not depend on specific events having occurred within an ASP.NET page. Otherwise, the ISAPI or CGI script may fail and cause the Web server to stop responding.