Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global.asax?

Status
Not open for further replies.

Sidro

MIS
Sep 28, 2002
197
US
HI,
I cant find enough detail about what and how to use the Global.asax file. When I do, they dont explain it in full detail and is too confusing for me. Can someone tell me what exactly is this file and what does it do? Is Global.asax like a module thats used in Visual basic, to hold global variables and methods? If it is like a module, then how do I access a method or variables, lets say from Default.aspx? Could you provide me with a code snippet example? And one last thing,is it true that IIS will not allow the global.asax to be viewed or downloaded by users? If it is then will it be safe to lets say, store a few password? Thankx in advance.
 
Sid: Here's a few definitive paragraphs, and a few suggestions:

*** from ASP Unleashed (Walther, 2002)

The Global.asax file is not used to display content. If you request this file, you receive an error. This error is intentional. Enabling users to view the contents of the Global.asax file would constitute a serious security hole.

The Global.asax file can be used to handle application wide events and declare application wide objects.

Every ASP.NET application supports a certain number of events. The most important events are:

* Application_AuthenticateRequest - raised before authenticating a user
* Application_AuthorizeRequest - raised before authorizing a user
* Application_BeginRequest - raised by every request to the server
* Application_End - raised immediately before th eend of all application instances
* Application_EndRequest - raised at the end of every request to the server
* Application_Error - raised by an unhandled error in the application
* Application_PreSendRequestContent - raised before sending content to the browser
* Application_PreSendRequestHeaders - raised before sending headers to the browser
* Application_Start - raised immediately after the first applicaton is created
* Dispose - raised immediately before the end of a single application instance
* Init - raised immediately after each application instance is created. This event might occur multiple times.

This list contains the standard application events. If you add other modules to your application, additional events are exposed in the Global.asax file. For example, FormsAuthenticationModule exposes a Forms_Authenticate event, and SessionStateModule exposes both Session_Start and Session_End events.

You can handle any of these events in the Global.asax file by adding the appropriate subroutine. In general, the subroutine should look like:

Sub Application_EventName
..application code
End Sub

Modifying the Global.asax file restarts the application. Any information stored in application (or Session) state is lost (so care here).

Understanding Context and Using the Global.asax File

Within an ASP.NET page, the Page object is the default object. In many cases, if you do not specify an object when you call a method or access a property, you are implicitly calling the method or accessing the property from the Page object. For example, when you call the MapPath method (maps virtual paths to physical paths) you are actually calling the Page.MapPath method. Or, when you access the Cache property, you are implicitly accessing the Page.Cache property.

The Global.asax file does not have the Page object as its defaul object. This means that you cannot simply call a method such as MapPath and expect it to work. Fortunately, in most cases, you can use a simple workaround. Instead of calling the MapPath method, you can call the Context.MapPath method. Or, instead of accessing the Page.Cache object, you can access the Context.Cache object.

If a familiar property or method does not work in the Global.asax file, you should immediately try calling the method or property by using the Context object instead.

Handling the Application Start and Init Events (code snippets)

The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. Its a good place to initialize global variable. For example, you might want to retrieve a list of products from a database table and place the list in aplliction state or the Cache object.

Application/Global.asax

<%@ Import Namespace=&quot;System.Data&quot; %>
<%@ Import Namespace=&quot;System.SqlClient&quot; %>

<Script ruant=&quot;server&quot;>

Sub Application_Start
Dim conNorthwind As sqlConnection
Dim strSelect As String
Dim dadProducts As SqlDataAdapter
Dim dstProducts As DataSet

conNorthwind = New SqlConnection( _
&quot;Server=localhost;UID=sa;PWD=secret;Database=Northwind&quot;)
strSelect = &quot;Select * From Products&quot;
dadProducts = New SqlDataAdapter(strSelect,conNorthwind)
dstProducts = New DataSet()
dadProducts.Fill(dstProducts, &quot;Products&quot;)
Context.Cache(&quot;Products&quot;) = dstProducts
End Sub

</script>

**********

Here's a tidbit from Visual Studio.NET

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HTTP modules. The Global.asax file resides in the root directory of an ASP.NET-based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

The ASP.NET Global.asax file can co-exist with the ASP Global.asa file. You can create a Global.asax file either in a WYSIWYG designer, in Notepad, or as a compiled class that you deploy in your application's \bin directory as an assembly. However, in the latter case, you still need a Global.asax file that refers to the assembly.

The Global.asax file is optional. If you do not define the file, the ASP.NET page framework assumes that you have not defined any application or session event handlers.

When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed. It completes all current requests for the application, sends the Application_OnEnd event to any listeners, and restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework re-parses and recompiles the Global.asax file and raises the Application_OnStart event.

ASP.NET provides several modules that participate in each request and expose events you can handle in Global.asax. You can customize and extend these modules as you like, or develop completely new custom modules to process information for and about HTTP requests made to your ASP.NET-based application. For example, you could create an output cache module that implements output-caching behaviors for your entire application.

All modules, whether custom or provided by the .NET Framework, must implement the IHttpModule interface. As long as these modules are registered with your application, you can easily interact with the HTTP requests coming in to your application.

Handling HTTP Module Events
You can use the Global.asax file to handle any event exposed by the modules in the request. For example, you might create a custom authentication module for your ASP.NET Web application in which you might expose an OnAuthenticateRequest event. The code that you write to handle the events exposed by an HTTP module must conform to the following naming pattern:

FriendlyModuleName_EventName(AppropriateEventArgumentSignature)
For example, if you want to include event-handling code for the beginning and end of a session, as well as for an OnAuthenticateRequest event, it could look like the following:

[Visual Basic]
<Script language=&quot;VB&quot; runat=&quot;server&quot;>
Sub Session_OnStart()
'Session start-up code goes here.
End Sub
Sub Session_OnEnd()
'Session clean-up code goes here.
End Sub
Sub Application_OnAuthenticateRequest(Source As Object, Details as EventArgs)
'Authentication code goes here.
End Sub
</script>
[C#]
<Script language=&quot;C#&quot; runat=&quot;server&quot;>
void Session_OnStart() {
// Session start-up code goes here.
}
void Session_OnEnd() {
// Session clean-up code goes here.
}
void Application_OnAuthenticateRequest(Object Source, EventArgs Details) {
// Authentication code goes here.
}
</script>

******

Sid -- these are just extracts from a few sources -- the use of the Global.asax file is seemingly endless, but handles modules and http handlers. I have seen it used here at tek-tips for the storage of &quot;connection strings&quot;, etc...

If you do a general search on the net, along with a few texts, I think you'll find that numerous events and processes (from page banners to connection strings, etc) that are stored in the Global.asax page. Also do a search here at tek-tips as several examples and discussions have been raised over the last year on this subject.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top