Home   Cover Cover Cover Cover
 

Application Events (Global.asax)


From Section 6.8 of the book

This example demonstrates the handling of application events. For every page hit as well as for every new user session it increments a specific counter and displays them on a web page.

Application events are handled in the file Global.asax.

/book/samples/Global.asax
<%@ Application Inherits="Global" Src="Global.asax.cs" %>

But the real code is in the code-behind file named Global.asax.cs.

/book/samples/Global.asax.cs
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["accesses"] = 0;
    Application["users"] = 0;
  }
  protected void Application_BeginRequest(Object sender, EventArgs e) {
    Application.Lock();
    Application["accesses"] = (int) Application["accesses"] + 1;
    Application.UnLock(); 
  }
  protected void Session_Start(Object sender, EventArgs e) {
    Application.Lock();
    Application["users"] = (int) Application["users"] + 1;
    Application.UnLock(); 
  }
  protected void Session_End(Object sender, EventArgs e) {}
  protected void Application_EndRequest(Object sender, EventArgs e) {}
  protected void Application_End(Object sender, EventArgs e) {}  
}

Finally we need a page on which the counter values are displayed:

Statistics.aspx
<%@ Page Language="C#"%>
<html>
    <head> <title>ASPX Page Statistics</title> </head>
  <body>
    <h1>Statistics</h1>
    Page Hits: <% Response.Write(Application["accesses"]); %><br>
    User Sessions: <% Response.Write(Application["users"]); %>
  </body>
</html>

Try it

   http://dotnet.jku.at/book/samples/6/Statistics.aspx