The ASP Emporium
Free Active Server Applications and Examples by Bill Gearhart
Online since Friday January 7, 2000

 home > code > tutorials > Accessing the 8 built-in Events of ASP

enter a phrase to search: (advanced search)


 h o m e 

 w h a t 's  n e w 

 a l l   c o d e 
  .net:
    • Fundamentals
    • C# Classes
  classic asp:
    • Code Library
    • ASP Apps
  general:
    • Tutorials
    • SQL

 d o w n l o a d s 

 u s e r   f o r u m s 

 l i n k s 

 s e a r c h 

 s u p p o r t 


Accessing the 8 built-in Events of ASP

A lot of VBScript programmers have little experience with events as there are not a whole lot of them available in the ASP environment. This tutorial will show a VBScript programmer how to access all 8 events made available by ASP.

So what's an event? An event is a procedure that is called when certain criteria has been met or only at a specified time. A programmer cannot trigger an event directly using ASP or VBScript but can plan for the event and schedule code to execute during that specific event by including special procedure blocks into their run-time code.

As I mentioned above, there are 8 events that you can plan for in your ASP application. They are all listed below and fall into three distinct categories

EVENTCATEGORY
Application_OnStartglobal
Application_OnEndglobal
Session_OnStartglobal
Session_OnEndglobal
Class_Initializeclass
Class_Terminateclass
OnTransactionCommittransactional
OnTransactionAborttransactional

Global Events

The first four events should look relatively familiar, they are all found in the global.asa file. Since those events can only occur at the start and end of either a session or application's scope, they can only be accessed through the global.asa.

Class Events

The next two events are class events. These events are triggered whenever a VBScript class is set and destroyed by a programmer invoking an instance of the class.

Transactional Events

The final two events belong to the ObjectContext object (the least used of the 6 built in ASP objects). These events can only be used in any page containing an @ Transaction directive. These events are triggered by Microsoft Transaction Server.

ASP Scope/Code Execution Chart

        Code Executes                                             Code Executes
        Less Frequently                                         More Frequently
        <-----+--------------+---------------+--------------+-------------+--->     

SCOPE:{  Application  }{  Session  }     {  Page  }    {  Class  } {  Procedure  }

                                                                   +-- sub1
                                                                   +-- func1
                                                      +-- class1 --+-- func2
                                       +- index.asp --+            +-- sub2
                      +-- visitor 1 ---+              |            +-- sub3
                      |                +- file.asp    +-- class2 -+-- ...
                      +-- visitor 2 -+                            +-- ...
    http://site.com --+              +--- index.asp --...
                      +-- visitor 3 ----- index.asp --...
                      |               +-- file.asp --...
                      +-- visitor 4 --+-- file2.asp --...
                                      |
                                      +-- index.asp --...

SCOPE:{  Application  }{  Session  }     {  Page  }    {  Class  } {  Procedure  }
                 \         /                  |             |
                  \       /                   |             |
                   \     /                    |             |
                    \   /                     |             |
              Global events execute      Transactional      +-- Class events
              at these levels            events execute         execute at
                                         at this level          this level

Global Events

ASP will look for global events only in the global.asa file of a web site. By the way, ASP considers the entire website to be one gigantic application. Therefore, it is best to only have one global.asa file and it should always be in the root directory of the site. Global events can have one of two scopes: Application and Session. Session level events will execute with much more frequency than application level events. These events can be utilized via the global.asa file. A simple global.asa file is below:

<SCRIPT LANGUAGE=VBScript RUNAT=Server>
Sub Application_OnStart()
	'This procedure will run automatically
	'when the web-server turns on.

	'Whenever the server restarts or if 
	'someone types IISRESET into the 
	'command prompt, this procedure will
	'run.

	'Use this procedure to fire up global
	'application variables or things you
	'will only need to run once...

	'You can only use the "Application" or
	'"Server" ASP objects in Application_OnStart

	'There is no need to use Application.Lock
	'or Application.Unlock in this sub as there
	'can not be anyone actively using the variables
	'while this sub is being triggered - it's
	'impossible.

	'This procedure executes before the 
	'very first Session_OnStart event and
	'never again until the server is restarted
	'for whatever reason.

	'This event works well for initializing
	'Application variables.
End Sub

Sub Application_OnEnd()
	'This procedure will run automatically
	'when the web-server is stopped or shut
	'down.

	'You probably have a 50/50 chance
	'of getting this procedure to fire up
	'if the server is crashing....

	'You can only use the "Application" or
	'"Server" ASP objects in Application_OnEnd
	'and you CANNOT use the "Server.MapPath" method

	'I usually put a little logging app in
	'Application_OnEnd so I can have a record
	'of when the server was last restarted.
End Sub

Sub Session_OnStart()
	'This procedure will run automatically
	'when a new user enters the site for the
	'first time since their last session (or
	'no session).

	'Session_OnStart fires up only one time
	'per session meaning if you view 200 pages
	'on this site in one sitting, or just 2 pages,
	'this routine will have only ran one time
	'for you - as soon as you entered the site...

	'You can use any of the built-in ASP objects 
	'in Session_OnStart.

	'Session_OnStart occurs immediately after IIS
	'creates a session for any given user.

	'Any user not accepting cookies will trigger
	'this event each time they request a page
	'on your site, basically defeating the point
	'of this event...

	'This is the most versatile of the global
	'events because you can use all of ASP's
	'built in objects. You can do anything
	'here that can be done in a regular ASP page.
End Sub

Sub Session_OnEnd()
	'This procedure will run automatically when
	'a user's session ends or times out.

	'You can only use the "Application",
	'"Server" or "Session" ASP objects in Session_OnEnd
	'and you CANNOT use the "Server.MapPath" method

	'This procedure is immediately executed if you call
	'the "Session.Abandon" method in code.

	'One of the best uses of this event is to
	'clear out a user's shopping cart after they
	'have already left, using a stored procedure.

	'A user's SessionID is still remembered when
	'this event is triggered. SessionID is forgotten
	'immediately after this event executes.
End Sub
</SCRIPT>

It is important to remember that all events (global or otherwise) must be Sub procedures and not Functions. Most events are Private (not Public) but using the Private statement with global.asa events will cause them to not execute. It also speeds up code execution if you do not include empty event procedures. Don't define the event unless you need to use it. In my little example above, I would be better off with empty script tags because I didn't do anything in any of the events.

Global events need to be error-proofed. You will need to put error handling into any of the events you use in the global.asa. You should always test your global.asa code first in a normal ASP page to make sure that it successfully executes without errors before loading it into the proper event inside the global.asa.

One last thing about Global events: They don't execute until someone hits an ASP page within your site (application). Meaning, if you have a website with 3 pages and all of them are html files, some of the events in your global.asa file may not be triggered...

Class Events

Personally, these events are my favorites... The class events are triggered when a developer sets or releases a class from memory. A VBScript class is the only way to access these procedures that are triggered by class events.

A simple VBScript class might look like this:

<%
Class TestClass
	Private Sub Class_Initialize()
		'This event fires up when someone
		'runs a statement like:
		'Set a = New TestClass

		'Class_Initialize is a great place
		'to setup defaults for your properties
		'or to do any processing work that
		'is required before any properties
		'or methods can be called.
	End Sub

	Private Sub Class_Terminate()
		'This event executes when someone
		'runs a statement like:
		'Set a = Nothing

		'When the class is freed from memory,
		'this event will be triggered.

		'Class_Terminate is a great place to
		'clean up any class-scope object references
		'or other variables or processes that may
		'be taking up valuable memory and were
		'called during the class's lifetime.
	End Sub
End Class
%>

Notice in the above code that none of the procedures reference each other and there are no public properties or methods. Yet both of those procedures will run, assuming we use proper VBScript coding conventions...

<%
Dim a

Set a = New TestClass      '<--- when this line is executed, so
                           '     is the Class_Initialize event

Set a = Nothing            '<--- when this line is executed, so
                           '     is the Class_Terminate event
%>

Using this logic it is possible to create a class that exports no properties or methods, yet still performs a task. Check out this sample code:

<%
Class Login
	Private Sub Class_Initialize()
		If Request.Cookies("logged_in") = False Then
			response.redirect("./login.asp")
		End If
	End Sub
End Class

Dim a

Set a = New Login       '<-- after this line is executed, the
                        '    class will determine if the user
                        '    has logged in automatically without
                        '    requiring a programmer to call a
                        '    public property or method.
Set a = Nothing
%>

Transactional Events

Transactional events are raised by Microsoft Transaction Server. Transactions are usually implemented in COM objects. A good example of a Transaction:

In an ecommerce system where someone enters a credit card for processing. The first step is to verify the card number via the CCVerification Object (plug) on the server. The second step is to take the verified number and send it to a credit card processor. The final step is parsing the results sent back from the processing service or credit card co. If any one of the three steps fail, the transaction as a whole fails. If the card number doesn't verify, the transaction fails. If the credit card processor cannot be reached or if the card is bad for some reason, the transaction fails. The transaction can only succeed if all three steps are completed successfully.

You can access Microsoft Transaction Server type functionality in ASP by using the @ Transaction directive. This indicates to ASP and MTS that the ASP page is considered to be a transaction and that opens the doors to the last two events, OnTransactionCommit and OnTransactionAbort.

Consider this sample ASP page:

<% @ Language = VBScript Transaction = Required %>
<%
Sub OnTransactionCommit()
	'This event fires when a transactional
	'script calls the "SetComplete" method of ASP's
	'built in "ObjectContext" object.

	Response.Write("Your credit card was processed successfully!")
End Sub

Sub OnTransactionAbort()
	'This event fires when any part of a transaction
	'script calls the "SetAbort" method of ASP's
	'built in "ObjectContext" object.

	Response.Write( "Your credit card has not been processed. " & _
			"This sale was terminated.")
	Response.End
End Sub


Dim a

 'step1: verify card
 '-------------------
Set a = New CCVerification
a.CardType = MasterCard
a.CardNumber = "1234-3456-4567-6789"
a.CardExpirationDate = "08/2005"
 'if card doesn't verify, the
 'transaction fails...
If a.VerifyCard <> 0 Then ObjectContext.SetAbort
Set a = Nothing

 'step2/3: send card for processing, retrieve results
 '-------------------
Set a = CreateObject("myCCproc.myCCCompany")
 'this method of the credit card company's
 'processing component also uses MTS. If
 'this object calls .SetAbort then our
 'OnTransactionAbort event will run.
if a.processcard("1234-3456-4567-6789") <> 0 Then _
	ObjectContext.SetAbort
set a = Nothing


 'if the script makes it to here without the "SetAbort"
 'method being called, the transaction will be committed
 'and the OnTransactionCommit event will be run. You are
 'not required to call SetComplete to complete a transaction.
%>

And that's it. The ASP Events are easy enough to use, if you know how to access them. And it never hurts to know why they run and what makes them run.