Understanding the Global.asax File


The Global.asax file provides access to events handlers for the HttpApplicationState class, for the HttpSessionState class, and for any HTTP module registered for the application. The file is optional, and you are not required to implement any of the event handlers. The Global.asax file essentially provides a gateway to all HTTP requests received by the application. It provides a centralized location where you can intercept client requests and use that information to modify custom application state information. The Global.asax file generally serves two purposes:

  • Handling events for the Application and Session objects

  • Centralizing application-wide tasks

This section focuses on the role of Global.asax both for state management and for centralizing application-wide tasks.

Table 4-5 summarizes the important Application and Session object event handlers that you can access in the Global.asax file.

Table 4-5: Global.asax Event Handlers

EVENT HANDLER

DESCRIPTION

Application_Start()

Called the first time an HttpApplication class is instanced. The Global.asax file has access to a pool of HttpApplication instances, but this event handler is called only once.

Application_BeginRequest()

Handles the HttpApplication BeginRequest() event. This is called when a new HTTP request is received by the application.

Application_EndRequest()

Handles the HttpApplication EndRequest() event. This is called when an HTTP request has finished processing but before the response has been delivered to the client.

Application_End()

Called when all HttpApplication instances unload. This occurs when the application is restarted, which may occur manually or when the Web.config file changes.

Application_Error()

Called when an unhandled exception is raised anywhere in the application. You can add generic code for managing unhandled exceptions, such as logging the issue and emailing a system administrator.

Session_Start()

Called when a new session is started.

Session_End()

Called when a session is abandoned. This event handler will not be called if the client simply closes their browser. It will be called when the current session is explicitly abandoned .

For example, consider a simple set of counters that track the following information:

  • AllRequests: This tracks the total number of requests received by the application.

  • AllUniqueSessions: This tracks the number of unique sessions created in the application.

  • SalesQueryCounter: This tracks the number of requests for a specific page in the application, namely, ap_SalesQuery.aspx .

Listing 4-2 shows one example of how the Global.asax file manages these counters.

Listing 4-2: Seeing Global.asax in Action
start example
 Public Class Global     Inherits System.Web.HttpApplication     Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)         ' Fires when the application is started         Application("AllRequests") = 0         Application("AllUniqueSessions") = 0         Application("SalesQueryCounter") = 0     End Sub     Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)         ' Fires when the session is started         Application("AllUniqueSessions") += 1     End Sub     Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)         ' Fires at the beginning of each request         Application("AllRequests") += 1         If InStr(Me.Request.Url.ToString, "ap_SalesQuery.aspx") > 0 Then             Application("SalesQueryCounter") += 1         End If     End Sub End Class 
end example
 

These counters are all initialized in the Application_Start() event, which fires the first time the application is instanced. The AllUniqueSessions counter gets incremented in the Session_Start event ( assuming that session state is enabled for the application). Finally, the SalesQueryCounter counter gets incremented in the Application_BeginRequest event, which fires every time the application receives a new request. The code uses the Request object's Url property to determine which page the user has requested .

Managing Unhandled Exceptions with the Application_Error() Event Handler

The Application_Error() event handler is another useful method that is called whenever an unhandled exception occurs anywhere within the application. You can design an application for all foreseeable exceptions, but it is likely that unhandled exceptions will occur, particularly when the application is moved from a development to a production environment. Listing 4-3 shows how you can have unhandled exceptions logged to the application event log, then emailed to the system administrator.

Listing 4-3: Managing Unhandled Exceptions with the Application_Error() Event Handler
start example
 Imports System.Diagnostics Imports System.Web.Mail Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)     ' Step 1: Write an error to the event log     Dim strMessage As String     strMessage = "Url " & Me.Request.UserHostAddress & Me.Request.Path & _         " Error: " & Server.GetLastError.ToString()     Dim Log As New EventLog()     Log.Source = "ASP.NET 1.0.3705.0"     Log.WriteEntry(strMessage, EventLogEntryType.Error)     ' Step 2: Send a mail message to the System Administrator     Dim objMail As Mail.MailMessage = New Mail.MailMessage()     With objMail         .BodyFormat = Mail.MailFormat.Html         .To = "sysadmin@yourcompany.com"         .From = "sysadmin@yourcompany.com"         .Subject = "Exception Report for " & Me.Request.UserHostAddress         .Body = "<html><body><h2>" & Me.Request.UserHostAddress & _             Me.Request.Path & "</h2>" & Me.Server.GetLastError.ToString() & _             "</body></html>"     End With     ' Step 4: Send the Mail message (SMTP must be configured on the Web server)     Dim objSmtpMail As Mail.SmtpMail     objSmtpMail.SmtpServer = "MySMTPServer"     objSmtpMail.Send(objMail)     objSmtpMail = Nothing     objMail = Nothing End Sub 
end example
 

As an added convenience, you can set the <customErrors> element in the Web.config file to automatically redirect remote users to a friendly custom error page. This redirection will occur after the Application_Error() event handler has been called. Local users (in other words, developers who are working on localhost) will continue to see a standard error screen that displays full exception details, including the call stack:

 <customErrors mode="RemoteOnly" defaultRedirect="ap_CustomErrorPage.aspx"/> 

In summary, the Global.asax file serves as a central location for efficiently managing application and session state and as central location for managing application-wide tasks. The Global.asax file plays a key role in developing optimal ASP.NET applications.

Using a Custom Base Class for Global.asax

The Application object is not the only way to store application-wide values. In fact, it may be inefficient to store certain kinds of information this way. For example, consider the counter example from Listing 4-2. The three counters are initialized and incremented within the Global.asax file only, and they are never modified outside of this file. There is no need to use an Application object for storing this information, particularly if you want to keep the counter values private and inaccessible from the rest of the application.

An alternative approach to using the Application object is to create a custom base class for the Global.asax file. This base class inherits from the HttpApplication class, just like the default Global class that sits behind the Global.asax file. The custom base class provides the same members as the default Global.asax file, but even better, you can extend the class with additional members, such as custom properties for tracking counters.

Listing 4-4 illustrates one possible custom base class.

Listing 4-4: Creating a Custom Base Class for the Global.asax File
start example
 Imports System.Diagnostics Public Class apCustomModule     Inherits System.Web.HttpApplication     Private m_Counter As Integer     Public Property MyCounter() As Integer         Get             MyCounter = m_Counter         End Get         Set(ByVal Value As Integer)             m_Counter = Value         End Set     End Property     Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)         ' Fires when the application is started         MyCounter = 0     End Sub     Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)         ' Fires at the beginning of each request         MyCounter = MyCounter + 1     End Sub     Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)         ' Fires when the application ends         Dim Log As New EventLog()         Log.Source = "ASP.NET 1.0.3705.0"         Log.WriteEntry("Number of Application Requests: " & MyCounter, _             EventLogEntryType.Information)     End Sub End Class 
end example
 

You can find this code implemented in the sample application, AspNetChap4A, which accompanies this chapter. Notice that the class inherits from the HttpApplication class and that it implements selected event handlers. The class provides a property called MyCounter , which is equivalent to the AllRequests counter from Listing 4-2. This property value gets incremented in the Application_BeginRequest() event handler ”that is, once for every client request.

The next and final step is to update the @ Application directive in the Global.asax file to inherit from the custom base class instead of from the default Global class:

 <%@ Application Codebehind="Global.asax.vb"      Inherits="MyApp.apCustomModule" %> 

The custom base class resides in memory continuously for as long as the application remains loaded. As a result, the MyCounter property acts like a static variable, such that all application users will share one instance. When the application does unload, the current counter value gets written to the application event log.

One caveat with this approach is that you run the risk of thread blocking issues if ASP.NET fails to manage the user load correctly. ASP.NET does a good job of managing its thread pool and is efficient at managing its pool of HttpApplication instances. You should not encounter problems updating custom properties if they encapsulate simple data types. To be on the safe side, make sure you stress test your Web application and monitor the number of errors the application encounters under heavy load.

In summary, the Global.asax file serves as a central location for efficiently managing application and session state and as a centralized location for managing application-wide tasks. The Global.asax file plays a key role in developing optimal ASP.NET applications.




Performance Tuning and Optimizing ASP. NET Applications
Performance Tuning and Optimizing ASP.NET Applications
ISBN: 1590590724
EAN: 2147483647
Year: 2005
Pages: 91

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net