Background

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:
  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:
  1. USE [C#corner]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Tbl_ExceptionLoggingToDataBase]    Script Date: 15-04-2014 23:34:43 ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Tbl_ExceptionLoggingToDataBase](  
  15.     [Logid] [bigint] IDENTITY(1,1) NOT NULL,  
  16.     [ExceptionMsg] [varchar](100) NULL,  
  17.     [ExceptionType] [varchar](100) NULL,  
  18.     [ExceptionSource] [nvarchar](maxNULL,  
  19.     [ExceptionURL] [varchar](100) NULL,  
  20.     [Logdate] [datetime] NULL,  
  21.  CONSTRAINT [PK_Tbl_ExceptionLoggingToDataBase] PRIMARY KEY CLUSTERED   
  22. (  
  23.     [Logid] ASC  
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  25. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  26.   
  27. GO  
  28.   
  29. SET ANSI_PADDING OFF  
  30. GO 
 The table will look as:
 
 
 
 Now create the Stored Procedure to log the exception into the database table as:
  1. Create Procedure ExceptionLoggingToDataBase  
  2. (  
  3. @ExceptionMsg varchar(100)=null,  
  4. @ExceptionType varchar(100)=null,  
  5. @ExceptionSource nvarchar(max)=null,  
  6. @ExceptionURL varchar(100)=null  
  7. )  
  8. as  
  9. begin  
  10. Insert into Tbl_ExceptionLoggingToDataBase  
  11. (  
  12. ExceptionMsg ,  
  13. ExceptionType,   
  14. ExceptionSource,  
  15. ExceptionURL,  
  16. Logdate  
  17. )  
  18. select  
  19. @ExceptionMsg,  
  20. @ExceptionType,  
  21. @ExceptionSource,  
  22. @ExceptionURL,  
  23. getdate()  
  24. End 
Now create the class named ExceptionLogging to log the error to the database table and write the following code as:
 
ExceptionLogging.cs
  1. using System;  
  2. using context = System.Web.HttpContext;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.Data;  
  6.   
  7. /// <summary>  
  8. /// Summary description for ExceptionLogging  
  9. /// article by Vithal Wadje  
  10.   
  11. /// </summary>  
  12. public static class ExceptionLogging  
  13. {  
  14.   
  15.     private static String exepurl;  
  16.     static SqlConnection con;  
  17.     private static void connecttion()  
  18.     {  
  19.         string constr = ConfigurationManager.ConnectionStrings["CharpCorner"].ToString();  
  20.         con = new SqlConnection(constr);  
  21.         con.Open();  
  22.     }  
  23.     public static void SendExcepToDB(Exception exdb)  
  24.     {  
  25.   
  26.         connecttion();  
  27.         exepurl = context.Current.Request.Url.ToString();  
  28.         SqlCommand com = new SqlCommand("ExceptionLoggingToDataBase", con);  
  29.         com.CommandType = CommandType.StoredProcedure;  
  30.         com.Parameters.AddWithValue("@ExceptionMsg", exdb.Message.ToString());  
  31.         com.Parameters.AddWithValue("@ExceptionType", exdb.GetType().Name.ToString());  
  32.         com.Parameters.AddWithValue("@ExceptionURL", exepurl);  
  33.         com.Parameters.AddWithValue("@ExceptionSource", exdb.StackTrace.ToString());  
  34.         com.ExecuteNonQuery();  
  35.   
  36.   
  37.   
  38.     }  
  39.   
  40.   

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:
  1. protected void Page_Load(object sender, EventArgs e)    
  2.    {    
  3.        try    
  4.        {    
  5.     
  6.            DataSet ds = new DataSet();    
  7.            ds.ReadXml(Server.MapPath("~/emp.xml"));    
  8.            GridView1.DataSource = ds;    
  9.            GridView1.DataBind();    
  10.     
  11.        }    
  12.        catch (Exception ex)    
  13.        {    
  14.     
  15.        ExceptionLogging.SendExcepToDB(ex);    
  16.        Label1.Text = "Some Technical Error occurred,Please visit after some time";  
  17.    
  18.        }    
  19.        
  20.    }   
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
  • Download the Zip file from the attachment for the full source code of the application.
  • 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.

Next Recommended Readings