The Application ObjectThe Application object canstore information for use by ASP.NET code, process requests , and respond to events. Table 4.1 gives the partial interface of the Application object. Table 4.1. The Application Object
Note that an ASP.NET application has a lifetime, just like any other program that might be run on a computer. When the application starts, the OnStart event occurs, and when an application finishes, the OnEnd event occurs. To use these events, you must use the appropriate event handlers to start and end an application. The events make an application's startup and ending state more predictable because developers have explicit methods in which they can insert startup and cleanup code. Application Event HandlersIf you need to write code to be run when the application either starts or finishes, you must put it into an appropriate event handler. In VB, an event handler takes the following form: Sub <ObjectName>_<EventName>(<ParameterList>) ... End Sub Because this sort of code requires a home, place it in a particular file in the root directory of the virtual mapping, called global.asax. As its name suggests, this file contains information, routines, and variables that are globally available to all the pages in the application. So, if you need to do some processing (such as a database lookup) at the beginning or end of an application, you can put some code in the global.asax. file as follows : <%@ Application Codebehind="Global.vb" Inherits="vbtestapp.Global" %> global.vb Imports System Imports System.ComponentModel Imports System.Web Imports System.Web.SessionState Public Class Global Inherits System.Web.HttpApplication Private Sub InitializeComponent() End Sub Sub Application_Start(ByVal Sender As Object, ByVal e As EventArgs) ' Insert code to be executed when the application starts End Sub Sub Session_Start(ByVal Sender As Object, ByVal e As EventArgs) ' Insert code to be executed when the session starts End Sub Sub Application_BeginRequest(ByVal Sender As Object, ByVal e As EventArgs) End Sub Sub Application_EndRequest(ByVal Sender As Object, ByVal e As EventArgs) End Sub Sub Session_End(ByVal Sender As Object, ByVal e As EventArgs) ' Insert code to be executed when the session ends End Sub Sub Application_End(ByVal Sender As Object, ByVal e As EventArgs) ' Insert code to be executed when the application ends End Sub End Class Using Event Handlers to Determine How Long Applications LiveDetermining exactly when an application in ASP.NET starts and ends isn't as obvious as determining the life of a typical program. A typical program running on your computer starts when you ask the operating system to run it, and it ends when you close the window or click an Exit button. The timing is a little different in an ASP.NET application. Because you are creating dynamic and interactive Web content, your application must be based around the client's requests for pages from your server. Because your application is defined as all the documents contained in a single virtual mapping on the server, the application starts the first time any client requests a document from the virtual mapping. Now that you know how an application starts, all you need to consider is how it ends. Web servers are supposed to offer continuous access to information all the time, so generally speaking, you don't want your application to end while users who might want to use it are still out there. Your application stops only when the operating system stops the Web server and the script in the OnEnd event handler runs. If the server crashes for some reason, however, the application still ends but the OnEnd script doesn't run! This can give you some unexpected results if you're counting on code in OnEnd to perform critical tasks . Using Application VariablesWhen creating event handlers for Application_OnStart() and Application_OnEnd() methods, the important question is, "What information are you going to manipulate?" The answer is absolutely anything that you might want to use in your scripts in other parts of the application, which consequently need to be Global or Public. One obvious value is the time that the application started. Storing Global InformationTo store global information in the Application object, you must assign that information to a name. The name becomes the key by which you access that value in the future. You can think of it as being a custom property of the object. To store the time that the application started, you can add code, such as the DateTime variable, into the Application_OnStart() event in the global.asax file, as follows: <SCRIPT LANGUAGE="VB" RUNAT="SERVER"> Sub Application_OnStart Application.Value ("startDateTime") = Now () End sub </SCRIPT> Following is part of a sample page, AppObj.aspx, which uses this stored time value and also creates a global value of its own: <H1>Application Started at: <% response.write(Application("startDateTime")) %> </H1> The <B> Demo </B> value does not really exist until the button below is clicked.<BR> Trying to get its value gives: <% =Application("Demo")%> <P> <FORM ACTION="SETDEMO.ASPX" METHOD="GET"> <INPUT TYPE="HIDDEN" NAME="DEMO" VALUE="5"> <INPUT TYPE="SUBMIT"> </FORM> Note that this example works only if you have the same global.asax file as shown here. Here are the results that the code produces. The time value that's displayed is the one you set in the application's onStart event. Sub Application_OnStart Application( "TimeValue" ) = Date() End Sub This page also makes a second use of the Application object, to access a variable named Foo and retrieve its value: Trying to get its value gives: <%=Application("Demo")%> The first time the AppObj.aspx page is requested after the application starts, Foo will not have been saved, so nothing is returned, as in Figure 4.9. Notice that referencing a nonexistent property doesn't cause an error. It just returns an empty value. This can have an important impact on debugging your application because spelling errors in variable names are not easy to find. When you click the Submit button in the browser window, you reference another ASP.NET file, called SetDemo.aspx. This file contains the following code: <% response.Buffer = TRUE %> <HTML> <HEAD> <TITLE>ASP.NET Demo</TITLE> </HEAD> <BODY> <% Application.Lock Application("Demo") = Request.QueryString("Demo") Application.Unlock Response.Redirect("appobj.aspx") %> </BODY> </HTML> This code takes the information from the <FORM> tag, where the hidden control named Demo has the value 5. This value is stored as a global value in the Application object, and the browser is redirected to the original AppObj.aspx page. This time Demo will be a valid variable containing the value 5. This technique can be valuable when you want to keep track of something and know whether it has already been set. Look at the same page now that Demo has a value: <HTML> <HEAD> <TITLE>ASP.NET Demo Second Page</TITLE> </HEAD> <BODY> <% Response.Write( Application( "Demo" ) ) %> </BODY> </HTML> Using the Lock and Unlock MethodsNotice that the example in the preceding section also uses the Lock and Unlock methods of the Application object. Because the Application object is global to all the clients that might be visiting your site, it's possible that two clients could try to access the same data at the same time. To prevent the value from being corrupted in this situation, you have to lock and unlock access to the object. When the Lock() method is invoked, no other scripts can change the information stored in the Application object until the UnLock() method is called. Using Application Object Collections: Contents and StaticObjectsThe Application object has two collections ” Contents and StaticObjects ”that enable developers to browse through objects and variables that are created at the application scope. The Contents collection contains a group of all the items that have been added to the application through a script command. You can use the Contents collection to obtain a list of items that have been given application scope, or to specify a particular item that is to be the target of an operation. For example: <% Application( "OneK" ) = 1024 %> The Application( "OneK" ) variable sets a global variable OneK and assigns its value to 1024 . You also can create instances of objects that have a global scope. An example might be an instance that sets the contents of an Application object to the browser type: <% Application( "objASPEXT" ) = _ Server.CreateObject( "ASPEXT.BrowserType" ) %> As with other collections, you can iterate them either with VB's For..Each and For..Next statements to examine the contents of each instance, or with the JScript enumerator object. For example: <% Dim Key as string For Each Key in Application Response.Write( "Key Name:" & Key & "<br>" & vbCrLf ) Response.Write( "Key Value:" & CStr( Application( Key ) ) & "<br>" & vbCrLf ) Next %> |