Tuesday 10 January 2012

Global.asax File in ASP.NET

Use of Global.asax File in ASP.NET Application


What is the use of Global.asax File in ASP.NET Application ?
1-The Global.asax file is an optional file and can be stored
in root directory.
2-In Global.asax file we can declare global variables like for example the variables used in master pages because same variables can be used for different pages right.
3-The Global.asax file is used to handle application-level and session-level events.
If a user requests the Global.asax file, the request is rejected. External users cannot view the file.
while adding this Global.asax file to our application bydefault it contains five methods,
Those methods are:
1.Application_Start.
2.Application_End.
3.Session_Start.
4.Session_End.
5.Application_Error.
4-The Global.asax file, sometimes called theASP.NET application file.
·  Session_Start: Fired when a new user visits the application Website.
·  Session_End: Fired when a user's session times out, ends, or theyleave the application Web site.
·  Application_Start: Fired when the first instance of theHttpApplication class is created. It allows you to create objectsthat are accessible by all HttpApplication instances.
·  Application_End: Fired when the last instance of an HttpApplicationclass is destroyed. It's fired only once during an application'slifetime.
·  Application_Error: Fired when an unhandled exception is encounteredwithin the application.
theApplication_Start event populates an application variable, whileSession_Start populates a session variable. The Application_Errorevent displays a simple message stating an error has occurred.
 void Application_Start(object sender, EventArgs e)
    {
        // type one
        Application["ActiveUsers"] = 0;

        //type two
        System.Data.DataSet ds = new System.Data.DataSet();
        ds.ReadXml(@"D:\..............\xmlfiles\tesdata.xml");
        Application["ds"] = ds;

    
    }


////////////////
void Session_Start(object sender, EventArgs e)
    {
        
        Session.Timeout = 20;
        Application.Lock();
        Application["ActiveUsers"] = System.Convert.ToInt32(Application["ActiveUsers"]) + 1;
        Application.UnLock();
  

    }

///////////
  void Session_End(object sender, EventArgs e)
    {
       
        Application.Lock();
        Application["ActiveUsers"] = System.Convert.ToInt32(Application["ActiveUsers"]) - 1;
        Application.UnLock();
      
    }

void Application_Error(object sender, EventArgs e)    {
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error in: " + Request.Url.ToString() +
                          ". Error Message:" + objErr.Message.ToString();   }

No comments:

Post a Comment