asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Maintaining State
By Wayne Berry
Rating: 3.6 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    This Issue

    In this issue, we discuss two built-in states of the Internet Information Server, session and application. We will also continue where we left off with the Nov 08, 1997 - Sharing Cookies Across Domains Issue, and show how to maintain session state across multiple servers in a web farm. Also discussed, will be user state and the use of personalization to maintain user state. Two begin, we need to define state and illustrate it's occurrence in executables and the Internet Information Server.

    State

    State is persistence across a particular scope. An example of state, is the user configuration of an executable such as Microsoft Internet Explorer. Once configured, the executable remains configured even after it is closed and restarted, the configuration is called the executable's state. The first, important thing to note in executable's state, is that after the executable is closed, execution has stopped, the state persists. Secondly, state is not a mystic entity, rather it is a set of saved variables. The configuration of the executable can be reduced to variables that define the state. For example, the location of the home page in Internet Explorer is saved as a string, it is part of the configuration and the state of the browser. Finally, these variables must be saved in a location that persists beyond the program's execution. With windows executables, state is stored in the registry, an .INI file, or a proprietary binary file. Obviously the executable's state adds value since the user does not need to reconfigure his/her favorite settings when reopening the executable.

    Built in to the Internet Information Server is a sense of state. Actually, two types of state are maintained through two different COM objects. There is session state and application state, each accessible from Active Server pages from the Session object and the Application object. Application state has the scope of all pages within the application. The Application object stores variables in RAM that can be accessed from all pages regardless of the user. By definition, the application's state persists even after the Application object is closed. Session state has the scope of the user's session. The Session object stores variables in RAM that can be accessed from all pages of an application for each user. There is only one Application object per application. However in one application, there might be many sessions hence many session objects. By definition, the session's state persists between pages even after the Session object is closed.

    Data Store

    The data store plays a major factor in maintaining state. For example, an executable's state is usually stored in the register, or an .INI file where the executable can easily access the data. However, the user can not easily access the data stored. If you configure Microsoft Internet Explorer on one machine, the state is maintained on that machine however it is not transferred to another machine. Imagine a version of Internet Explorer where the state is maintained on a web server, you open Internet Explorer, it knows who you are by your cookie and retrieves your state. On another machine, you enter in information to identify yourself and it retrieves the same information for your state.

    In comparison, the state of the Session and the Application are maintained in RAM. RAM is a fast data store, by very inconvenient. The inconvenience lies in two circumstances, when maintaining a web farm and when holding important data. Since power outages or a crash of the web server could loose the data stored in the state of the Session and Application objects, important data, such as online monetary transactions, should not be stored in these objects. Session state in particular is tempting to use in a shopping basket situation, but not advised for this reason. Secondly, when running a web farm, a set of machines all running the same site with different IP address and the same domain name, session state is not maintained. The reason for this is that the requests are divided up between multiple machines that do not have access to each other's RAM. Web farms are run when the number of hits exceeds the horsepower of a single machine, or for redundancy. Microsoft, http://www.microsoft.com, runs a web farm with roughly twenty machines.

    XSession is a third party object that maintains state across multiple servers and preserves the user's state. XSession uses the file system as a data store. By writing the files to the hard drive, the inconveniences of the Session object are lost. First of all it maintains a storage location that is unaffected by power outages and can be backed up. Secondly, the file store allows multiple machines to access the same disk location and share the session information. For this reason XSession is an improvement on the built in Session object.

    Microsoft Personalization, or Membership, service is a combination of COM and SQL Server to maintain a customer's state on your server. With the personalization COM object, you can maintain the state of a customer across multiple machines. The reason stems from the fact that the data store is SQL Server. The SQL Server data store can be accessed from multiple machines and the state can be shared across them.

    In summary, the type of data store effects the quality of the state. When considering how your Internet will operate, i.e. web farm or not, take into consideration what product you are using and where it keeps its' data.

    Session Object

    The Session object in Active Server pages maintains the session state of the user. Session is defined as, a single visit by a single user. In other words the scope of the state is length of the visit of the user to the web site.

    The length of a visit, a prerequisite to understanding the Session object, is one of the hardest things to calculate in the web environment. According to the HTTP protocol, the client doesn't send a message to the server when it leaves the web site. On the first visit to the web site the browser makes a request, and for each page and graphic after that a request is made. But, after the final request the browser does not indicate to the server when it has left the page. For this reason the length of the visit can not be calculated. Webtrends and other log file analyzing software usually make a rough estimation by taking the average length of time spent on all pages dividing it in half and assuming that is the length of time spent on the last page. There is a margin of error in this calculation that is acceptable.

    The Session object on the other hand needs to know when the session is done, it faces the same problem as the log analyzing software, there is no way to tell when the user has stopped viewing the site. To over come this problem, Microsoft has put a time-out period in the Session object. Supposedly after the last page request and the time-out period have expired, the session data is cleared from RAM and the session is over. If the browser makes a request before the time out period is completed, the time is reset and the session object begins to expire again. By default the time is 20 minutes. This technique successfully avoids the problem associated with not knowing the session length, however it causes another problem.

    If the user is still viewing the page after the session timeout period has expired, the information stored in the Session object is lost and a new session is started with the next page request. For this reason session objects should not be used with information that you can afford to lose, such as fiscal transactions. The workaround to the problem is to increase the timeout period so that the session never expires while the user is viewing the site, however it is impossible to increase the time to cover all cases. Imagine a user who gets up from his computer on Friday, and returns to work on Monday to finish reading your site. One way to hedge your bets is to use a log analyzing software like WebTrends to find out the average time users spend on the site. Then double this time and use it to configure the session length. For example, if you had an average page view time of eleven minutes, you would want a session timeout of 22 minutes.

    Once you have your timeout correctly configured, you can assign variables to the Session object per user. Unlike SQL Server, and other database data stores, you do not have to allocate room in a table before writing information. This is the reason that the session object is so popular. To write the users email address all you have to do is execute this line of VBScript:

    Example 1

    
    Session("Email")="joeblow@hisserver.com"
    
    
    Notice that we didn't need to create the Session object in order to use it. The Session object is a built-in object within Active Server pages and doesn't need to be instantiated with the Create object method. Other built-in objects are Application, Request, Response, and Server.

    Now that you have written the data, you can retrieve it from the Session object. You can do in this in the same page, or another page of the application as long as the page is requested within the same session. Here is the code for retrieving the data:

    Example 2

    
    strEmail=Session("Email")
    
    
    When the data is not set that corresponds to the name passed, in this case "Email", the Session object returns a null variant. You can test this with the following statement which checks to make sure that the "Email" name is not set before setting it.

    Example 3

    
    If (IsNull(Session("Email"))) Then
    Session("Email")="joeblow@hisserver.com"
    End If
    
    
    Take into consideration that the Session object doesn't just take string data types, it will take any data type that can be represented as a variant. This includes other objects, which might be the most powerful feature of the Session object. This feature allows you to store dictionary objects full of information about the user in the Session, along with any other COM object. The possibilities become endless. For example: on a category page you could run a SQL query to find the list of products, then store the list in a session object. When the user goes to the detail page for a particular product, the list stored in the Session object could be used to generate the next product and previous product links.

    Besides the already mentioned drawbacks, the data store is in RAM, and the time-out period, the Session object can be easily misused. Most of the misuse happens when inappropriate objects are stored within the Session. For example, using the session object to store large objects will consume your RAM at peak traffic. Without careful consideration you can easily design Active Server pages which work in development, but do not scale to a live web site.

    Another misuse of the Session object happens when you try to store ADO Connection objects within a Session object. Some developers open a connection to a database, then store the open connection in the form of an ADO object in the session. This technique also does not scale, and leads to multiple open connection that can't be accessed. You also need to implement a connection handling technique that deals with timed-out connections and a system for closing a connection. Storing connections in a Session object opens a single connection for every user to the sit and with the default time-out period, these connections are held open for a minimal of 20 minutes. If you are going against SQL Server 6.5, the server must use eight kilobytes of RAM for every connection. A better technique for handling connections is to open and close a connection with ever page and turn ODBC connection caching on.

    Sessions only survive within the scope of an application. In other words you can narrow the session's scope by creating other applications within your domain. This technique is only available in IIS 4.0, because only in IIS 4.0 can you create multiple applications. When a user traverses your site, and they cross from one application scope to another, an application object is created for each application scope. Data saved in the Session object within the first application scope, is not available in the second application scope. However, the object from the first scope doesn't go away. Returning to the first scope, within the time-out period, will make the variables available.

    When the user session is started a special subroutine is run from a file called global.asa. The subroutine is called: Session_OnStart. Here is where you do all the initialization of the Session object. There is another subroutine called Session_OnEnd, which is called when the session object times out, or is abandoned. You can do data clean up within this subroutine. When using IIS 4.0, and you have multiple applications, there can be a global.asa with different subroutines in the root of each application. Because each application has a different Session, each session can be initialized and cleared individually.

    The Session object is a powerful tool if used correctly. However, it does have it drawbacks, including using RAM for a data store, and occasional loss of data because of a time-out. In order to use the Session object correctly, you must not hold critical data because of the time-out or loss of power to the machine. You should not store large objects, and never store ADO connections. Session objects can not be used in web farms.

    Application Object

    The Application object in Active Server Pages is an object, which maintains the application's state. The application state exists across all pages of the application and all users within a particular application. With version four of the Internet Information server, you may have multiple applications within a domain and on a server. With IIS 3.0, there is only one application state, and one application, per machine. Unlike the Session object, the application state does not timeout, the application saves the data as long as the application is running. Rebooting the web server, or having an out of process application crash will cause the application to lose its saved values. The Application object has the same drawback that the Session object has, you many not use the application object in a web farm. The reason for this is that the Application object uses RAM as a data store, and another machine’s RAM is not accessible from a remote server.

    The Application object is used much like the Session object. However because multiple users can access the object at the same time you need to lock and unlock the object before writing to it. You can use Example 4 to write the number of request made to the application. Just include the code at the top of every page within the application.

    Example 4

    
    Application.Lock
    Application("Requests")= Application("Requests")+1
    Application.Unlock
    
    
    Like the session object, the application object calls special subroutines within the global.asa. Application_OnStart is called when the application ends Application_OnEnd is called when the application closes. The application object has many uses, however it is not used as much as the Session object.

    XSession Object

    The XSession object is a hybrid of the Session object that allows developers to maintain session state across multiple web farms. The XSession object uses the file system to store the session information instead of RAM like the Session object. As long as the multiple servers that comprise the web farm can all reach the same file location, XSession can share session state between those computers.

    Since XSession saves the session's state to files, server crashes do not lose the state. With IIS 4.0’s ability to automatically restart the out of process web sites, there is a potential for lost data with Microsoft's Session object, not with XSession. The next request to the server will search for the data written to the file using the user's cookie as a key to the file.

    XSession has a different scope than Microsoft's Session object. Not only does it maintain session state, it also maintains the state of the customer. Unlike Microsoft's Session object, returning users, days later, will be able to retrieve their session state, or in other words their user state. The only other way to currently maintain the user's state is with a database and a cookie schema.

    Example 5 uses XSession to save the user's email address.

    Example 5

    
    Set XSession = Server.CreateObject("SMUM.XSession.1")
    XSession("Email")="joeblow@hisserver.com"
    
    
    Notice that it is the same syntax that Microsoft's Session objects uses, however you must create the XSession object in order to use it.

    In Example 6 we use XSession to retrieve the user's email address.

    Example 6

    
    Set XSession = Server.CreateObject("SMUM.XSession.1")
    strEmail=XSession("Email")
    
    
    Like Microsoft's session object, XSession can store any types of variable, including dates, long values, and strings.

    XSession is a powerful COM object that can be used with Active Server Pages to store the user's state without a database. XSession is also flexible in the sense that column and table designs do not have to be created in order to store information.

    Each of the three objects discussed in this article have their own purpose and place. Session objects store the session state, and allows variables to be shared between multiple pages for a particular user. Applications objects store the application state, and allows variables to be shared between pages for all users. XSession stores the user's state, and allows variables to be shared between pages and sessions for a particular user.

    Further Reading

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    ASP Session Manager
    ASP Session Manager works by inserting 2 lines of code at the top of your ASP script and have the session serialize itself to any DBMS. There are three licenses available, ranging from a single binary to an enterprise ISP license with source code.
    [Top]
    SA-Session Pro
    Web farm getting out of control? You need scalability! SA-SessionPro is a simple, yet very powerful means of making your ASP application persistent--share and save information on a per-user, per-application, per-server, or per network basis. SA-Session is like the built in Session object that comes with the IIS Server, except it allows developers more flexibility. It has the ability to store information without expiration and the ability to preserve session state across multiple machines in a web farm.
    [Top]
    SessionFarm
    SessionFarm is an Active Server Pages component that allows you to manage session state on multiple servers in a web-farm. SessionFarm utilizes the built-in IIS Session object which means you don't have to learn new methods and objects. The IIS Session object is stored on either a file-share or a SQL database using optimized stored procedures.

    SessionFarm requires no rewriting of your existing code and works by supplementing the existing IIS Session.

    For code samples, see http://www.groat.com/sessionfarm/implement.asp.

    [Top]
    Other Articles
    Mar 7, 2001 - Are Session Variables Satan's Spawn?
    A seemingly innocent Inquiry has sparked a member of the 15Seconds discussion list to answer with a sermon on the evil nature of Session Variables.
    [Read This Article]  [Top]
    Dec 30, 1999 - Using Hidden FRAMES to Hold Data or Maintain State
    Hidden frames allow users to maintain almost any kind of data, and maintain state easily and reliably. Mark Burnham's article uses a shopping cart scenario to show simple ways to read and write data, and call functions from a hidden frame. Visible frames can be loaded with virtually anything, but these hidden frames will always be there, holding data until it's needed.
    [Read This Article]  [Top]
    Dec 23, 1999 - How to Detect If Cookies Are ON
    Mark Burnham offers a quick and easy way to check if your browser accepts cookies. If it does, then you're clear to use session variables when writing ASP scripts. Just follow the sample code to learn how to copy a form and compare SessionIDs.
    [Read This Article]  [Top]
    Jul 1, 1999 - Avoid the Pitfalls of Sessions with the LookupTable
    Brian Reagan demonstrates how to use the LookupTable object to avoid problems with session objects timing out. Read this in-depth article and learn the tricks of the trade.
    [Read This Article]  [Top]
    Jan 14, 1999 - Easy Application State Securely
    This article by Dmitry Khanine shows how to make your web site 100-percent secure when maintain your application state.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES