Specify Application start and end procedures in the Global.asa file.
Using Global.asa File with Applications
Sometimes you will want to create objects that are available to all the users in an application. As with Session variables, you will want to initialize those objects and maybe work with some when an application begins. You may want to initialize an Application variable as well, which you do before the application runs. The Global.asa file also lets you define code to initialize (or finish) use of an application. Recall that ASP looks for the Global.asa file in the root directory of the application.
Implementing an Application Variable
For example, suppose you wanted to track the number of users who are visiting your site at any given time. You'd need to do this in several steps:
Initialize an Application variable in the Application_OnStart procedure (so it is initialized when the first user arrives).
For each new user session started, increment the value in the Application variable.
When each session ends, decrement the value in the Application variable.
Get the value of the Application variable when you need it.
You already know that ASP can detect a session start and end and execute a procedure in the Global.asa file. ASP can also detect both the first use of an application and when it is no longer in use; it will look to the Global.asa file for procedures in both these cases.
Filename: GLOBAL.ASA
<SCRIPT LANGUAGE="VBSCRIPT" RUNAT=Server>
Sub Application_OnStart
Application("aiUserCount") = 0
End Sub
Sub Session_OnStart
Application("aiUserCount") = Application("aiUserCount") +1
End Sub
Sub Session_OnEnd
Application("aiUserCount") = Application("aiUserCount") –1
End Sub
</SCRIPT>
Here is the same code segment with an explanation:
Global.asa File set up Example
Global.asa file is used to configure your application on your web server, it is executed on the Server, thus the parameter RUNAT=SERVER
This signals that the next piece of code will execute only when the application starts. This may be after the web server is turned on or reset, or it may be after a period of inactivity when the application has run its Application_OnEnd procedure.
(We have not defined an Application_OnEnd Subroutine in this Global.asa file)
A numeric variable is initialized to track the number of users currently active in our ASP application.
The Application_OnStart subroutine runs only once whenever the application starts and is then closed.
Executes when the user's session begins
The user count is then incremented and subroutine closed
The user count is then decremented and the subroutine is closed
Executes when the user's session ends
The user count is then decremented and the subroutine is closed
The next lesson describes some other uses for application variables.
Ad ASP.NET Core 3