HI WELCOME TO KANSIRIS

What is global.asax

Leave a Comment

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 HttpModules.

The Global.asax file resides in the root directory of an ASP.NET-based application. The Global.asax file is parsed and dynamically compiled by ASP.NET.

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 Global.asax file does not need recompilation if no changes have been made to it. There can be only one Global.asax file per application and it should be located in the application's root directory only.
The Global.asax contains two types of events those are

Events which are fired for every request

Events which are not fired for every request

Now I will explain about

Events which are fired for every request

Application_BeginRequest() – This event raised at the start of every request for the web application.

Application_AuthenticateRequest – This event rose just before the user credentials are authenticated. We can specify our own authentication logic here to provide custom authentication.

Application_AuthorizeRequest() – This event raised after successful completion of authentication with user’s credentials. This event is used to determine user permissions. You can use this method to give authorization rights to user. 

Application_ResolveRequestCache() – This event raised after completion of an authorization request and this event used in conjunction with output caching. With output caching, the rendered HTML of a page is reused without executing its code.

Application_AcquireRequestState() – This event raised just before session-specific data is retrieved for the client and is used to populate Session Collection for current request.

Application_PreRequestHandlerExecute() – This event called before the appropriate HTTP handler executes the request.

Application_PostRequestHandlerExecute() – This event called just after the request is handled by its appropriate HTTP handler.

Application_ReleaseRequestState() – This event raised when session specific information is about to serialized from the session collection.

Application_UpdateRequestCache() – This event raised just before information is added to output cache of the page.

Application_EndRequest() – This event raised at the end of each request right before the objects released. 

Now we will see

Events which are not fired for every request

Application_Start() – This event raised when the application starts up and application domain is created.

Session_Start() – This event raised for each time a new session begins, This is a good place to put code that is session-specific.

Application_Error() – This event raised whenever an unhandled exception occurs in the application. This provides an opportunity to implement generic application-wide error handling.

Session_End() – This event called when session of user ends.

Application_End() – This event raised just before when web application ends.

Application_Disposed() – This event fired after the web application is destroyed and this event is used to reclaim the memory it occupies.

What is Global.asax file: global.asax allows us to write event handlers that react to global events in web applications.

How it gets called: Global.asax files are never called directly by the user, rather they are called automatically in response to application events.

Point to remember about global.asax:
  1. They do not contain any HTML or ASP.NET tags.
  2. Contain methods with specific predefined names.
  3. They defined methods for a single class, application class.
  4. They are optional, but a web application has no more than one global.asax file.
How to add global.asax file:

Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web project model) and choose the Global Application Class template.

global.asax1.gif
 
After you have added the global.asax file, you will find that Visual Studio has added Application Event handlers:

<%@ Application Language="C#" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
    }
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
    }
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
    }
    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
    }
    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
    }
</script>

Purpose of these application event handlers: To reach and handle any HttpApplication event.

If you want to know about HttpApplication events, see the MSDN article.

How these handler reach to HttpApplication Events
  1. global.asax file aren't attached in the same way as the event handlers for ordinary control events
  2. Way to attach them is to use the recognized method name, i.e. for event handler Application_OnEndRequest(), ASP.NET automatically calls this method when the HttpApplication.EndRequest event occurs.
What kind of application event global.asax can handle:

Global.asax can handle 2 types of applications events

1) Events that occurs only under specific conditions, i.e. request / response related events.

Order in which application event handler executes;

OrderApplication EventsWhat they do
1Application_BeginRequest()This method is called at the start of every request.
2Application_AuthenticateRequest()This method is called just before authentication is performed. This is time and place where we can write out own authentication codes.
3Application_AuthorizeRequest()After the user is authenticated (identified), it's time to determine the user's permissions. Here we can assign user with special privileges
4Application_ResolveRequestCache()This method is commonly used in conjunction with output caching. 
5Application_AcquireRequestState()This method is called just before session-specific information is retrieved for the client and used to populate the Session collection.
6Application_PreRequestHandlerExecute()This method is called before the appropriate HTTP handler executes the request.
7Application_PostRequestHandlerExecute()This method is called just after the request is handled.
8Application_ReleaseRequestState()This method is called when the session-specific information is about to be serialized from the Session collection so that it's available for the next request.
9Application_UpdateRequestCache()This method is called just before information is added to the output cache.
10Application_EndRequest()This method is called at the end of the request, just before the objects are released and reclaimed. It's a suitable point for cleanup code.
2) Events that don't get fired with every request.

OrderApplication EventsWhat they do
1Application_Start()This method is invoked when the application first starts up and the application domain is created. This event handler is a useful place to provide application-wide initialization code. For example, at this point you might load and cache data that will not change throughout the lifetime of an application, such as navigation trees, static product catalogs, and so on.
2Session_Start()This method is invoked each time a new session begins. This is often used to initialize user-specific information. 
3Application_Error()This method is invoked whenever an unhandled exception occurs in the application.
4Session_End()This method is invoked whenever the user's session ends. A session ends when your code explicitly releases it or when it times out after there have been no more requests received within a given timeout period (typically 20 minutes).
5Application_End()This method is invoked just before an application ends. The end of an application can occur because IIS is being restarted or because the application is transitioning to a new application domain in response to updated files or the process recycling settings.
6Application_Disposed()This method is invoked some time after the application has been shut down and the .NET garbage collector is about to reclaim the memory it occupies. This point is too late to perform critical cleanup, but you can use it as a last-ditch failsafe to verify that critical resources are released.
So now it's time to write codes under these event handlers.

Let's try for Application_Error

protected void Application_Error(Object sender, EventArgs e)
{
    Response.Write("<font face=\"Tahoma\" size=\"2\" color=\"red\">");
    Response.Write("Oops! Looks like an error occurred!!<hr></font>");
    Response.Write("<font face=\"Arial\" size=\"2\">");
    Response.Write(Server.GetLastError().Message.ToString());
    Response.Write("<hr>" + Server.GetLastError().ToString());
    Server.ClearError();
}

So when any error happens, it get handled here with custom message.
 
global.asax2.gif

Let's write code for Application_AuthenticateRequest , here we can write code our own authentication codes, because this method is called just before authentication is performed.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    Response.Write("Authenticating request...<br>");
    bool cookieFound = false;
    HttpCookie authCookie = null;
    HttpCookie cookie;
    for (int i = 0; i < Request.Cookies.Count; i++)
    {
        cookie = Request.Cookies[i];
        if (cookie.Name == FormsAuthentication.FormsCookieName)
        {
            cookieFound = true;
            authCookie = cookie;
            break;
        }
    }
    // If the cookie has been found, it means it has been issued from either
    // the windows authorisation site, is this forms auth site.
    if (cookieFound)
    {
        // Extract the roles from the cookie, and assign to our current principal, which is attached to the
        // HttpContext.
        FormsAuthenticationTicket winAuthTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string[] roles = winAuthTicket.UserData.Split(';');
        FormsIdentity formsId = new FormsIdentity(winAuthTicket);
        System.Security.Principal.GenericPrincipal princ = newSystem.Security.Principal.GenericPrincipal(formsId, roles);
        HttpContext.Current.User = princ;
    }
    else
    {
        // No cookie found, we can redirect to the Windows auth site if we want, or let it pass through so
        // that the forms auth system redirects to the logon page for us.
    }
}

If there is no error, see below the order in which application events are handled.

global.asax3.gif 

As per your requirement you can write your codes to use these application events handlers.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.