- So let us start by creating the application. Use the following procedure to create a web site:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New" - "Web Site..." then select "C#" - ""ASP.NET Empty Web Site"" (to avoid adding a master page).
- Provide the project a name such as "ExceptionLoggingToEmail" or another as you wish and specify the location.
- Then right-click on Solution Explorer then select "Add New Item" - "Default.aspx" page.
- Drag and Drop one GridView to the Default.aspx page. Then the page will look as follows.
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 send these error details to an Email.<%@ 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">
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
Now create the class named ExceptionLogging to log the error to Email then write the following code:
In the code above we have created a SendErrorTomail 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:
In the code above, we have used try and catch keywords to handle the exception, 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 SendErrorTomail of the class ExceptionLogging to log the error by creating 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 Email as:
- Make the changes in the web.config file depending on your Email id Credential .