Monday, March 22, 2010

Events in Global.asa with asp

In Global.asa you can tell the application and session objects what to do when the application/session starts and what to do when the application/session ends. The code for this is placed in event handlers. The Global.asa file can contain four types of events: Application_OnStart - Occurs when the FIRST user calls the first page in an ASP application. This event occurs after the Web server is restarted or after the Global.asa file is edited. The "Session_OnStart" event occurs immediately after this event. Session_OnStart - This event occurs EVERY time a NEW user requests his or her first page in the ASP application. Session_OnEnd - This event occurs EVERY time a user ends a session. A user-session ends after a page has not been requested by the user for a specified time (by default this is 20 minutes). Application_OnEnd - This event occurs after the LAST user has ended the session. Typically, this event occurs when a Web server stops. This procedure is used to clean up settings after the Application stops, like delete records or write information to text files. A Global.asa file could look something like this: Note: Because we cannot use the ASP script delimiters (<% and %>) to insert scripts in the Global.asa file, we put subroutines inside an HTML Global.asa can also be used to control page access. The example below shows how to redirect every new visitor to another page, in this case to a page called "newpage.asp": And you can include functions in the Global.asa file. In the example below the Application_OnStart subroutine occurs when the Web server starts. Then the Application_OnStart subroutine calls another subroutine named "getcustomers". The "getcustomers" subroutine opens a database and retrieves a record set from the "customers" table. The record set is assigned to an array, where it can be accessed from any ASP page without querying the database: ________________________________________ Global.asa Example In this example we will create a Global.asa file that counts the number of current visitors. • The Application_OnStart sets the Application variable "visitors" to 0 when the server starts • The Session_OnStart subroutine adds one to the variable "visitors" every time a new visitor arrives • The Session_OnEnd subroutine subtracts one from "visitors" each time this subroutine is triggered The Global.asa file: To display the number of current visitors in an ASP file:

There are <%response.write(Application("visitors"))%> online now!