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.

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

But the real code is in the code-behind file named 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["accesses"] = (int) Application["accesses"] + 1;
  protected void Session_Start(Object sender, EventArgs e) {
    Application["users"] = (int) Application["users"] + 1;
  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:

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

Try it