Global.asax is used for handling Web Application events. We can have only one Global.asax file per application. It resides in the root directory of our application. This file is optional.
This class has events which will be fired when application starts or end, session starts or ends, or when an unhandled error occurs etc.
We are going to store all unhandled errors into the database table and application logs. We are also going to track users i.e. capture the time they visited the webpage, their IP address and the web pages they are visiting.
Error Logging i.e. Storing Unhandled errors
Let us see how to store unhandled errors into Database table.
Create a table LogItems to store errors
CREATE TABLE [dbo].[LogItems](
[EventId] [int] IDENTITY(1,1) NOT NULL,
[LogDateTime] [datetime] NULL,
[Source] [char](100) NULL,
[Message] [varchar](1000) NULL,
[Form] [varchar](4000) NULL,
[QueryString] [varchar](2000) NULL,
[TargetSite] [varchar](300) NULL,
[StackTrace] [varchar](4000) NULL,
[Referer] [varchar](250) NULL
) ON [PRIMARY]
Stored procedure to insert values into LogItems table
CREATE PROCEDURE [dbo].[ebbNet_insertLogItems]
@source varchar(100),
@LogDateTime dateTime,
@Message varchar(1000),
@Form varchar(4000),
@QueryString varchar(2000),
@TargetSite varchar(300),
@StackTrace varchar(4000),
@Referer varchar(250),
@EventId int output
AS
INSERT INTO LOGITEMS
(Source, LogDateTime,Message,Form,QueryString,TargetSite,StackTrace,Referer)
Values (
@Source,
@LogDateTime,
@Message,
@Form,
@QueryString,
@TargetSite,
@StackTrace,
@Referer)
Select @EventId=@@identity
Code
In Global.asax write the following code under Application_Error function. When ever an unhadled error occurs in our application this code will be executed.
void Application_Error(object sender, EventArgs e)
{
//get the error
Exception ex = Server.GetLastError().GetBaseException();
HttpContext ctx = HttpContext.Current;
string referer="";
if(ctx.Request.ServerVariables["HTTP_REFERER"]!=null)
referer=ctx.Request.ServerVariables["HTTP_REFERER"].ToString();
string sForm="";
if(ctx.Request.Form!=null)
sForm=ctx.Request.Form.ToString();
//get the query string
string sQuery="";
if(ctx.Request.QueryString!=null)
sQuery=ctx.Request.QueryString.ToString();
int evtId;
System.Data.SqlClient.SqlConnection conn = null;
try
{
string connectionString = ConfigurationManager.ConnectionStrings
["DatabaseConnectionString1"].ConnectionString;
conn = new System.Data.SqlClient.SqlConnection(connectionString);
conn.Open();
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.ebbNet_insertLogItems";
cmd.Parameters.AddWithValue("@source", ex.Source);
cmd.Parameters.AddWithValue("@LogDateTime",DateTime.Now);
cmd.Parameters.AddWithValue("@Message", ex.Message);
cmd.Parameters.AddWithValue("@Form",sForm);
cmd.Parameters.AddWithValue("@QueryString",sQuery);
cmd.Parameters.AddWithValue("@TargetSite",ex.TargetSite.ToString());
cmd.Parameters.AddWithValue("@StackTrace",ex.StackTrace.ToString());
cmd.Parameters.AddWithValue("@Referer",referer);
System.Data.SqlClient.SqlParameter outParam = new System.Data.SqlClient.SqlParameter
("@EventId", System.Data.SqlDbType.Int);
outParam.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outParam);
cmd.ExecuteNonQuery();
evtId = Convert.ToInt32(cmd.Parameters[8].Value);
conn.Close();
}
finally
{
if (conn != null)
conn.Close();
}
We can also write the errors into Application Log
In Global.asax write the following code under Application_Error function. The following code creates a new application log named ErrorSample , if it does not already exists and writes the errors to it. We need registry permissions to create Log on remote server.
void Application_Error(object sender, EventArgs e)
{
//get the error
string ErrorDescription = Server.GetLastError().ToString();
//creation of event log if it does not exists
string EventLogName = "ErrorSample";
if (!System.Diagnostics.EventLog.SourceExists(EventLogName))
System.Diagnostics.EventLog.CreateEventSource(EventLogName, EventLogName);
//inserting into event log
System.Diagnostics.EventLog Log = new System.Diagnostics.EventLog();
Log.Source = EventLogName;
Log.WriteEntry(ErrorDescription, System.Diagnostics.EventLogEntryType.Error);
}
Tracking website vistors
Create a table UserStatistics to store user statistics
CREATE TABLE [dbo].[UserStatistics](
[DateTimeHit] [datetime] NOT NULL,
[IPAddress] [varchar](20) NOT NULL,
[PageUrl] [varchar](500) NOT NULL
) ON [PRIMARY]
Stored procedure to insert values into user statistics table.
CREATE PROCEDURE [dbo].[ebbNet_insertUserStatistics]
@DateTimeHit datetime,
@IPAddress varchar(20),
@PageUrl varchar(500)
AS
BEGIN
SET NOCOUNT ON;
insert into dbo.UserStatistics
values (@DateTimeHit, @IPAddress, @PageUrl)
END
Code
In Global.asax under Application_BeginRequest write the following code. Application_BeginRequest is called each time a request is made.
void Application_BeginRequest(object sender, EventArgs e)
{
//we are storing only the information related to aspx pages
if (Request.FilePath.Contains("aspx"))
{
System.Data.SqlClient.SqlConnection conn = null;
try
{
string connectionString = ConfigurationManager.ConnectionStrings
["DatabaseConnectionString1"].ConnectionString;
conn = new System.Data.SqlClient.SqlConnection(connectionString);
conn.Open();
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.ebbNet_insertUserStatistics";
cmd.Parameters.AddWithValue("@DateTimeHit", DateTime.Now);
cmd.Parameters.AddWithValue("@IPAddress", Request.UserHostName);
cmd.Parameters.AddWithValue("@PageUrl", Request.Path);
int rowsUpdated = cmd.ExecuteNonQuery();
conn.Close();
}
finally
{
if (conn != null)
conn.Close();
}
}
}
Whatever is written here can have an impact on the application. Because it writes to SQL Server, and if the website traffic is very high this method is not recommended. Error Logging and User Tracking can be done using ASP.NET Health Monitoring systems.
0 Comments Received
Post a Comment