Wednesday, August 29, 2007

Global.asax

GLOBAL.ASAX

  • Used by Web Applications to handle some application-level events raised by the ASP.net runtime or by registered http modules
  • Global.asax file is optional and is located in the root directory of the application
  • Only one global.asax file per application is accepted, those in sub-directories are ignored
  • When the application is started, global.asax is parsed into a source class and compiled
  • The resultant assembly is created in the temporary directory just as any other dynamically generated assembly would be
  • The class is named as ASP.global_asax and is derived from System.Web.HttpApplication
  • Any modification made during application execution causes application restart

Contents/Syntax of Global.asax

  • Four elements determine the syntax of the global.asax file
  1. Application Directives
  2. Code declaration blocks
  3. Server side <object> tags
  4. Server side includes

Application Directives

  • The global.asax supports three directives: @Application, @Import and @Assembly
  • @Import directive imports a namespace into an application
  • @Assembly directive links an assembly to the application at compile time
  • @Application supports a few attributes - Description, Language and Inherits

Code Declaration Blocks

  • A global.asax file can contain code wrapped by a <script> tag
  • <script language= "C#" runat="server" src="global.aspx.cs">

Server-Side <object> tags

  • The server-side <object> tag allows to create new objects using a declarative syntax
  • object tag can take three forms, depending on the specified type

    <object id="..." runat="server" scope=Pipeline|Application|Session class="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session progid="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session classid="...">

  • In first case, the object is identified by the name of the class and assembly that contains it
  • In other two cases, the object to create is a COM object identified by the progid or classid

Server-Side Includes

  • An #include directives inserts the contents of the specified file as-is into the ASP.net file that uses it
  • The directive must be enclosed in an HTML comment
  • <!-- #include file="filename"> or <!-- #include virtual="filename">

Static Properties

  • If static proerties are defined in global.asax file, they will be accessible for reading and writing by all pages in the application
  • Sample code as under:

    <script language="C#" runat="server">

    public static int Counter = 0;

    </script>

  • To access this property from a page, code as under

    Response.Write(ASP.global_asax.Counter.ToString());

No comments: