The following code sample shows how we can use the events in
the Global.asax file to store values in the Application state and then retrieve
them when necessary. The program stores an Application and a Session counter in
the Application state to determine the number of times the application has been
accessed and the number of users currently accessing the application.
Listing 1
using System;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
public class Global : HttpApplication
{
protected void Application_Start(Object sender, EventArgs e)
{
Application["appCtr"] = 0;
Application["noOfUsers"] = 0;
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Application.Lock();
Application["appCtr"] = (int) Application["appCtr"] + 1;
Application.UnLock();
}
protected void Session_Start(Object sender, EventArgs e)
{
Application.Lock();
Application["noOfUsers"] = (int) Application["noOfUsers"] + 1;
Application.UnLock();
}
// Code for other handlers
}
After storing the values in the Application state, they can
be retrieved using the statements given in the code sample below.
Listing 2
Response.Write("This application has been accessed "+Application["appCtr"] + " times");
Response.Write("There are "+ Application["noOfUsers"] + " users accessing this application");