Thursday, October 2, 2008

ASP.Net Session



Like cookies, items stored in Session state are scoped to a particular user. You can use Session state to store user preferences or other user-specific data across multiple page requests.


Unlike cookies, Session state has no size limitations. If you had a compelling need, you could store gigabytes of data in Session state.


Furthermore, unlike cookies, Session state can represent more complex objects than simple strings of text. You can store any object in Session state. For example, you can store a DataSet or a custom shopping cart object in Session state.



When you use Session state, a session cookie named ASP.NET_SessionId is added to your browser automatically. This cookie contains a unique identifier. It is used to track you as you move from page to page.


When you add items to the Session object, the items are stored on the web server and not the web browser. The ASP.NET_SessionId cookie is used to associate the correct data with the correct user.


By default, if cookies are disabled, Session state does not work. You don't receive an error, but items that you add to Session state aren't available when you attempt to retrieve them in later page requests. (You learn how to enable cookieless Session state later in this section.)


By default, the ASP.NET Framework assumes that a user has left the website when the user has not requested a page for more than 20 minutes. At that point, any data stored in Session state for the user is discarded.


Using the Session Object


The main application programming interface for working with Session state is the HttpSessionState class. This object is exposed by the Page.Session, Context.Session, UserControl.Session, WebService.Session, and Application.Session properties. This means that you can access Session state from just about anywhere.


This HttpSessionState class supports the following properties (this is not a complete list):

  • CookieMode Enables you to specify whether cookieless sessions are enabled. Possible values are AutoDetect, UseCookies, UseDeviceProfile, and UseUri.
  • Count Enables you to retrieve the number of items in Session state.
  • IsCookieless Enables you to determine whether cookieless sessions are enabled.
  • IsNewSession Enables you to determine whether a new user session was created with the current request.
  • IsReadOnly Enables you to determine whether the Session state is read-only.
  • Keys Enables you to retrieve a list of item names stored in Session state.
  • Mode Enables you to determine the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer.
  • SessionID Enables you to retrieve the unique session identifier.
  • Timeout Enables you to specify the amount of time in minutes before the web server assumes that the user has left and discards the session. The maximum value is 525,600 (1 year).


The HttpSessionState object also supports the following methods:

  • Abandon Enables you to end a user session.
  • Clear Enables you to clear all items from Session state.
  • Remove Enables you to remove a particular item from Session state.


The Abandon() method enables you to end a user session programmatically. For example, you might want to end a user session automatically when a user logs out from your application to clear away all of a user's session state information.


Handling Session Events


There are two events related to Session state that you can handle in the Global.asax file: the Session Start and Session End events.


The Session Start event is raised whenever a new user session begins. You can handle this event to load user information from the database. For example, you can handle the Session Start event to load the user's shopping cart.


The Session End event is raised when a session ends. A session comes to an end when it times out because of user inactivity or when it is explicitly ended with the Session.Abandon() method. You can handle the Session End event, for example, when you want to automatically save the user's shopping cart to a database table.


void Session_Start(object sender, EventArgs e)

{

//Code to handle Session at start of application

}


void Session_End(object sender, EventArgs e)

{

//Code to handle Session when it expires

}


Controlling When a Session Times Out


By default, the ASP.NET Framework assumes that a user has left an application after 20 minutes have passed without the user requesting a page. In some situations, you'll want to modify the default timeout value.


For example, imagine that you are creating a college admissions website and the website includes a form that enables an applicant to enter a long essay. In that situation, you would not want the user session to timeout after 20 minutes. Please, give the poor college applicants at least an hour to write their essays.


The disadvantage of increasing the Session timeout is that more memory is consumed by your application. The longer the Session timeout, the more server memory is potentially consumed.


You can specify the Session timeout in the web configuration file or you can set the Session timeout programmatically.


Using Cookieless Session State


By default, Session state depends on cookies. The ASP.NET Framework uses the ASP.NET_SessionId cookie to identity a user across page requests so that the correct data can be associated with the correct user. If a user disables cookies in the browser, then Session state doesn't work.


If you want Session state to work even when cookies are disabled, then you can take advantage of cookieless sessions. When cookieless sessions are enabled, a user's session ID is added to the page URL.


Here's a sample of what a page URL looks like when cookieless sessions are enabled:


http://localhost:4945/Original/(S(5pnh11553sszre45oevthxnn))/SomePage.aspx


The strange-looking code in this URL is the current user's Session ID. It is the same value as the one you get from the Session.SessionID property.


You enable cookieless sessions by modifying the sessionState element in the web configuration file. The sessionState element includes a cookieless attribute that accepts the following values:

  • AutoDetect The Session ID is stored in a cookie when a browser has cookies enabled. Otherwise, the cookie is added to the URL.
  • UseCookies The Session ID is always stored in a cookie (the default value).
  • UseDeviceProfile The Session ID is stored in a cookie when a browser supports cookies. Otherwise, the cookie is added to the URL.
  • UseUri The Session ID is always added to the URL.


When you set cookieless to the value UseDeviceProfile, the ASP.NET Framework determines whether the browser supports cookies by looking up the browser's capabilities from a set of files contained in the following folder:


\WINDOWS\Microsoft.NET\Framework\[version]\CONFIG\Browsers


If, according to these files, a browser supports cookies, then the ASP.NET Framework uses a cookie to store the Session ID. The Framework attempts to add a cookie even when a user has disabled cookies in the browser.


When cookie less is set to the value AutoDetect, the framework checks for the existence of the HTTP Cookie header. If the Cookie header is detected, then the framework stores the Session ID in a cookie. Otherwise, the framework falls back to storing the Session ID in the page URL.


Configuring a Session State Store


By default, Session state is stored in memory in the same process as the ASP.NET process. There are two significant disadvantages to storing Session state in the ASP.NET process.


You can set the Session state mode to any of the following values:

  • Off Disables Session state.
  • InProc Stores Session state in the same process as the ASP.NET process.
  • StateServer Stores Session state in a Windows NT process, which is distinct from the ASP.NET process.
  • SQLServer Stores Session state in a SQL Server database.
  • Custom Stores Session state in a custom location.


By default, the Session state mode is set to the value InProc. This is done for performance reasons. In-process Session state results in the best performance. However, it sacrifices robustness and scalability.


When you set the Session state mode to either StateServer or SQLServer, you get robustness and scalability at the price of performance. Storing Session state out-of-process results in worse performance because Session state information must be passed back and forth over your network.


Finally, you can create a custom Session state store provider by inheriting a new class from the SessionStateStoreProviderBase class. In that case, you can store Session state any place that you want. For example, you can create a Session state store provider that stores Session state in an Oracle or FoxPro database.


Thanks,

Paresh Bhole

No comments:

Hello

Thanks for checking out my post...

... Paresh Bhole