Maintaining State with the Session Object

The Session object provides a mechanism that allows data to be stored on a per-client basis. Before delving into how to use the Session object, you need to understand the concept of a session state.

ASP.NET Session State

What is a session? A session is a period of time during which a unique user interacts with a Web Server. Session state is the ability to retain data for this unique user during the session.

The Session object is very similar to a hash table, in that it stores data in key-value pairs. Data stored in the Session object can be retrieved for a predetermined amount of time.

The following is the syntax used to store data in the Session object:

Session("Key") = Value

The following is the syntax used to retrieve data from the application object:

Value = Session("Key")

Session state is managed individually for each active ASP.NET session. The session state can be maintained either in memory, in the memory of a remote server, or in an SQL Server database.

The session state is identified and tracked by means of a 120-bit SessionID. This SessionID is generated using an algorithm that guarantees uniqueness so that there cannot be more than one ASP.NET session with the same SessionID, thus preventing collisions. The same algorithm is responsible for guaranteeing that the SessionID is created randomly, making it more difficult for malicious users to attempt to calculate an existing session's SessionID.

The SessionID is transmitted as part of the Web requests. Depending on the type of application, the SessionID is transmitted either by using an HTTP cookie or by modifying a URL.

Choosing which session state provider to use is a serious decision. The four distinct ways to store session state for an application are in-process session state, out-of-process session state with ASP.NET State Service, out-of-process session state in an SQL database, and out-of-process session state as a Web Service. Each of these has advantages and disadvantages. In-process session state is the fastest solution, but cannot be used for Web farms. Out-of-process session state solutions are better suited for scaling an application across multiple processors or multiple computers. Out-of-process session state should be used when the data being processed cannot be lost in the case of a server or a process being restarted.

Before considering these methods in more detail and getting our hands dirty with some implementations of session state, let's take a look at how session state is configured.

Like most other Web application configuration settings, ASP.NET Session State settings are configured through the ASP.NET XML configuration file web.config.

The following is the default sessionState element used to configure the session state setting from within the web.config file:

<sessionState
  mode="InProc"
  cookieless="false"
  timeout="20"
  stateConnectionString="tcpip=127.0.0.1:42424"
  sqlConnectionString="data source=127.0.0.1;user id=sa;password="
/>

Let's take a look at each of the attributes that appear in the sessionState element.

The mode attribute specifies where to store the session state data; mode is the only mandatory attribute.

There are four possible settings for the mode attribute:

  • Off Indicates that session state is not enabled

  • InProc Indicates that session state is stored locally

  • StateServer Indicates that session state is stored on a remote server

  • SQLServer Indicates that session state is stored on the SQL Server

The mode options will be discussed in more detail throughout this chapter.

The cookieless attribute is a Boolean value that specifies whether sessions without cookies should be used to identify client sessions. A value of true indicates that sessions without cookies should be used. The default value, false, indicates that sessions without cookies should not be used.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value is 20.

The stateConnectionString attribute specifies the server name and port where the session state is stored remotely. The default setting is tcpip=127.0.0.1:42424. This attribute is required only when the mode attribute is set to StateServer.

Finally, the sqlConnectionString attribute specifies the connection string for a SQL Server database. The default setting is data source=127.0.0.1;user id=sa; password=. This attribute is required only when the mode attribute is set to SQLServer.

In-Process Session State

The in-process mode is the default setting for ASP.NET (see Figure 9.2). In-process session state is, as the name suggests, managed within the ASP.NET process. This means that if the ASP.NET process is recycled, any data stored in session state is lost.

Figure 9.2. When you use in-process session state management, the State Manager runs as part of the ASP.NET process.


Why use in-process, if there are other settings that are available and will give better reliability? The most important reason for using in-process is performance. Because in-process session state is managed locally, it will be much faster to read from and write to than the other available options. The other options will normally entail cross-process calls that take significantly longer to process. In-process state maintenance cannot be used with Web Farms because the state will be managed on a specific instance of Microsoft Internet Information Service (IIS). Each additional request made to the Web Service will not necessarily be made to the same instance of IIS, therefore the state may not exist there.

To see how the Session object is used within a Web Service, we will create a simple Web Service that uses the Session object to store the number of searches that users have performed on specific criteria. To simplify this example, the return value of the WebMethod will be the search count.

Create a new ASP.NET Web Service project. In the Solution Explorer, select Service1.asmx and rename it StatefulService.asmx. Expand the StatefulService.asmx node and open the StatefulService.asmx.vb file for editing. Add the following code to the StatefulService.asmx.vb file:

 <WebMethod(EnableSession:=True)> _
Public Function UserSearch(ByVal Criteria As String) As Integer
    If Session(Criteria) Is Nothing Then
        Session(Criteria) = 1
    Else
        Session(Criteria) = CInt(Session(Criteria)) + 1
    End If
    UserSearch = CInt(Session(Criteria))
End Function

This WebMethod is very similar to the other implementations that you have seen up to now. The only difference that you may have noticed is that a new property, EnableSession, has been added to the WebMethod attribute. Setting this property to true is necessary to enable storage and retrieval of data stored in the session state.

The method starts off by checking whether a variable, with a key identical to criteria that was passed into the WebMethod, has already been stored in the Session object (Line 3). Based on the outcome, the method either initializes the variable with the value of 1 or increments that variable by 1.

Let's take a look at how state is maintained by executing this sample Web Service. To do this, open a Web browser and set the URL to point to the StatefulService.asmx file. Select the UserSearch WebMethod by clicking the UserSearch link at the top of the page. The Test interface should now appear. Enter a value for the Criteria and click the Invoke button.

A new browser should open up to produce the results of the WebMethod call.

Now click the Refresh button to execute the WebMethod again. You will notice that the result has been incremented by one.

To get a picture of how the call would be made from other environments, such as a Win32 application or another Web Service, we will make a small modification to the Web.config file. In the sessionState element, change the cookieless attributes value to true. The following code shows the settings:

<sessionState
  mode="InProc"
  cookieless="true"
  timeout="20"
  stateConnectionString="tcpip=127.0.0.1:42424"
  sqlConnectionString="data source=127.0.0.1;user id=sa;password="
/>

Close the browser with the WebMethod results. Now click the Invoke button within the browser that shows the WebMethod's test interface. The window should look similar to Figure 9.3. Notice that the SessionID is displayed within the URL.

Figure 9.3. The results returned from the UserSearch WebMethod.


As an introduction to the next section, open up a command prompt and type the following line:

iireset

After the Internet Information Services have been restarted, go back to the browser displaying the results from the UserSearch WebMethod's execution. Click the Refresh button again.

It would seem that we are back to “square one.” What you have just done is simulate the recycling of the ASP.NET process. As you have noticed, all session state has been erased.

Out-of-Process Session State

The new out-of-process state management option in ASP.NET exists in two variations:

  • Out-of-process state management with the ASP.NET State Service

  • Out-of-process state management with SQL Server

We will begin by introducing the new ASP.NET State Service and continue later to the SQL Server implementation.

Using the ASP.NET State Service

The ASP.NET State Server is implemented by the new ASPState Service, included in the .NET Framework. Because this is a Windows NT service, this option will only be available on the Windows NT-based operating systems (Windows NT 4.0, Windows 2000 and Windows XP). Figure 9.4 shows how the State Manager exists in a separate process when using the ASP.NET State Server.

Figure 9.4. When used with ASP.NET State Server, State Manager runs as a separate process.


To use the ASP.NET State Service for out-of-process state management, the service must be running. If the service is not running, it can be started by opening up the Settings Microsoft Management Console, right-click the ASP.NET State Service, and select Start from the pop-up menu. Figure 9.5 demonstrates how the ASP.NET State Service can be started.

Figure 9.5. Starting the ASP.NET State Service.


Another way to start the service is to open a command prompt and type the following:

net start aspnet_state

NOTE

If you use the ASP.NET State Service for state management, it is advisable to set the startup parameter for the service to automatic.


After the ASP.NET State Server has been activated, the Web application needs to be configured to take advantage of this option. Again, configuring the Web application to use this option will be performed by editing the web.config file. The following code shows the settings:

<sessionState
  mode="StateServer"
  cookieless="true"
  timeout="20"
  stateConnectionString="tcpip=127.0.0.1:42424"
  sqlConnectionString="data source=127.0.0.1;user id=sa;password="
/>

Only two changes need to be made from the default settings, thus moving from in-process to out-of-process state management. The mode attribute needs to be changed to StateServer and the stateConnectionString needs to be configured. Note that the stateConnectionString attribute is made up of three parts. The syntax is in the following format:

								stateConnectionString="<protocol>=<server>:<port>"

At the time of this book's publication, the only known value for protocol is tcpip. Server indicates the name or IP address of the server that will act as the state management server, and the value of port is the port number to be used.

The value of the stateConnectionString specifies the local server.

Again, we will take a look at how state is maintained by executing the sample Web Service just as we did in the previous section. Open a Web browser and test the UserSearch WebMethod again.

As you did before, click the Refresh button a few times and you will notice that after each click, the result is incremented by one. Now, restart the Internet Information Services. Once again, click the Refresh button in the Web browser. Notice that the state is maintained, even though the ASP.NET process has been recycled.

There is, of course, a downfall to this mechanism. If the machine hosting the Session Manager becomes unavailable, or worse, is restarted, all session state is lost. This brings us to the next option, out-of-process state management with SQL Server.

Using SQL Server

Out-of-process state management with SQL Server is very similar to out-of-process state management with the ASP.NET State Server, except that it is even more robust. When using the previous mechanism (ASP.NET State Service in StateServer mode), the session state is stored in memory on the designated machine. When using the ASP.NET State Service in SQLServer mode, the state is maintained in a database. If the server with ASP.NET State Service mode set to StateServer is restarted, all state is lost. On the other hand, when using the SQLServer mode, even if the server hosting the SQL Server in which the state is being maintained is restarted, the state will be retained. When the server becomes available again, the state will be available again. Figure 9.6 displays the process boundaries that exist when using the SQLServer mode.

Figure 9.6. When used with SQL Server, ASP.NET state management not only runs as a separate process but is persisted to the database.


Configuring ASP.NET to manage state with SQL Server requires two steps. The first step is a setup procedure that needs to be performed only once. The second step entails making two minor changes to the web.config file.

To manage session state by using SQL Server, the necessary tables and stored procedures need to be created. ASP.NET will use the stored procedures to persist state into the tables. The .NET Framework SDK includes an SQL script that will create all of the SQL Server objects needed to perform this task.

The SQL script file is named InstallSqlState.sql and is found in the [system drive] winntMicrosoft.NETFramework[version] directory.

To execute this SQL script, you can use the command line tool osql.exe that is provided by SQL Server. (When installing the .NET Framework, a lightweight version of SQL Server is installed.) You can also use the Query Analyzer utility if you have a full version of SQL Server installed. Administrator rights equivalent to that of sa are needed to execute the script because modifications will be made to the SQL Servers master database.

To use the command-line tool (osql.exe), the following syntax is used:

osql /S [server name] /U [user] /P [password] /i InstallSqlState.sql

You need to replace [server name] with the name of the server that you are going to use as the State Server. Also replace [user] and [password] with the corresponding machine's administrator's credentials.

After executing the script, you should receive a result similar to that shown in Figure 9.7.

Figure 9.7. Execution of the InstallSqlState script.


Next, as mentioned earlier, the web.config file needs to be configured to specify the mode and the database.

<sessionState
      mode="SQLServer"
      stateConnectionString="tcpip=127.0.0.1:42424"
      sqlConnectionString="data source=127.0.0.1;
                           user id=sa;password=password"
      cookieless="true"
      timeout="20"
    />

The mode attribute is changed to SQLServer and the sqlConnectionString points to a database that has been set up on either the local machine or a remote machine.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.10