ASP.NET Tutorial/ASP.Net Instroduction/Global.asax

Материал из .Net Framework эксперт
Версия от 11:57, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Appication level event handlers in global.asax

<script language="VB" runat="server">
   Sub Application_Start(Sender as Object, e as EventArgs)
      Application("Time") = System.DateTime.Now
   End Sub
   Sub Application_AcquireRequestState(Sender as Object, e as EventArgs)
      Response.Write("Acquiring request session state" & "...<br>")
   End Sub
   Sub Application_AuthenticateRequest(Sender as Object, e as EventArgs)
      Response.Write("Authenticating request...<br>")
   End Sub
   Sub Application_AuthorizeRequest(Sender as Object, e as EventArgs)
      Response.Write("Authorizing request...<br>")
   End Sub
   Sub Application_PostRequestHandlerExecute(Sender as Object, e as EventArgs)
      Response.Write("Request handler executed...<br>")
   End Sub
   Sub Application_PreRequestHandlerExecute(Sender as Object, e as EventArgs)
      Response.Write("Request handler executed...<br>")
   End Sub
   Sub Application_PreSendRequestContent(Sender as Object, e as EventArgs)
      Response.Write("Receiving request content...<br>")
   End Sub
   Sub Application_PreSendRequestHeaders(Sender as Object, e as EventArgs)
      Response.Write("Receiving request headers...<br>")
   End Sub
   Sub Application_ReleaseRequestState(Sender as Object, e as EventArgs)
      Response.Write("Releasing request state...<br>")
   End Sub
   Sub Application_ResolveRequestCache(Sender as Object, e as EventArgs)
      Response.Write("Resolving request cache...<br>")
   End Sub
   Sub Application_UpdateRequestCache(Sender as Object, e as EventArgs)
      Response.Write("Updating request cache...<br>")
   End Sub
   Sub Application_Error(Sender as Object, e as EventArgs)
      Response.Write(Sender.Request.isAuthenticated & " is authenticating request...<br>")
   End Sub
   Sub Session_Start(Sender as Object, e as EventArgs)
      Response.Write("Session is starting...<br>")
   End Sub
   Sub Application_BeginRequest(Sender as Object, e as EventArgs)
      Response.Write("<b>Process</b>")
      Response.Write("Request is starting...<br>")
   End Sub
   Sub Application_EndRequest(Sender as Object, e as EventArgs)
      Response.Write("Request is ending...<br>")
   End Sub
</script>


Application level action sequence

<%@ Application Language="C#" %>
<script runat="server">
    void Application_Start(Object sender, EventArgs e) {
    }
    protected void Application_OnEndRequest()
    {
        Response.Write("<hr>This page was served at " +DateTime.Now.ToString());
    }
    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();
    }

    void Session_Start(Object sender, EventArgs e) {
    }
    void Session_End(Object sender, EventArgs e) {
    }
       
</script>


Global application file. (C#)

Use this file to define global variables.
React to global events (such as when a web application first starts).
<%@ Application Language="C#" %>
<script runat="server">
    protected void Application_OnEndRequest()
    {
        Response.Write("<hr>This page was served at " + 
         DateTime.Now.ToString());
    }
       
</script>


Global.asax file can be used to track the number of page requests made for any page.

File: Global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">
    private string _conString;
    private SqlConnection _con;
    private SqlCommand _cmdSelect;
    private SqlCommand _cmdInsert;
    public override void Init()
    {
        _conString = WebConfigurationManager.ConnectionStrings["Log"]. ConnectionString;
        _con = new SqlConnection(_conString);
        _cmdSelect = new SqlCommand("SELECT COUNT(*) FROM Log WHERE Path=@Path", _con);
        _cmdSelect.Parameters.Add("@Path", SqlDbType.NVarChar, 500);
        _cmdInsert = new SqlCommand("INSERT Log (Path) VALUES (@Path)", _con);
        _cmdInsert.Parameters.Add("@Path", SqlDbType.NVarChar, 500);
    }
    public int NumberOfRequests
    {
        get
        {           
           int result = 0;
           _cmdSelect.Parameters["@Path"].Value = Request. AppRelativeCurrentExecutionFilePath;
           try
           {
               _con.Open();
               result = (int)_cmdSelect.ExecuteScalar();
           }
           finally
           {
               _con.Close();
           }
           return result;
        }
    }
    void Application_BeginRequest(object sender, EventArgs e)
    {
        _cmdInsert.Parameters["@Path"].Value = Request. AppRelativeCurrentExecutionFilePath;
        try
        {
            _con.Open();
            _cmdInsert.ExecuteNonQuery();
        }
        finally
        {
            _con.Close();
        }
    }
</script>


Log exception in Global.asax (C#)

using System;
using System.Collections;
using System.ruponentModel;
using System.Web;
using System.Web.SessionState;
namespace MyApp
{
  public class Global : System.Web.HttpApplication
  {
    protected void Application_Error(Object sender, EventArgs e)
    {
      System.Diagnostics.EventLog myEventLog;
      Exception ex=Server.GetLastError();
      myEventLog=new System.Diagnostics.EventLog();
      myEventLog.Log="Application";
      myEventLog.Source="Default";
      myEventLog.WriteEntry(ex.ToString());
      myEventLog=null;
    }
  }
}


Log exception in Global.asax (VB)

Imports System.Web
Imports System.Web.SessionState
Public Class Global Inherits System.Web.HttpApplication
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim myEventLog As System.Diagnostics.EventLog
        Dim ex As Exception = Server.GetLastError()
        myEventLog = New System.Diagnostics.EventLog()
        myEventLog.Log = "Application"
        myEventLog.Source = "Default"
        myEventLog.WriteEntry(ex.ToString())
    End Sub
End Class


Override string GetVaryByCustomString in Global.asax (C#)

<%@ Application Language="C#" %>
<script runat="server">
    public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg.ToLower() == "prefs ")
        {
            HttpCookie cookie = context.Request.Cookies["Language"];
            if (cookie != null)
            {
                return cookie.Value;
            }
        }
        return base.GetVaryByCustomString(context, arg);
    }
    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) 
    {

    }
       
</script>


Override string GetVaryByCustomString in Global.asax (VB)

<%@ Application Language="VB" %>
<script runat="server">
    Overrides Function GetVaryByCustomString(ByVal context As HttpContext, _
            ByVal arg As String) As String
        If arg.ToLower() = "prefs" Then
            Dim cookie As HttpCookie = context.Request.Cookies("Language")
            If cookie IsNot Nothing Then
                Return cookie.Value
            End If
        End If
        Return MyBase.GetVaryByCustomString(context, arg)
    End Function
    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        " Code that runs on application startup
    End Sub
    
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        " Code that runs on application shutdown
    End Sub
        
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        " Code that runs when an unhandled error occurs
    End Sub
    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        " Code that runs when a new session is started
    End Sub
    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        " 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.
    End Sub
       
</script>


Some events don"t fire with every request:

Start() is invoked when the application first starts up.
Start() is invoked each time a new session begins. 
Error() is invoked whenever an unhandled exception occurs in the application.
End() is invoked whenever the user"s session ends. 
End() is invoked just before an application ends. 
Disposed() is invoked after the application has been shut down.


Static application variables

File: Global.asax
<%@ Application Language="C#" ClassName="Global" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script runat="server">
    private static string[] fileList;
    public static string[] FileList
    {
        get
        {
            if (fileList == null)
            {
                fileList = Directory.GetFiles(HttpContext.Current.Request.PhysicalApplicationPath);
            }
            return fileList;
        }
    }
    private static Dictionary<string, string> metadata = new Dictionary<string, string>();
    public void AddMetadata(string key, string value)
    {
        lock (metadata)
        {
            metadata[key] = value;
        }
    }
    public string GetMetadata(string key)
    {
        lock (metadata)
        {
            return metadata[key];
        }
    }
</script>

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="StaticApplicationVariables" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblInfo" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using ASP;
public partial class StaticApplicationVariables : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    StringBuilder builder = new StringBuilder();
    foreach (string file in Global.FileList)
    {
      builder.Append(file + "<br />");
    }
    lblInfo.Text = builder.ToString();
    }
}


The global.asax Application File

The global application class that"s used by the global.asax file should always be stateless.
You can handle two types of events in the global.asax file:
Events that always occur for every request. 
Events that occur only under certain conditions.
BeginRequest() called at the start of every request, including requests for files that aren"t web forms.
AuthenticateRequest() called before authentication is performed. 
AuthorizeRequest() assigns special privileges.
ResolveRequestCache() is used in conjunction with output caching. 
AcquireRequestState() is called before session-specific information is retrieved for the client.
PreRequestHandlerExecute() is called before the appropriate HTTP handler executes the request.
PostRequestHandlerExecute() is called just after the request is handled.
ReleaseRequestState() is called when the session-specific information is about to be serialized from the Session collection.
UpdateRequestCache() is called before information is added to the output cache. 
EndRequest() is called at the end of the request.