Using Session State


The ASP.NET framework includes built-in support for automatically tracking and associating resources on the server with users. You can associate information with users as they move from page to page at your Web site by taking advantage of session state.

By default, when a user first requests a page from an ASP.NET Web site, the Web site automatically adds a session cookie to the user's browser. This cookie, named the _ ASP.NET_SessionID cookie, tracks the user for the remainder of his or her visit to the Web site.

By using session state, you can associate any type of information with the user that you please . For example, you can use session state to display the user's name on each page he or she requests. Or you can use session state to associate a shopping cart with the user as he or she browses from page to page. You can also use session state to enable the user to complete HTML forms that span multiple pages.

In the following sections, you learn how to take advantage of the built-in session state facility included in the ASP.NET framework. You learn how to store objects in session state and how to manage session state in process, with a Windows service, and with a database table.

Adding Items to Session State

You can store any object in session state by using a statement like the following:

 
 Session( "myItem" ) = "Hello!" 

This statements adds a new item, named myItem , to session state with the value "Hello!" .

After you add an item to session state, you can retrieve the item on any page that a user visits . The following statement retrieves myItem from session state and displays its value:

 
 Response.Write( Session( "myItem" ) ) 

You should be aware of three points when using session state. First, any items you add to session state remain there for the duration of a user's visit to your Web site. Normally, the items continue to be associated with the user until the user shuts down his or her browser, the item is explicitly removed from session state, or the user does not request a page for more than 20 minutes.

Second, items added to session state are added relative to a particular user. If Fred requests a page that adds an item named myItem to session state with the value "Hello!" and Jane requests a page that adds an item named myItem to session state with the value "Goodbye!" , no conflict occurs. Separate copies of each item added to session state are created for each user.

Finally, you can add any object to session state. Because objects stored in session state are stored on the server, session objects are not subject to the same size limitations as cookies. For example, you can add a DataSet to session state like this:

 
 Session( "myDataSet" ) = dstDataSet 

After you add the DataSet to session state, you can retrieve the same DataSet in whatever pages the user requests.

CAUTION

Almost any object can be added to session state. The one requirement is that the object support serialization.


Be aware, however, that a separate copy of each item added to session state is created for each user who requests the page. If you place a DataSet with 400 records into session state in a page, and 500 users request the page, you have 500 copies of that DataSet in memory.

Removing Items from Session State

You can remove an item from session state by using the Remove() or RemoveAll() method. The Remove() method removes a particular item for the current user. For example, to remove an item named myItem associated with the user making the current request, you would use the following statement:

 
 Session.Remove( "myItem" ) 

The RemoveAll method removes all the items stored in session state for a particular user:

 
 Session.RemoveAll 

Starting a User Session

A user session starts when a user requests the first page from a Web site. When the first page is requested , the Web server adds the ASP.NET_SessionID cookie to the user's browser.

You can detect the start of a new session by using the NewSession property. When a new session starts, the NewSession property returns the value True :

 
 Response.Write( Session.NewSession ) 

Each user session is assigned a unique session ID. You can retrieve the value of a session ID like this:

 
 Response.Write( Session.SessionID ) 

A session ID is guaranteed to be unique among all current user sessions. However, a session ID is not guaranteed to be unique over time; it might be recycled for a new session in the future.

Ending a User Session

When does a user session end? Remember that HTTP is a stateless protocol. A Web server has no means of detecting when a user leaves a Web site. Instead, the Web server detects that a certain period of time has passed without the user requesting a page. At that point, the Web server assumes that the user has left, and it removes all items in session state associated with that user.

By default, a session times out when a user has not requested a page for more than 20 minutes. If the same user requests a page after a 20-minute period has elapsed, that person is treated as a new user.

You might want to change the session timeout period. Setting a smaller timeout period makes your Web site more scalable because the server can reclaim memory devoted to individual session instances faster. On the other hand, you might want to set a longer timeout period if you expect that users might need to devote more than 20 minutes to a page.

You can modify the default timeout period for a session in several ways. To set a new session timeout period, modify the Timeout property of the Session object like this:

 
 Session.Timeout = 10 

This statement sets the session timeout period to 10 minutes. The new session timeout value applies to the remainder of the user's visit to the Web site.

You also can modify the session timeout period in the Web.Config file. For example, placing the following Web.Config file in the root directory of your application changes the default session timeout period to 60 minutes:

 
 <configuration>   <system.web>     <sessionState timeout="60" />   </system.web> </configuration> 

You also have the option of explicitly ending a user session. You can do so by calling the Abandon method like this:

 
 Session.Abandon 

If a user requests a new page after the Abandon method is called, he or she is treated as a new user. The user is assigned a new session ID and all the items in session state previously associated with that user are removed from memory. The Abandon method is often used with sign-out pages.

CAUTION

Calling the Abandon method does not end the user session until the current page finishes processing. You can still retrieve items from session state after the Abandon method is called. For example, the following statements display "Hello!" twice:

 
 Session( "myItem" ) = "Hello!" Response.Write( Session( "myItem" ) ) Session.Abandon Response.Write( Session( "myItem" ) ) 

However, the items will be gone from memory when the user makes a new page request.


Handling Session Events

You can capture two events related to session state: Session_Start and Session_End . The Session_Start event is raised when a user requests the first page from a Web site. The Session_End event is triggered when the user session ends.

You can capture both of these events by adding subroutines to the Global.asax file. For example, suppose that you want to create a page that displays the current number of active user sessions at your Web site. You could do so by using the Global.asax file in Listing 16.2 (this page can be found in the SessionStart subdirectory).

NOTE

The Global.asax file must be located in your application's root directory. For more information on the Global.asax file, see Chapter 15, "Creating ASP.NET Applications."


Listing 16.2 SessionStart/Global.asax
 <Script Runat="Server"> Sub Session_Start()   If Application( "SessionCount" ) Is Nothing Then     Application( "SessionCount" ) = 0   End If   Application( "SessionCount" ) += 1 End Sub Sub Session_End()   Application( "SessionCount" ) -= 1 End Sub </Script> 

The C# version of this code can be found on the CD-ROM.

Two subroutines are declared in Listing 16.2. The first subroutine, Session_Start , executes at the start of each new user session. This subroutine increments an item stored in application state by one.

The second subroutine, Session_End , executes whenever a user session ends. This subroutine decrements an item stored in application state by one.

CAUTION

Modifying the Global.asax file automatically drops all items from session state. If you modify the Global.asax file in a production Web site, all user sessions are terminated . (This warning applies when session state is stored in process.)


The page in Listing 16.3 displays the current number of user sessions by displaying the value of SessionCount (see Figure 16.2).

Listing 16.3 SessionStart/SessionCount.aspx
 <Script Runat="Server"> Sub Page_Load   lblSessionCount.Text = Application( "SessionCount" ) End Sub </Script> <html> <head><title>SessionCount.aspx</title></head> <body> Current Sessions: <asp:Label   ID="lblSessionCount"   Runat="Server" /> </body> </html> 

The C# version of this code can be found on the CD-ROM.

Figure 16.2. Displaying number of current users.

graphics/16fig02.jpg

You also can use the Session_Start subroutine to automatically redirect users to a particular page when a user session begins. You might want to force all users who visit your Web site to go to the Default.aspx page before visiting any other page. The Global.asax file in Listing 16.4 automatically redirects new users to the Default.aspx page. (This page can be found in the SessionRedirect subdirectory.)

Listing 16.4 SessionRedirect/Global.asax
 <Script Runat="Server"> Sub Session_Start   If Instr( Request.Path.ToLower, "/default.aspx" ) = 0 Then     Response.Redirect( "Default.aspx" )   End If End Sub </Script> 

The C# version of this code can be found on the CD-ROM.

If the first page a user requests is not the Default.aspx page, he or she is automatically redirected to this page. Because the Session_Start event is triggered only once per user session, this subroutine executes only once when the user makes the first page request.

Storing Session State in Process

By default, session state is managed in process. All items added to session state are stored in the same process as the Web server.

The advantage of storing session state in process is performance. You can store and retrieve items much faster in session state when you do not need to marshal the data across separate processes.

ASP Classic Note

In Classic ASP, session state was always managed in process.


Storing session state in process does, however, have some significant disadvantages:

  • If, for whatever reason, the server crashes, you lose all data stored in session state. You lose session data when an ASP.NET application is reloaded for any reason. For example, modifying the Global.asax file drops all active user sessions.

  • If session state is stored in process, session state cannot be shared across multiple servers. Storing session state in process limits the scalability of your Web site because you cannot configure multiple servers to handle requests. In other words, storing session state in process is incompatible with Web farms.

ASP.NET provides you with the option of managing session state out of process. In the following sections, you learn two methods of storing session data in a separate process: First, you learn how to manage session state with a separate Windows service. Second, you learn how to manage a session state with a database.

Storing Session State in a Windows Service

Instead of storing session data in process, you can store the data in a separate Windows service. To do so, you need to complete the following two steps:

  • Start the ASP.NET Windows service.

  • Modify the Web.Config file to set the sessionstate mode to the value stateserver and specify the location of the State service.

You can start the ASP.NET Windows service by going to Start, Programs, Administrative Tools, Services. Find the ASP.NET State service and click the Start Service button (the VCR play button).

You should modify the settings for the service so that it starts automatically when Windows starts. To do so, double-click the name of the service and set Startup type to the value Automatic (see Figure 16.3).

Figure 16.3. Automatically starting the ASP.NET State service.

graphics/16fig03.jpg

Alternatively, you can start the ASP.NET State service by executing the following statement from a command prompt:

 
 net start aspnet_state 

After you start the service, you need to modify the Web.Config file for your application to use the service. The Web.Config file in Listing 16.5 contains the proper settings. (This file can be found in the SessionService subdirectory.)

Listing 16.5 SessionService/Web.Config
 <configuration>   <system.web>     <sessionState        mode="StateServer"        stateConnectionString="tcpip=127.0.0.1:42424" />   </system.web> </configuration> 

The C# version of this code can be found on the CD-ROM.

In the Web.Config file in Listing 16.5, the mode attribute is set to the value StateServer (by default, mode is set to the value InProc ). The stateConnectionString attribute is assigned information about the location of the service. In this example, the State service is assumed to be running on the same machine as the Web server on port 42424.

You could run the ASP.NET State service on a separate server by supplying the IP address of the server. If you supply this address, any information stored in session state is not lost even if your Web server goes down.

You also can use the same State service with multiple Web servers. For example, you can build a Web farm in which all the servers share the same state information stored on a separate server.

After you enable the ASP.NET State service, you can store and retrieve items from session state just as you normally would. However, when you store items in session state with the State service enabled, the items are stored in a separate process.

To test that items are actually being stored in a separate process, add an item to session state and restart the Web service by launching the Internet Services Manager, right-clicking the name of your server, and clicking Restart IIS. Restarting the Web service should have no effect on the items stored in the State service.

A test page (named TestSession.aspx ) is included in the SessionService subdirectory.

Storing Session State in a Database Table

You also can manage session state out of process by storing session data in a Microsoft SQL Server database. The advantage of this approach is that you can cluster multiple database servers so that if one server fails, another database server can take over the state management.

Storing session state in a SQL Server database requires the completion of the following two steps:

  • Create the necessary objects in SQL Server to manage the session data by executing the InstallSqlState.sql batch file.

  • Modify the Web.Config file to set the sessionState mode to the value SQLServer and specify the connection information for the SQL Server database.

To complete the first step, launch the Microsoft SQL Server Query Analyzer and log in to SQL Server by using the sa account.

Next, open the InstallSqlState.sql batch file. You can find this file at the following location:

 
 WINNT\Microsoft.NET\Framework\[  Framework Version  ]\InstallSqlState.sql 

After you load the InstallSqlState.sql batch file, click the Execute Query button. Executing this batch file creates a new database named ASPState on your database server. The batch file also creates several other objects, including tables to store the state data and stored procedures to add and retrieve the data.

NOTE

The InstallSqlState.sql batch file adds a new job to SQL Server. This job clears away expired sessions. For the job to execute, the SQL Server Agent service must be running.


After the batch file is finished executing, you need to restart the SQL Server service. Launch the SQL Server Service Manager, and stop and start the SQL Server service.

NOTE

If you want to remove the objects added to SQL Server by the InstallSqlState.sql batch file, you can execute the UninstallSqlState.sql batch file from Query Analyzer.


The final step is to create a new Web.Config file that configures session state to store data in the database. A Web.Config file with the necessary settings is included in Listing 16.6. (This file is located in the SQLState subdirectory.)

Listing 16.6 SQLState/Web.Config
 <configuration>   <system.web>     <sessionState        mode="SQLServer"        sqlConnectionString="Server=127.0.0.1;UID=sa;PWD=secret" />   </system.web> </configuration> 

The C# version of this code can be found on the CD-ROM.

In the Web.Config file in Listing 16.6, the mode attribute is set to the value SQLServer . A valid SQL Server connection string is also supplied. In this example, the SQL connection string points to the local server and passes the credentials for the sa account. Notice that you do not specify a database in the connection string.

After you create the Web.Config file, all data added to session state is stored on the database. You can test it by using Query Analyzer. The session data is stored in the tempdb database in a table named AspStateTempSessions . Each row in this table represents the data stored for one user session.

Because the session data is stored in a database table, you can analyze the session data using standard SQL queries. For example, if you want to retrieve a count of the number of active user sessions, you can execute the following query against the tempdb database:

 
 SELECT COUNT( SessionID ) FROM AspStateTempSessions WHERE Expires > GetDate() 

This query returns a count of the session IDs in the AspStateTempSession table where the session hasn't expired.

Disabling Session State

By default, session state is enabled for all pages in an application. You can improve the performance of your Web application by disabling session state for pages when you don't need to use it.

To disable session state for a particular page, modify the value of the EnableSessionState attribute in the page directive like this:

 
 <%@ Page EnableSessionState="False" %> 

If you need to retrieve objects from session state but don't need to add objects to it, you can set the EnableSessionState attribute to ReadOnly like this:

 
 <%@ Page EnableSessionState="ReadOnly %> 

You also can disable session state for all the pages in an application by adding the following Web.Config file to the root directory of the application:

 
 <configuration>   <system.web>     <sessionState        mode="Off" />    </system.web> </configuration> 

The Web.Config file takes precedence over the page directive for particular pages. So, if you disable session state with the Web.Config file, you cannot selectively enable session state with the page directive.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net