Saving Application Variables Across Web RestartsBy Daniel Cooper
A while ago I had a problem with a site that I was working on. One of the requirements called for a featured product to appear in the footer of the site, which would be changed monthly by the client through a back-end interface.
Usually when one has to dynamic information for a site a database is the answer. In this case I thought "This is stupid. I'm not going to do a database call to retrieve a single value and I'm not going to have an orphan table in the database to only hold that value!"
The obvious solution is to use an application variable. After all, itís global, can be set easily and have little overhead. The problem is that the webserver gets rebooted every week, meaning that any settings in the application variables would be lost. My problem was: "How do I make application wide values persistent?"
What I did was write two functions. One writes key/value pairs to a text file in a format that the second
function can read back. I set up the site so that when the site's operator set a value, it was written both
to the text file and to an application variable. Then when the application restarts, the
file contains code to initialize those variables to the previous values set. Note that this approach will only
persist textual application variables since there is no way to represent a binary object through a text file.
So the code to record application variable values looks a little like this:
And in the
Application_OnStart event in
Global.asa we have a line like:
So once you set a value in both an application variable and in the file you can access it throughout the site with little overhead and the confidence of knowing that if your web application is restarted the value will persist.
Here's how its done:
recordToFile()- writes a key/value pair to a text file you specify, I use
data.txtbut it can be any filename. It creates the file if it doesnít already exist and will create a key/value pair or set the value if it exists.
readFromFile()- opens your data file and retrieves the value for a given key, or null if it canít find it.
Following is the code to
recordToFile. In Part 2 we'll look
at the code for
readFromFile and dissect both functions.