In my first InformIT article in this series, "Techniques for Retaining State Information in Active Server Page Applications", I discussed why the HTTP protocol makes retaining user state information a non-trivial problem for Web applications. I also discussed five techniques that are commonly used to retain state. I suggested that because ASP Sessions require the user's browser to have cookies enabled and have scalability problems, serious application developers should not use ASP Sessions; instead, they should invest some extra coding time to develop their own technique for retaining state on the server.
Implementing your own user state retention technique requires you to solve several problems. First, you need a way to identify each user of your application. Second, you need a place to store state information, either on the client or server. And finally, you need some way of deleting expired state data. In this article, I'll show sample code for a technique I use that solves these problems. This technique can be easily adapted to work with any Web application that needs to retain user state information.
Click here to download the code for this article, which is a modification to the project I developed for my "Develop Scriptless Web Apps Using Visual Basic" InformIT article, so if you haven't read that article, I suggest you do so now. I also assume that you are familiar with using ASP, VBScript, and either Microsoft Internet Information Server (IIS) or Microsoft Personal Web Server (PWS) to develop and debug Web applications. Note that as is common for articles of this type, my sample code isn't as robust as it probably should be, and I make notes where it is a good idea to include additional logic.
The sample code presented in this article solves the user state retention problem by
Generating a unique identifier for each user the first time he or she makes a request to the application
Including this identifier as a URL query string parameter for all remaining requests from the user to the application running on the server
Storing state information in simple comma-separated values (CSV) text files with the name of the file derived from the user's unique identifier
Periodically executing an off-line process to delete expired user state files
My solution also encapsulates in a class module the actual implementation details of how and where the user state information is saved. The purpose of this class is to save and restore state information for a single user. Any piece of information that needs to be saved for each user should be made a property of this class, and the details of saving and restoring the state data should be contained in its methods. Encapsulation allows the implementation details to be modified at a later date, with minimal impact on the rest of the application. For example, instead of storing state information in simple CSV files, it could be changed to save it to a table in a relational database.