-->

26 January 2020

Asp.Net Global.asax

  Asp.Net CS By Example       26 January 2020


 Global.asax 

  Global.asax is a Global Configuration File to manage special events related to the Application and Session management.

  Global.asax is another special file that can be added to the root of an application. It defines subroutines that are executed in response to application-wide events.

 For instance, Application_Start is executed the first time the application runs (or just after we restart the server). This makes this method the perfect place to execute any initialization code that needs to run when the application loads for the first time. Another useful method is Application_Error, which is called whenever an unhandled error occurs within a page.

  The following is a list of the handlers that we will use most often within the Global.asax file:
1) Application_Start : called immediately after the application is created; this event occurs once only
2) Application_End : called immediately before the end of all application instances
2) Application_Error : called by an unhandled error in the application
4) Application_BeginRequest : called by every request to the server
5) Application_EndRequest : called at the end of every request to the server
6) Application_PreSendRequestHeaders: called before headers are sent to the browser
7) Application_PreSendRequestContent : called before content is sent to the browser
8) Application_AuthenticateRequest : called before authenticating a user
9) Application_AuthorizeRequest : called before authorizing a user.

 The Global.asax file is created in the same way as the Web.config file—just select File
  => Right click On Project.
  => select 'Add' Menu
  => select 'New Item' Menu
  => select 'Web' Setcion in Visual C#.
  => Now Select 'Global Application Class' form from the dialog that appears.
  => Give a meaningful Name to Dataset E.g. 'AppGlobal.asax'
  => And Last step is click On 'Add' Button.

  Code: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace LearnAsp.Net
{
    public class Global : System.Web.HttpApplication
    {
        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
            if (HttpContext.Current.Server.GetLastError() != null)
            {
                Exception myException = HttpContext.Current.Server.GetLastError().GetBaseException();
                string pagename = HttpContext.Current.Request.Url.AbsolutePath;
                StackTrace st = new StackTrace(myException, true);
                StackFrame stackFrame = new StackFrame(0);
                WriteErrorLog(" Page Name : " + pagename + " | " + " Error Message : " + myException.Message); 
				WriteErrorLog(new String('-',30));
                Response.Redirect("~/DefaultError.aspx", true);
            }
        }

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

        public bool WriteErrorLog(string LogMessage)
        {
            bool Status = false;
            string LogDirectory = Server.MapPath("~/ErrorLog/");
            DateTime CurrentDateTime = DateTime.Now;
            string CurrentDateTimeString = CurrentDateTime.ToString();
            CheckCreateLogDirectory(LogDirectory);
            string logLine = BuildLogLine(CurrentDateTime, LogMessage);
            LogDirectory = (LogDirectory + "Log_" + LogFileName(DateTime.Now) + ".txt");
            StreamWriter oStreamWriter = null;
            try
            {
                oStreamWriter = new StreamWriter(LogDirectory, true);
                oStreamWriter.WriteLine(logLine);
                Status = true;
            }
            catch
            {
            }
            finally
            {
                if (oStreamWriter != null)
                {
                    oStreamWriter.Close();
                }
            }
            return Status;
        }   

        private bool CheckCreateLogDirectory(string LogPath)
        {
            bool loggingDirectoryExists = false;
            DirectoryInfo oDirectoryInfo = new DirectoryInfo(LogPath);
            if (oDirectoryInfo.Exists)
            {
                loggingDirectoryExists = true;
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(LogPath);
                    loggingDirectoryExists = true;
                }
                catch
                {
                    // Logging failure
                }
            }
            return loggingDirectoryExists;
        }

        private string BuildLogLine(DateTime CurrentDateTime, string LogMessage)
        {
            StringBuilder loglineStringBuilder = new StringBuilder();
            loglineStringBuilder.Append(LogFileEntryDateTime(CurrentDateTime));
            loglineStringBuilder.Append(" \t");
            loglineStringBuilder.Append(LogMessage);
            return loglineStringBuilder.ToString();
        }

        public string LogFileEntryDateTime(DateTime CurrentDateTime)
        {
            return CurrentDateTime.ToString("dd-MM-yyyy HH:mm:ss");
        }

        private string LogFileName(DateTime CurrentDateTime)
        {
            return CurrentDateTime.ToString("dd_MM_yyyy");
        }
    }
}

logoblog

Thanks for reading Asp.Net Global.asax

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.