the complete webmaster
tutorials reviews reference
ASP
CGI
FrontPage
HTML
Java
JavaScript

Sponsored by El Scripto

Visit the Mortgage Loan Place for Home Loans and also click here to find VA Loans on our site.

Get more website traffic

home / articles / asp

Active Server Pages: Using State To Your Advantage

Introduction

To date, we've talked about the infrastructure of Active Server Pages (ASP) and its potential with respect to developing large-scale, enterprise applications. So far, we've seen the capabilities of the Request and Response objects and briefly talked about other objects intrinsic to the ASP runtime environment. Coverage of this material was undoubtedly lengthy; however, I felt compelled to give you a thorough introduction to the topic preparing you for some of the more powerful features of ASP we would cover in articles to come.

In this article, I’ll explore strategies for managing transient application state using ASP. Often referred to as simply ‘state management’, the concept of maintaining data for a specific user or application over a series of HTTP requests often poses some interesting problems related to web application development.

I’ll introduce a new object in the ASP object model: the Session object. You’ll use the Session object to manage information for individual users of a particular application. In a later installment, we’ll use another object, the Application object to store common information that can be shared between all users of a single ASP application.

I’ll also discuss state management techniques for ensuring that your ASP application scales gracefully in a distributed server environment. Distributed environments may be of special interest given that a single client requesting resources from your site may actually be serviced by a number of independent web servers making it harder to store information on a particular server about a particular client. The concept of load balancing HTTP requests and server distribution may become more important as your transaction requirements increase and you venture into developing enterprise-sized OLTP applications.

The 'State' of HTTP

Applications can be ‘stateless’ or ‘stateful’. HTTP is a ‘stateless’ protocol. We’ll talk more about ‘stateful’ later, but let it suffice to say that HTTP does not attempt to retain information, or state, about the current connection after a request completes. In a previous article, I introduced you to some of the characteristics of HTTP especially the request/response nature of interactions between clients (browsers) and servers.

In that article, we learned that when a browser needs to obtain a resource, it sends the server an HTTP Request message containing various pieces of information telling the server the nature of the request and, most importantly, the resource or document that it needs. When the server receives and processes this request, it generates an HTTP Response message containing, in some form or fashion, the contents of the requested document.

Once this sequence of events completes the connection terminates and the server waits for the next request. This request/response interaction allows a web server to process a large number of distinct requests and effectively service a large number of users without the overhead of maintaining long-lived information about each connection made.

Web Applications and State

We introduce complications into this scenario when information needs to survive or be recorded between several requests. It is not uncommon to encounter the same state management requirements in web applications as we do in conventional client-server applications – it’s just harder to implement at times because the rules are slightly different.

In a typical application, a user ‘logs in’ to the system, performs a variety of functions, then ‘logs out’, effectively completing a ‘session’ with the application. For purposes of this discussion, a ‘session’ is the continuous usage of an application by the same user for a period of time. From a web application perspective, however, the concept of a potentially long-running ‘session’ (a persistent connection) does not exist by default, it must be simulated, in effect giving continuity to a series of independent pages.

ASP Sessions and the Session Object

To implement consistent user sessions on the Web, ASP provides a flexible solution that requires no special programming. The Session object, one of the intrinsic objects supported by ASP, provides the developer with a means of storing and retrieving data as well as performing session-related functions.

ASP automatically creates a Session object when a browser requests a page from an application that does not already have a session. When ASP creates a Session object, the user’s ‘session’ begins. By default, the session lasts for twenty minutes, if no activity occurs within that timeframe, ASP destroys the session. This period can be adjusted by setting the Timeout property of the Session object.

Session Object Properties and Methods

The following table lists the properties and methods of the Session object:

Property Description
SessionID Returns the session identification for this user.
TimeOut The timeout period for the session state for this application, in minutes.
   
Methods Description
Abandon This method destroys a Session object and releases its resources

Storing Information in the Session Object

An interesting feature of the Session object is that it supports a dynamic associative array that can be used to store named instances of data. This data can be simple data types, scalar variables and object references. A script simply assigns a value to a named entry in the array:

Session("User")="Jules"

The preceding example stores the string "Jules" in the Session object with the identifying name "User." Likewise, object references are stored using the VBScript keyword SET:

Set Session("PR") = Server.CreateObject("PR.Calculate")

Value can be retrieved from the Session object by referencing the Session object by name, as in the following:

Welcome <% = Session("User") %>!

Or

<% Response.Write Session("PR").Name %>

Note that before you store an object reference in the Session object, you should know what threading model it uses. Only objects marked as both free- and apartment-threaded can be stored in the Session object without locking the session to a single thread.

How ASP Keeps Track

The Session object maintains these name/value pairs for the lifetime of a user's logical session. For each ASP page requested by a user, the Session object preserves the information in the server’s memory.

To locate this information, ASP uses a unique session identifier to match user requests with the information specific to that user's session. Session identifiers are simply globally unique identifiers (GUIDs) generated by ASP using the Windows API.

Session State and Cookies

ASP uses HTTP cookies to store and maintain Session Ids in the context of the client browser. For example, an ASP application with an established session would include a Set-Cookie header in the HTTP Response such as:

Set-Cookie: ASPSESSIONID=AXXQGHSSWQAJPUYT; path=/MyASPApp

The browser returns this cookie with each request made to the virtual web application directory /MyASPApp, giving ASP the opportunity to find the session-specific data previously stored.

It’s important to note that the Session ID cookie contains no expiration time; therefore, it is only valid as long as the browser remains active.

The Session Object: Limitations

Given our discussion so far, the session object allows a relatively easy method of storing session specific information in the context of an ASP application. However, as you might have already guessed, a potential downside to this approach is that you cannot guarantee that a browser will accept cookies, the primary vehicle for identifying sessions via the Session ID, rendering the Session metaphor completely useless.

Furthermore, in more complex applications, if you are attempting to use a clustering strategy that allows multiple requests to be serviced by a number of different servers, the concept of session state stored on a particular server tends to break down in a hurry.

At this point, it’s probably evident that the Session object has its’ place in ASP application development, but there are definitely some limitations.

Another Method: A Database Table

There are times when the Session object may not be robust enough for your application needs. Although you may still choose to use the Session object for some non-critical pieces of data, your application may benefit from using an external storage mechanism such as relational database server to store state information.

When you think of it, a database server provides a very suitable model for storing an application’s state. For one, the database can reside anywhere on the network and be accessible from any number of servers. Also, database servers today offer, at least, some performance enhancement features, referential integrity and even redundancy. For the most part, utilizing this storage medium to store transient application state is no more complex than any other database application.

The main complication arises when you try to decide how to uniquely identify and store application data and ensure that the data is always associated with the correct user on the network.

Choosing the Right Identity

There are several ways to uniquely identify a client making requests of your web server. At first glance, you might choose to use the client’s IP address because every host on the Internet is assigned a unique IP address.

This strategy tends to weaken when you think of the numerous IP addresses dynamically assigned by Internet Service Providers that probably expire in a couple of hours. Better yet, if the client is connecting via a proxy server, they could be one of a hundred clients masquerading behind the proxy’s single IP address.

A strategy you may choose involves managing the unique identifier yourself, in effect, taking over the management of the session and the unique identifier that identifies its’ data. This probably doesn’t alleviate the need for storing this unique identifier in a client-based cookie, however, using C++ or VB5 and the Windows API, you too can create unique identifiers.

Click here to see an example of how to implement this unique identifier using VB5 and the Windows API.

Self-Managed Sessions

Once identifying the session is no longer a problem, you need to implement the code to persist the session state. You may choose one of several methods:

First, you could write a generic distributed Session object as a COM component that behaved much like the intrinsic Session object provided by ASP. We haven’t covered COM components in this series of articles yet, however, if you are familiar with the concept you probably get the idea of how the underlying database would be managed. A database table for managing this state might look something like this:

Name Type Description
SessionID Character Unique session identifier generated by your algorithm.
PropertyName Character Name of property you wish to store for this session.
Value Character Value of property you wish to store for this session.

Given a Session ID and the desired property name, you could either insert a new value or retrieve an existing value from the table. As long as property names are kept unique and  data storage needs are limited to simple data types, you have essentially created a custom version of the ASP Session object.

On the other hand, if you are interested in only a finite amount of data, your table structure could be much more straightforward. Consider the following, very specialized adaptation of this solution, that stores only limited demographic information for the current client:

Name Type Description
SessionID Character Unique session identifier generated by your algorithm.
Name Character Person Name
Address Character Person Address

What Happens When It's All Over?

If you choose to store state information in an external table, one final complication may be garbage collection. In other words, when a session ‘ends’ what do you do with information previously recorded in the database?

A straightforward way to approach this in the self-managed session model, is to create your own methods of construction and destruction with respect to the individual session.

For example, when you create a session for a user, your application is responsible for the destruction of that session via your custom Session object. This strategy obviously has a couple of holes in that users have a nasty habit of not always logging off.

Yet another strategy might be to ‘age’ the properties and sessions in your session management table and clean them up periodically. Another less-than-perfect, but useable solution if self-managed sessions is your choice.

A Final Approach: HTTP-based State

One last approach might be the simplest, but could also be the least reusable. You could encapsulate the state in the HTTP Request and Response messages.

Although this technique is certainly not new, and is not limited to ASP applications, HTML provides for encapsulating state information through the use of both normal, visible form fields and form fields having the HIDDEN attribute.

The basic concept is that given a known amount of state, you can store name/value pairs in form fields, basically eliminating the need for server-based application state.

Using this technique gives you the ability to use the standard HTML form submission model to create and encapsulate the HTTP Request and the ASP Response object to query property specific information. To complete the model, you have to carry the state received from the HTTP Request forward to the HTTP Response by regenerating the additional hidden fields and their respective values.

An example HTML form using this technique might initially look as follows.

<HTML>
<BODY>
<FORM ACTION="FIRST.ASP" METHOD=POST>
<INPUT TYPE=TEXT NAME="USERID">
<INPUT TYPE=PASSWORD NAME="PASSWORD">
<INPUT TYPE=SUBMIT NAME="MYSUBMIT" VALUE="OK">
</FORM>
</BODY>
</HTML>

The above example is a standard form requesting the user id and password with a submit button that invokes the server script FIRST.ASP. The Submit button ‘packages’ these fields into the HTTP request for transmission to the server.

When returning information to the client, our server side script generates the next data entry form preserving state from previous forms in hidden fields as follows:

<FORM ACTION="NEXT.ASP" METHOD=POST>
<INPUT TYPE=TEXT NAME="STREETADDRESS">
<INPUT TYPE=TEXT NAME="CITY">
<INPUT TYPE=HIDDEN NAME="USERID" VALUE="1234">
<INPUT TYPE=SUBMIT NAME="MYSUBMIT" VALUE="OK">
</FORM>

Notice the usage of both hidden and visible form fields. Using this technique, we preserved the USERID field across HTTP Requests, giving server-side script the ability to re-establish the state for this user based on the contents of USERID along with any other data we may have obtained with additional form fields.

Conclusions

The HTTP request/response interaction model has been instrumental in creating one of the most effective distributed processing platforms of all time: the World Wide Web. HTTP has its limitations and certainly its’ ‘stateless’ nature forces us as software developers to sometimes think in a totally different paradigm spending most of our time dealing with the hassles of storing and retrieving data instead of pursuing the more interesting aspects of our application.

When all is said and done, you have a choice. In this article I’ve attempted to outline a couple of these choices for you at a reasonably high level and offer some potential architectural suggestions for those of you planning large-scale applications.

In summary, remember a couple of things...

For reasonably lightweight, single server applications (and product demos), the ASP Session object provides a simple solution for storing and retrieving transient application state information. If you keep in mind what you’re attempting to store in this object and don’t overuse it, you’ll get by just fine.

For more complex applications, especially those with significant state management requirements and those that must maintain state across multiple servers and multiple applications you may need to investigate some of the alternatives we’ve discussed or formulate your own state management strategy.

As always, I appreciate having you along as my guest and would be even more appreciative of any feedback you may have. See you next time!

Author: Keith Cox
Date: 04/20/98

More articles about Active Server Pages
More articles by Keith Cox
Author Biography

Open software to automate your online business
write for us about us advertise

Copyright 1997, 1998 A Big Lime. All rights reserved.

body>