Logging Exception To Database In ASP.NET

Monitoring the errors of a live application is very important to avoid any inconvenience. In C# to handle exceptions the try, catch and finally keywords are used, so in this article we will learn how to catch the error and log error details to the Database table so developers can fix it as soon as possible.
So let us start by creating the application.
Use the following procedure to create a web site:

Download Aspose : API TO Create and Convert Files
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Web Site..." then select "C#" - "Empty Weh Site" (to avoid adding a master page).
  3. Provide the project a name such as "ExceptionLoggingToDatabase" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer rhen select "Add New Item" - "Default.aspx" page.
  5. Drag and Drop one GridView to the Default.aspx page. Then the page will look as follows.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body bgcolor="silver">
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
</asp:GridView>
</form>
</body>
</html>
In the preceding source code, we have taken the one grid view and we try to assign a file as the data source for the grid view that is not available so it can generate the error file not found and we can log these error details to the database table.
Now create the table and provide a name as Tbl_ExceptionLoggingToDataBase or as you wish to store the exception details as:

 
/****** Object:  Table [dbo].[Tbl_ExceptionLoggingToDataBase]    Script Date: 15-04-2014 23:34:43 ******/  
SET ANSI_NULLS ON  
GO  
  
SET QUOTED_IDENTIFIER ON  
GO  
  
SET ANSI_PADDING ON  
GO  
  
CREATE TABLE [dbo].[Tbl_ExceptionLoggingToDataBase](  
    [Logid] [bigint] IDENTITY(1,1) NOT NULL,  
    [ExceptionMsg] [varchar](100) NULL,  
    [ExceptionType] [varchar](100) NULL,  
    [ExceptionSource] [nvarchar](max) NULL,  
    [ExceptionURL] [varchar](100) NULL,  
    [Logdate] [datetime] NULL,  
 CONSTRAINT [PK_Tbl_ExceptionLoggingToDataBase] PRIMARY KEY CLUSTERED   
(  
    [Logid] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  
GO  
  
SET ANSI_PADDING OFF  
GO 
 
 The table will look as:
 
 Now create the Stored Procedure to log the exception into the database table as:

Create Procedure ExceptionLoggingToDataBase  
(  
@ExceptionMsg varchar(100)=null,  
@ExceptionType varchar(100)=null,  
@ExceptionSource nvarchar(max)=null,  
@ExceptionURL varchar(100)=null  
)  
as  
begin  
Insert into Tbl_ExceptionLoggingToDataBase  
(  
ExceptionMsg ,  
ExceptionType,   
ExceptionSource,  
ExceptionURL,  
Logdate  
)  
select  
@ExceptionMsg,  
@ExceptionType,  
@ExceptionSource,  
@ExceptionURL,  
getdate()  
End  
Now create the class named ExceptionLogging to log the error to the database table and write the following code as:

ExceptionLogging.cs
using System;  
using context = System.Web.HttpContext;  
using System.Configuration;  
using System.Data.SqlClient;  
using System.Data;  
  
/// <summary>  
/// Summary description for ExceptionLogging  
/// article by Vithal Wadje  
  
/// </summary>  
public static class ExceptionLogging  
{  
  
    private static String exepurl;  
    static SqlConnection con;  
    private static void connecttion()  
    {  
        string constr = ConfigurationManager.ConnectionStrings["CharpCorner"].ToString();  
        con = new SqlConnection(constr);  
        con.Open();  
    }  
    public static void SendExcepToDB(Exception exdb)  
    {  
  
        connecttion();  
        exepurl = context.Current.Request.Url.ToString();  
        SqlCommand com = new SqlCommand("ExceptionLoggingToDataBase", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ExceptionMsg", exdb.Message.ToString());  
        com.Parameters.AddWithValue("@ExceptionType", exdb.GetType().Name.ToString());  
        com.Parameters.AddWithValue("@ExceptionURL", exepurl);  
        com.Parameters.AddWithValue("@ExceptionSource", exdb.StackTrace.ToString());  
        com.ExecuteNonQuery();  
  
  
  
    }  
  
  
}  
In the code above we have created a SendExcepToDB method that accepts the Exception class reference object and we can call this method from the default.aspx.cs file.

Now open the default.aspx.cs page and write the following code to assign the data source to the grid view:

protected void Page_Load(object sender, EventArgs e)    
   {    
       try    
       {    
    
           DataSet ds = new DataSet();    
           ds.ReadXml(Server.MapPath("~/emp.xml"));    
           GridView1.DataSource = ds;    
           GridView1.DataBind();    
    
       }    
       catch (Exception ex)    
       {    
    
       ExceptionLogging.SendExcepToDB(ex);    
       Label1.Text = "Some Technical Error occurred,Please visit after some time";  
   
       }    
       
   }    

In the code above, we have used try and catch keywords to handle the exception, from the first in the try block we are trying to assign the emp.xml as the data source to the grid view that is not available and in the catch block we are calling the method SendExcepToDB of the class ExceptionLogging to log the error by ing the Exception class reference object.
Now run the application The following dummy message we will be shown to the user and the actual error will be logged to the database table as:
 
Now all the Exception details will be logged into the database table as:
 

We can see that in the preceding table all the Exception details are logged into the database with an application URL and page Name along with other details that helps developers to fix the error easily.
Notes

  • Make the changes in the web.config file depending on your server location.
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.

Download Aspose : API To Create and Convert Files

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode