Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET Database Programming Weekend Crash Course - J. Butler, T. Caudill.pdf
Скачиваний:
31
Добавлен:
24.05.2014
Размер:
3.32 Mб
Скачать

Session 12—Maintaining State in ASP.NET

115

No More Cookies but Plenty of Milk!

In ASP.NET you can configure your application to store state without the use of cookies, also known as the cookieless method. In this method, ASP.NET simply munges the session id information into the URL of the requested page. This allows you to very easily implement your session information in a standard aspx page on server Foo, pass that information along to a relative path static html page, and then finally pass it back to a third aspx page and maintain state across the session. In order to do this, the session id information is encoded into the URL and thus isn’t dependent on the client to store it as a cookie. An example of a munged URL used when the cookieless method is used:

http://localhost/session12cookieless/(a5kb53fnuscirn55a4vt1gyt)/Webform2. aspx

The value a5kb53fnuscirn55a4vt1gyt highlighted in bold above is a unique key, which has been “munged” into the URL. This unique key allows the .NET Framework to locate session information specific to the user. In a cookie based implementation a similar value would be stored on the user’s hard drive as a cookie.

Advantages

The advantages of this method are:

Supports state maintenance for all browsers, even those without cookie support.

Allows you to pass session information between dynamic and static pages.

Disadvantages

The disadvantages of this method include:

Security risk associated with URL munging the data.

If implemented in-process, still requires that the user visit the session storing server to retrieve values.

How to make it happen

To implement this method, follow these steps:

1.Open the web.configWeb.config in the virtual directory of your ASP.NET application.

2.Locate the <system.Web> section of the Web.config file, or if none exists, create one.

3.Locate the <sessionstate> element.

4.Set the value of cookieless = true.

5.Save Web.config.

116

Saturday Afternoon

Here is an example of a correctly configured Web.config file enabling cookieless state maintenance:

<?xml version=”1.0” encoding=”utf-8” ?> <configuration>

<system.Web>

<sessionState

mode=”InProc”

stateConnectionString=”tcpip=127.0.0.1:42424” sqlConnectionString=”data source=127.0.0.1;user id=sa;password=” cookieless=”true”

timeout=”20”

/>

</system.Web>

</configuration>

Note

When modifying the Web.config file be sure to pay particular notice to the capitalization of sections and elements, the file is case sensitive and incorrect capitalization will create errors.

After implementing the method as described above you can now test the use of the cookieless option by turning off cookies in your Web browser, create a virtual directory, add the Web.config file to the virtual directory and create the following three pages illustrated in Listings 12-1, 12-2, and 12-3.

Listing 12-1 Code for Webform1.aspx

<HTML>

<HEAD>

<SCRIPT RUNAT=”server” ID=”Script1”>

Sub btn1_Click(Sender As Object, E As EventArgs) Session(“SomeValue”) = text1.Value

span1.InnerHtml = “Session data created/updated! <P>Your session contains:” & Session(“SomeValue”) & “</font>”

End Sub </SCRIPT>

</HEAD>

<BODY>

<FORM RUNAT=”server” ID=”Form1”>

<INPUT ID=”text1” TYPE=”text” RUNAT=”server” NAME=”text1”> <INPUT TYPE=”submit” ID=”btn1” NAME=”btn1” ONSERVERCLICK=”Btn1_Click” RUNAT=”server” VALUE=”Submit Query”>

</FORM>

<ASP:HYPERLINK ID=”HyperLink1” RUNAT=”server” NAVIGATEURL=”StaticPage1.htm”>Click here to navigate to a static page.</ASP:HYPERLINK>

<BR>

<SPAN ID=”span1” NAME=”span1” RUNAT=”server”></SPAN> </BODY>

</HTML>

Session 12—Maintaining State in ASP.NET

117

Listing 12-2 Code for Webform2.aspx

<HTML>

<HEAD>

<SCRIPT RUNAT=”server” ID=”Script1”> Sub Page_Load()

span1.InnerHtml = “Session data Recovered! <P>Your session contains: “ & Session(“SomeValue”) & “</font>”

End Sub </SCRIPT>

</HEAD>

<BODY>

<FONT SIZE=”6”><SPAN ID=”span1” NAME=”span1” RUNAT=”server”></FONT> <P>

Click <A HREF=”Webform1.aspx”>here</A> to modify the session variable </P>

</SPAN>

</BODY>

</HTML>

Listing 12-3 Code for staticpage1.htm

<HTML>

<HEAD>

<TITLE>Static Page</TITLE> </HEAD>

<BODY>

<P>

Static HTML Page. Of course there are no values to read, but click <A HREF=”Webform2.aspx”>

here</A> and you will see that session can still be recovered.

</P>

</BODY>

</HTML>

Open the Webform1.aspx page, and look at the URL in your browser, you should see that upon loading that page ASP.NET has now established a session id embedded in your Web browser. ASP.NET will use this unique key to track all of your session variables. Type in a value that you would like to store, then click the Submit Query button. You will see that the submitted value has been stored. Next, follow the hyperlink to the staticpage1.htm file. Although no session information is available here because it is an .htm file, you will see that the embedded session id remains in your browsers URL. Now follow the hyperlink to the Webform2.aspx page. You will see that the session information has been recovered!

In the previous example, you will notice that we set the mode attribute to InProc. This means that the state will be stored in process or in the physical memory of the server it was launched from when the session state was implemented. This means that if the server were to crash, all session information would be lost. This mode is effectively the mode that you operate in under traditional ASP. As we discussed earlier, this provides little in the way of redundancy or failover support needed for highly scalable Web applications.

118

Saturday Afternoon

Out of Process State Management

We will now look at two new methods in ASP.NET that use external state management. This technique stores session values in an external state store instead of the ASP.NET worker process. By storing it out of process, you can make certain that state is stored across worker process restarts (such as when the machine must be restarted) as well as across multiple machines (such as you would commonly face in a Web farm). There are two external state management approaches:

The first method relies on using SQL Server to store state. This option provides you the most scalability and redundancy but requires you to have SQL Server. There is no Oracle support for this approach as of yet!

The second method utilizes an “ASP.NET state store.” This is a dedicated NT Service that can run on any Windows NT or Windows 2000 server.

Session Management with SQL Server

In this method, ASP.NET will utilize a database called ASPState on a selected SQL Server to store session information. Using this method you can choose to set the property Cookieless to either True or False, at your discretion, since where or how the unique session id is stored has no impact on the method used to store the values associated with the session id. The session id stored in the cookie or alternatively munged in the URL will be the unique key used to query the ASPState database and track session variables.

Advantages

The advantages of this method are:

Stores session state out of process, allowing you to run your application across multiple servers.

Supports request-based load balancing.

Provides extensive redundancy, reliability, and uptime when used in conjunction with clustering and hardware or software load balancing.

Ability to support periodic “code rot” purges.

Ability to partition an application across multiple worker processes.

Ability to partition an application across multiple Web farm machines.

Disadvantages

The disadvantages are:

Additional network traffic for database queries.

Maintenance of SQL Server database.

Session 12—Maintaining State in ASP.NET

119

How to make it happen

Note

In order to use the SQL Server session management, you first need to make sure that you have SQL Server installed or available along with the InstallSqlState.sql file that ships with the Premium version of the .NET Framework SDK. You should also have administrative access to SQL Server.

1.You will need to locate the InstallSqlState.sql file that ships with the Premium version of the .NET Framework. This file creates a database for storing state values on a SQL Server Database of your choice. To implement this method, you need to install this script only once on your targeted database. You will need administrative access to SQL Server to execute this script.

2.To run the script, launch a command prompt, Start Programs Accessories Command Prompt.

3.Navigate to the [Drive]\WINNT\Microsoft.NET\Framework\[version] directory, where [Drive] is the installation drive such as C:\ and [version] is the version of the .NET Framework installed.

4.Type OSQL –S localhost –U [Administrator Userid] –P [Password] <InstallSqlState.sql.

5.An illustrative example of a properly formatted command line would be:

OSQL –S localhost -U sa -P < InstallSqlState.sql

6.Press Enter.

To uninstall this database, you can execute the SQL script UninstallSqlState.sql using the same process described in this session.

Note

This will create a database called ASPState on the selected SQL Server instance. We recommend that you restart SQL Server to make sure that the scripts have been applied. Next, we need to update the <system.Web> section of the Web.config file we used earlier in this session.

In order to activate SQL Server State Maintenance set the value of mode=”SQLServer”. Additionally set the sqlConnectionString=”data source=127.0.0.1;user id=sa; password=”, where data source is the IP address or name of your SQL Server; user id is an administrative user id, and of course the password for the administrator. Finally save the Web.config file. The following example provides an example of a properly configured Web.config file to support SQL Server State Maintenance:

<?xml version=”1.0” encoding=”utf-8” ?> <configuration>

<system.Web>

<sessionState

mode=”SQLServer”

sqlConnectionString=”data source=127.0.0.1;user id=sa;password=” stateConnectionString=”tcpip=127.0.0.1:42424”

cookieless=”true”

timeout=”20”

/>

</system.Web>

</configuration>

120

Saturday Afternoon

Now you can run the same series of pages that you built earlier in the session, and you should see that they produce exactly the same results. What really should get you excited is to see what happens when you start and stop the SQL Server database when these pages are running to see how the recovery of session information is executed! Now that should make a few Web farm developers real happy!

Session Management with ASP.NET State Server

A second out of process approach to session state management utilizes an NT service and a file-based dictionary rather than a database to store state. This solution is likely to be used by shops that do not utilize SQL Server as their primary database in a Web farm, possibly using Oracle, or for smaller Web farms that do not yet need the scalability of SQL Server.

The ASP.NET State Server runs externally from worker processes in a dedicated .NET State Server process that runs as a Windows NT service. There is no end-user code allowed to run in the same process, thus eliminating the chance of unstable code breaking the service; additionally, no live object references are maintained.

The ASP.NET State Server stores blobs of binary data, either in memory or on disk. The

.NET worker processes are then able to take advantage of this simple storage service by saving (using .NET serialization services) all objects contained within a client’s Session collection object at the end of each Web request. Whenever the client needs to access the Session collection, the .NET objects will be retrieved as binary streams from the state

server by the appropriate worker process. It is then deserialized into a live instance of the object and placed back into a new Session collection object exposed to the request handler. The information stored in the collection is then accessed via the same methods used for in-process and SQL Server approaches described earlier in the session.

Advantages

The advantages of this method are:

Stores session state out of process, allowing you to run your application across multiple servers.

Supports request-based load balancing.

Provides adequate redundancy, reliability, and uptime when used in conjunction with clustering and hardware or software load balancing.

Ability to support periodic “code rot” purges.

Ability to partition an application across multiple worker processes.

Ability to partition an application across multiple Web farm machines.

Disadvantages

The disadvantages are:

Additional network traffic for data communication.

Managing a new NT Service.