What is the Global.asa?
The Global file is an optional file in which you can specify event scripts and declare objects that have session or application scope. It is not a content file displayed to the users; instead it stores event information and objects used globally by the application. This file must be named Global.asa and must be stored in the root directory of the application. An application can only have one Global.asa file.
Global.asa files can contain only the following:
So what does this mean, and what use is a Global.asa file in my applications?
Well, simply put the Global.asa is the doorway into and out of your Web Applications. With this file you can capture special events happening on your website. These events and a description of each is listed below
| Event Call Name | Description |
|---|---|
| Application_OnStart() | The minute the first user fetches the first file in your Web Application directory an application_onstart event occurs. It will never occur again until the web server stops and then restarts. |
| Session_OnStart() | The code in this event is fired for each user before their first page is fetched and displayed the instant that they access any resources or pages inside your Web Application. |
| Session_OnEnd() |
This event is fired when a session Times Out. This event can allow you to execute cleanup code or code that dumps for example, session data into a database. Session_OnEnd fires when the session ends and not when the user leaves your site or closes their browser. So by default this happens 20 minutes later and the user is long gone! This is often a source of much confusion for beginners, if you want to use this to log when the last request happened on your site you can use the DateAdd() function to get the time of the last request. |
| Application_OnEnd() | This event is fired if the Web Application stops. |
Ok, So what does a global.asa look like?
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
'You can add special event handlers in this file that will get run automatically when
'special Active Server Pages events occur. To create these handlers, just create a
'subroutine with a name from the list below that corresponds to the event you want to
'use. For example, to create an event handler for Session_OnStart, you would put the
'following code into this file (without the comments):
'Sub Session_OnStart
'**Put your code here **
'End Sub
'EventName Description
'Session_OnStart Runs the first time a user runs any page in your application
'Session_OnEnd Runs when a user's session times out or quits your application
'Application_OnStart Runs once when the first page of your application is run for the first time by any user
'Application_OnEnd Runs once when the web server shuts down
</SCRIPT>
That's basically it, but the above global.asa won't actually do anything it won't catch any events because it doesn't have any sub routines declared.
Here is a really easy use for the Global.asa, a hit counter.
We're going to use the global.asa to count the number of hits we get. Though what this is actually going to do is count the number of sessions created, which is more accurate than hits - you can't refresh this page and get another hit.
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_Onstart()
'Set the variable to 0 when the application starts
Application("hits") = 0
End Sub
Sub Session_OnStart()
'Lock the application so we don't get the wrong numbers
'then add one to the application variable "hits" and
'unlock the application again
Application.Lock
Application("hits") = Application("hits") + 1
Application.Unlock
End Sub
</SCRIPT>
There, that doesn't look so complicated does it? All it is doing is adding one to a variable that has Application Scope. To retrieve this variable from anywhere within your Web Application all you have to do is this: -
<%
'Write the number of hits to the page
Response.Write("There have been ")
Response.Write(Application("hits"))
Response.Write(" session starts of this Web Application.")
%>
There have been 1 session starts of this Web Application.
You could expand on this example by getting it to log to a database with a few Server Variables such as the users IP address and when they visited the site.
NOTE: If the server is restarted for whatever reason, your hit counter will be reset. Also to start this counting you'll need to stop and start the web server (So it will fire the Application_Onstart() event).
Another simple use of the global.asa is to track the number of users currently on your website, which adds a nice touch - a very good example of this can be seen at http://www.coveryourasp.com/ (where the examples are in server side JavaScript but the explanations are good enough that you can convert them to VBscript very easily).
Allot of people find the global.asa good for storing variables that change very little but are used allot - such as connection strings for database's like this: -
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_Onstart()
'Set up the application variables
Application("myConnectionString") = "SomeStupidlyLongAndComplicatedString"
End Sub
</SCRIPT>
Tip : Before you put any code in your Global.asa to execute during events, test it first in a regular ".asp" page. If it doesn't run there it certainly isn't going to run in your global.asa
Problems and Gotcha's with the Global.asa

Advanced use of the Global.asa
Above is a nice easy use of the Global.asa utilising Application scope variables, but the global.asa can be used for much more complicated tasks.
Lets imagine we have a website and we want to display a Daily Quote, or image. This would mean going to the website each day and editing the page that stores the daily item - Or would it?
If we use the Global.asa we can capture the first visitor of each day and execute code to change the daily item, thus automating the process.
Before reading down a little bit think about what we might need to catch and check before executing the code.
Had any ideas? Well, lets see if great minds think alike ...
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_Onstart()
'Set up the application variable
Application("DailyDate") = Date()
End Sub
Sub Session_OnStart()
'Check to see if a variable matches today's date and if it
'doesn't then execute DailyEvent()
If Application("DailyDate") <> Date() Then
Call DailyEvent()
End If
End Sub
Sub DailyEvent()
'Here you could connect to a database and collect a random
'quote from a table but we'll just set one manually for now
Application("DailyItem") = ("The Global.asa is Totally Awesome Dude!")
'Now we need to set the variable to today's date so the quote
'isn't changed again today
Application("DailyDate") = Date()
End Sub
</SCRIPT>
If the above code doesn't click straight away don't worry I'm going to explain it all to you now.
When the Web Application is started the Application_OnStart() event is fired and Application("DailyDate") is set to the system date of the web server.
Then whenever a user hits your web site it executes the Session_Onstart() event, if the user hits your site is the first person to hit it that day (After 00:00) then the If statement catches the discrepancy in the compare statement and calls the DailyEvent sub.
When this sub is called it sets the Application("DailyItem") variable to the quote for that day and then we set Application("DailyDate") to the system date of the web server so that the next time a user calls the Session_Onstart() event the quote isn't changed - at least not until the next day.
Scarily Advanced Global.asa
If you have ever programmed in Visual basic you might be familiar with the concept of 'Project References', this is where you can tell a project that it is going to use an external com component, such as ADODB or MS Office components.
In ASP you might be used to including the 'adovbs.inc' reference page on to any page you want to have database access, this can be an irritating thing to have to do - because when you forget to do it can lead to all sorts of troubles. If you use code like below without it it will result in errors.
<%@ Language = VBScript %>
<%
OPTION EXPLICIT
Dim Conn, SQL, RS
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open "SomeConnectionString"
SQL = ("SELECT names FROM tbl_people")
Set RS = Server.CreateObject("ADODB.RecordSet")
RS.Open SQL, Conn, adOpenForwardOnly, adLockReadOnly
'...
RS.Close
Set RS = Nothing
Conn.Close
Set Conn = Nothing
%>
This is because the variables adOpenForward and adLockReadOnly haven't been declared, we could solve this by including the adovbs.inc file on each page that connects to a database, or we can make an Application reference to the ADODB component within the global.asa which makes these variables available to us in any page within the Web Application.
<!--METADATA TYPE="TypeLib" NAME="Microsoft ActiveX DataObjects 2.6 Library" UUID="{00000206-0000-0010-8000-00AA006D2EA4}" VERSION="2.6"-->
<SCRIPT LANGUAGE=VBScript RUNAT=Server>
'Some Global.asa code here
</SCRIPT>
Looks pretty good eh? Well, to find out a little more about including METADATA in a Web Application visit http://www.4guysfromrolla.com/ where there is an article covering the matter.
By looking at the above I'm sure you can see the possibilities are practically endless for the global.asa - play around with it it can be very rewarding.
The official Microsoft Global.asa pages.
|
If you have any comments, complaints or compliments about this article then please contact me I'd love to hear what you have to say.
Who is the author? |
|