ASP.NET State Management


Web page requests are by default independent of each other. If I request page B from a server, the contents of page B don’t know whether I have or haven’t viewed page A a few minutes ago. This arrangement works well for simple read-only requests, such as the movie theater example I discussed in the opening paragraph of this chapter. It’s easy to write a server that does this because you don’t have to store any data from one page request to another.

Internet page requests from a single user didn’t originally know about each other. Sometimes this is OK.

As Web interactions get more sophisticated, however, this design no longer meets your users’ needs. What I did on page A does affect the content that page B should show. For example, I book a lot of air travel directly on airline Web sites because they offer extra frequent flyer miles. It’s not acceptable to me to search for an outgoing flight, write it down on paper, search for a return flight, write it down as well, and then manually type both of these flight numbers into yet another page for purchasing my ticket. I want the airline’s site to automatically remember my outgoing flight selection while I choose a return flight and then remember both of these while I buy the ticket.

Then again, as Web interactions get richer, sometimes it isn’t.

Remembering data from one form to another was never a problem for a desktop application, which targeted a single user. The programmer could simply store input data in the program’s internal memory without worrying about which user it belonged to, since only one person used the program at a time. But keeping track of a user’s actions over multiple pages is much more difficult in a Web application, used by (you hope) many different people simultaneously. A Web programmer needs to keep my data separate from all the other users’ so that their flights don’t get mixed with mine (unless they’re headed to Hawaii in February, in which case, hooray!). We call this managing session state, and the Web programmer needs some efficient, easy- to-program way of doing it.

A Web programmer often must maintain separate data for many users simultaneously.

Original ASP provided a simple mechanism for managing session state, which ASP.NET supports and extends. Every time a new user accesses an .ASPX page, ASP.NET creates an internal object called a Session. This object is an indexed collection of data living on the server and tied to a particular active user. You can access items in the collection by means of a numerical index or a string name that you specify. The Session object can hold any number of items for each user, but since they all use server memory, I advise you to limit the amount of data you store in session state to the minimum necessary.

ASP.NET provides a set of data tied to a specific user. Called a Session, programmers can use this object to store data for a specific user.

The Session object automatically remembers (placing a unique ID in a browser cookie or appending it to the URL) which user the data refers to, so the programmer doesn’t have to write code to do that. For example, when I submit a form selecting a flight, the .ASPX page programmer can store that flight’s information in the Session object. When I request the page to buy my ticket, the programmer reads the flight from my Session object. The .ASPX run time automatically knows who the user is (me), so the programmer’s code automatically fetches my flights and not someone else’s, as shown in Figure 3-11.

click to expand
Figure 3-11: Managing session state.

This feature is easy for programmers to use, and hence quite popular. Each .ASPX page contains a property named Session that provides access to the session object for the current user. You place items in this object using an integer index or a string key, and retrieve them the same way. If you attempt to fetch an item that doesn’t exist in the session object, you’ll get a null object reference in return. A sample of the code that does this is shown in Listing 3-6. You will also find this sample on this book’s Web site. The pages will look like Figure 3-12.

ASP.NET provides a simple API for setting and getting session state variables.

Listing 3-6: Code for session state management.

start example
 ‘ Code that stores data in session state. Protected Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click ’ Store current text string in session state. Session("DemoString") = TextBox1().Text ’ Redirect user to page for viewing state. Response().Redirect("WebForm2.aspx") End Sub ‘ Fetch designated string from session state object ’ Display to user in label Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim str As String str = Session("DemoString") If (Not str Is Nothing) Then Label2.Text = str Else Label2.Text = ("(the item ""DemoString"" does not exist " & _  "in the session collection)") End If End Sub
end example

click to expand
Figure 3-12: Session state management sample application.

Obviously, if a server were to maintain a permanent session for every user that ever viewed even one page on it, you’d run out of memory very quickly. The session mechanism is designed to maintain state only for active users—those who are currently performing tasks that require the server to maintain state for them. ASP.NET automatically deletes a user’s Session object, dumping its contents, after it has been idle for a configurable timeout interval. This interval, in minutes, is set in the <sessionstate> section of the web.config file, shown in Listing 3-7. The default is 20 minutes. You can also dump the session yourself by calling the method Session.Abandon.

ASP.NET automatically deletes sessions after a configurable timeout interval.

Listing 3-7: Session state management entries in the web.config file.

start example
<sessionState mode="inproc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false"  timeout="2"  />
end example

While the session mechanism in original ASP was easy to use, it had a number of drawbacks that hampered its expansion to large-scale systems. First, it stored session state in the worker processes that actually ran page scripts and called code living in programmer-written custom objects. A badly behaved object could and often did crash this process, thereby killing the session state of every user it was currently serving, not just the one whose call caused the crash. ASP.NET fixes this problem by providing the ability to store session state in a separate process, one that runs as a system service (see Figure 3-13), so badly behaved user code can’t kill it. This means that worker processes can come and go without losing their session state. It slows down the access to the session state somewhat, as applications now need to cross process boundaries to get to their session state, but most developers figure that’s worth it for reliability. To turn this feature on, set the mode attribute in the web.config file to stateserver and ensure that the state server process is running on the server machine.

Session state can be stored in a separate process for robustness.

click to expand
Figure 3-13: ASP.NET session state process running as a system service.

Original ASP always stored session state on the server machine on which it was created. This architecture didn’t scale well to a Web farm in which every request is potentially handled by a different server. ASP.NET allows each application to specify the machine on which it wants its session state to be stored. You do this by setting the stateConnectionString attribute in the web.config file. In this way, any machine that handles a subsequent call can access the session state stored by a previous call handled by a different machine. Obviously, you now incur the overhead of another network round- trip, so maybe you’d rather set up your load balancer to route subsequent requests to the same machine. You can swap out that machine by simply changing its name in the configuration files of all the clients.

Session state can be easily stored on a different machine.

You can also store session state in SQL Server for better management of large collections. You do this by setting the mode attribute to sqlserver and providing a SQL connection string in the sqlConnectionString attribute. The current setup scripts create a temporary database for holding session state. This provides fast access because the data isn’t written to the slow iron disk, but it also means that the session state won’t survive a crash. If you want that durability and don’t mind paying the performance penalty for it, you can change the database attributes yourself to use a permanent table.

You can also store session state in a SQL Server database.

ASP.NET also helps you manage application state, where an application represents a top-level IIS virtual directory and all of its subdirectories. Application-level state is stuff that changes from time to time, so you don’t want to hard code it, but it applies to all users of the application and isn’t tied to an individual user. An example of application state might be the current unadvertised special offer that every page would display. Each application contains one state object named Application, similar in use to the Session object, except that all accesses of the Application object operate on the same data regardless of the user on the other end.

ASP.NET also provides another state collection for data at an application level.

start sidebar
Tips from the Trenches

My customers report that they can get a significant performance boost in heavily loaded systems by turning off session state for pages that don’t need it, by adding the attribute EnableSessionState="false” to the @page directive in the raw .ASPX file.

end sidebar




Introducing Microsoft. NET
Introducing Microsoft .NET (Pro-Developer)
ISBN: 0735619182
EAN: 2147483647
Year: 2003
Pages: 110

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