Reading appSettings from Web.config into Classic ASP

I’ve done far too much work in my career on Classic ASP. Many times, sites that were originally written in Classic ASP were to be ported to ASP.Net, and often the transition between the two happened over time, with both technologies living together in the same web site. This poses many challenges, but one is easy to resolve: global application settings.

In ASP.Net, it is common to use the appSettings section of the Web.config file to store global application values. In Classic ASP, it is common to use the Application() object to store these values, and to set these values in the global.asa file.

If we want to share these values so they do not exist in both places, we can create Application object values based on appSettings in the Web.config file.

First, let’s imagine this is our global.asa file:

Sub Application_OnStart
	Application("value1") = "hello"
	Application("value2") = "goodbye"
End Sub

And let’s imagine this is the appSettings section of our Web.config file:

<appSettings>
	<add key="value1" value="hello" />
	<add key="value2" value="goodbye" />
</appSettings>

Same values, but they exist in two places. Fortunately, the Web.config file is an XML file, and Classic ASP can read XML files. Replace your global.asa code with this:

Sub Application_OnStart
	Dim xmlDoc, xmlappSettings, xmladd
	Set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
	Set xmlappSettings = Server.CreateObject("Microsoft.XMLDOM")
	Set xmladd = Server.CreateObject("Microsoft.XMLDOM")
	xmlDoc.async = false
	xmlDoc.load(Server.MapPath("Web.config"))
	Set xmlappSettings = xmldoc.GetElementsByTagName("appSettings").Item(0) 
	Set xmladd = xmlappSettings.GetElementsByTagName("add")
	For Each addItem In xmladd
		Application(addItem.getAttribute("key")) = addItem.getAttribute("value")
	Next
	Set xmladd = Nothing
	Set xmlappSettings = Nothing
	Set xmlDoc = Nothing
End Sub

This code will read your Web.config and create corresponding Application() object items with the same key/value. Going forward, you can save your configuration entries into a Web.config file (and use config file transformations).

Keep in mind that the global.asa’s Application_OnStart only runs when the application is first started, so changes to the Web.config may not get picked up until you restart your web application.

Classic ASP may have its limitations, but creative solutions like this can solve some of them.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.