Initializing Web Applications Using Global.asax

for RuBoard

ASP.old provided a file, global.asa, that provided functionality specific to the ASP application and session. You would typically put initialization code in global.asa, which provided a set of event-handling procedures for this purpose.

ASP.NET provides a similar functionality in the file Global.asax. Four categories of entries can appear in a Global.asax file:

  • Application directives

  • Code declaration blocks

  • Server-side object tags

  • Server-side includes

Each of these four categories of entries is discussed in more detail in the next few sections.

Note that when you make a change to Global.asax, as with all ASP.NET files, the binary representation of the script will be automatically recompiled. This isn't a big deal in the case of most scripts, but in the case of Global.asax, making a change and recompiling has the potentially troublesome side effect of wiping out all existing sessions (including any data stored in session variables ). Be aware of this when making changes to Global.asax on a production system; as with any major change to a production site, you may want to use Windows Scheduler to upload the updated version of the file to the production server at a time when traffic on your site is at its lowest , such as the middle of the night or on a weekend . Also, storing session data out-of-process or in SQL Server will prevent this problem from happening.

Note, too, that the code in Global.asax can't be run directly; nothing happens when a user navigates to Global.asax using a browser, for example. This prevents users from viewing or running the code contained in this file.

Application Directives in Global.asax

An application directive is a line of code that instructs ASP.NET to take some special action regarding the execution of the page.

Three application directives are supported in Global.asax:

  • @Application , which allows you to specify an inheritance relationship between the application object and another object

  • @Assembly , which links an assembly to the application

  • @Import , which imports a namespace

You've seen examples of @Import directives in virtually every code example in this book so far, so we won't go into them again here.

Using the @Application Directive in Global.asax

The @Application directive supports two attributes: a class name and a description string.

 <%@ Application inherits="MyComp.MyApp" [sr]                 description="My Custom Application %> 

You use the @Application directive in situations where you want to create a custom Application object that inherits from another object.

Note that the options available in the @Application directive in Global.asax are different from the attributes of the @Application directive that are legal in normal ASPX pages.

Using the @Assembly Directive in Global.asax

The @Assembly directive represents a reference to an external assembly (a component) that is not contained in the application's \bin directory. The advantage of referencing an assembly is that you get the performance and type-safety benefits of early binding, as well as IntelliSense when working with the assembly's objects in the Visual Studio development environment.

 <%@ Assembly Name="PrattleFreeApp.Customer" %> 

ASP.NET assemblies are typically contained in a \bin subdirectory under the application directory. Such assemblies are automatically referenced by all pages in an ASP.NET application. The @Assembly directive is used in situations where, for some reason, the assembly is stored in an unexpected place.

The syntax for referencing an external assembly in Global.asax is the same as referencing an external assembly in a normal ASP.NET page.

Code Declaration Blocks in Global.asax

Code declaration blocks are events associated with Page objects such as Server and Application . You can write code in event handlers for these objects in Global.asax. The advantage of this is centralized management of initialization code. Because code in Global.asax is guaranteed to execute no matter which page initially uses to access the application, you don't have to worry about including it (or copying it) into every file of your application.

The event procedures that can be included in Global.asax (in the order in which the events fire) are

  • Application_OnStart

  • Session_OnStart

  • Session_OnEnd

  • Application_OnEnd

Listing 5.2 shows an example of an event handler for the Session object.

Listing 5.2 Example of an OnStart Event Handler in Global.asax
 <SCRIPT runat='server' language='c#'>   void Session_OnStart()   {     Response.Write("Starting a new session!<BR>");     Session["StartTime"] = DateTime.Now;     Session.Timeout = 45;   } </SCRIPT> 

You can test this script by dropping it into a Web-accessible directory and then navigating to an ASPX script file located in that directory. Don't try to navigate directly to Global.asax; it won't work. Also, the code in Global.asax isn't accessible from ASP.old scripts, so don't try testing it with an .ASP file.

This code is very straightforward; it sends a message to the browser for debugging purposes, stores the date and time the session began in a Session variable, and then sets the session timeout to 45 minutes. The code in this event procedure executes only the first time a user navigates to one of the pages in the Web application; a Web application is defined as any ASP.NET Web script in a given directory.

Server-Side Object Tags in Global.asax

In many cases, it's useful for a Web application to have access to an object globally. This enables you to share objects across multiple pages. You can also specify whether the object has application or sessionwide scope. You use server-side object tags in Global.asax to do this, as shown in Listing 5.3.

Listing 5.3 Declaring an Application-Scoped Object in Global.asax
 <object id="users"         scope="application"         class="System.Collections.ArrayList"         runat="server"/> <SCRIPT runat='server' language='c#'>     public void Session_OnStart()     {         String usr;         usr = Request.UserHostAddress;         users.Add(usr);         Response.Write("Global.asax: New session created.");     } </SCRIPT> 

In addition to the definition of the application-level object called users, the code includes a Session_OnStart event handler that adds the user's IP address to the user's ArrayList at the time the session is initiated. (In a real application, you would need a corresponding Session_OnEnd code to remove the user's IP address from the array when the session timed out.)

To display the contents of the array, use code similar to that shown in Listing 5.4.

Listing 5.4 Displaying Results of the Active-User Array
 <SCRIPT runat='server'>   void Page_Load(Object Sender,EventArgs e)   {     // NB the variable "users" is defined in global.asax     Response.Write(users.Count + " users have active sessions.<BR>");     foreach(String usr in users)     {       Response.Write(usr + "<BR>" );     }   } </SCRIPT> 

This code will work in any script that is contained in the application directory. To test it, you will either have to access the same page from two computers or launch two separate sessions on the same machine by using a different Web browser (such as Netscape or Opera) for your second session.

When you access the Web server from your local machine, the IP address will always be 127.0.0.1.

Note that you don't have to use this technique to use an object globally; instead, you can place objects in the Session object or (better yet) place the object in the ASP.NET cache. For information on this, see Chapter 4, "State Management and Caching."

Server-Side Includes in Global.asax

Server-side includes (SSIs) are the same in Global.asax as they are in any other server-side script. The SSI directive tells the Web server to include an external file in the script; it works the same as if you had copied and pasted it into the script yourself.

The syntax for a server-side include in Global.asax is the same as in any other server-side script in ASP or ASP.NET:

 <!-- #include File = "MyFile.inc" --> 

It's typical to see server-side includes used as a code-sharing tactic. Unfortunately, maintaining server-side includes can be unwieldy, particularly in situations where the includes are numerous or contain large amounts of code. Other disadvantages exist to using includes, notably that you don't have access to IntelliSense in the Visual Studio development for procedures contained in SSIs.

Rather than using SSIs, you may want to consider defining your global procedures as objects and referencing them as components instead.

for RuBoard


C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
ISBN: 672321556
EAN: N/A
Year: 2005
Pages: 103

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