Error Logging in ASP.NET

Errors may occur during the development. Not only in the Web sites, it is in all the fields. Every coders may know which place the error will come.Some errors can be easily identified and get a solution easily.But some cases we cant identify what error and why this error is coming like this. For an good website we have to maintain the error log in the Application. So we can track the errors easily and fix the issues sooner.

In this blog, we will see how to create a simple error log in our website. We will show an error has been occured message to the user. At the same time,we will log the error in a htm file. The html error file will be created with the name of current date. whenever the error is occurred, It will automatically update with the html file.

Types of errors

Syntax errors-(ex: we missed the semicolon at end of the statement).
Logical error-(ex: Converting a string to int).
Application error-(ex: may be the folder permission does not give to create a new file).

Download the project with full source code.

let us see steps,how to catch errors and log.

Step 1: Create a new folder named Logs and set write permission.

Step 2: Create a new ErrorPage.aspx and in that page write the Error has been occurred during process message in a Label.

Step 3: create a new class named General.cs and add the variables to use in the error log.

private string strDLLName, strErrorIn, strFileName, strFileLocation, strErrorMethodName, strErrorMessage, strLineNo, strException, strLogFormat;

Step 4: write the method GetErrorDetails as a return type void.

public void GetErrorDetails(Exception ex)
 {
 strException = ex.StackTrace.Trim().Remove(0, 3);
 string strDllInfo, strLocationInfo;
 if (strException.Contains(":") && strException.Contains(".") && strException.Contains("\\"))
 {
 strDllInfo = strException.Substring(0, strException.IndexOf('('));
 strLocationInfo = strException.Substring(strException.IndexOf(')'), (strException.LastIndexOf(':')) - strException.IndexOf(')')).Remove(0, 5);

 //Get the DLL Name
 strDLLName = strDllInfo.Substring(0, strDllInfo.Substring(0, strDllInfo.LastIndexOf('.')).LastIndexOf('.'));

 //Get the File Type & Name
 string strFileCheck = strLocationInfo.Substring(strLocationInfo.LastIndexOf('\\')).Remove(0, 1);
 string[] arrFileCheck = strFileCheck.Split('.');

 if (arrFileCheck.Length > 2)
 strErrorIn = "Page File";
 else
 strErrorIn = "Class File";
 strFileName = strFileCheck;

 //Get the Error File Location
 strFileLocation = "~\\" + strLocationInfo.Substring(AppDomain.CurrentDomain.BaseDirectory.Length);

 //Get the Error Method Name
 strErrorMethodName = strDllInfo.Substring(strDllInfo.LastIndexOf('.')).Remove(0, 1);

 //Get the Error Meassage
 strErrorMessage = ex.Message;

 //Get the Error Line No.
 strLineNo = strException.Substring(strException.LastIndexOf(':'), (strException.Length - strException.LastIndexOf(':'))).Remove(0, 6);
 }
 else
 {
 strDLLName = "-";
 strFileName = "-";
 strFileLocation = "-";
 strErrorMethodName = ex.ToString();
 strErrorIn = "Application Error";
 strLineNo = "-";
 strErrorMessage = ex.Message;
 }
 //Write the Error In ErroLog File
 WriteError(strDLLName, strErrorIn, strFileName, strFileLocation, strErrorMethodName, strErrorMessage, strLineNo);
 }

Step 5: Write the catched error in the html file

private void WriteError(string strDLLName, string strErrorIn, string strFileName, string strFileLocation, string strErrMethodName, string strErrMessage, string strLineNo)
 {
 bool boolErrLog = true;

 string strbaseDir = AppDomain.CurrentDomain.BaseDirectory;
 string strErrHeader = "<TR bgColor=\"#E6D4A7\"><TD align=center><font size=\"4\">DataBase</font></TD><TD align=center><font size=\"4\">User</font></TD><TD align=center><font size=\"4\">Date</font></TD><TD align=center><font size=\"4\">DLL Name</font></TD><TD align=center><font size=\"4\">Error In<font></TD><TD align=center><font size=\"4\">File Name</font></TD><TD align=center><font size=\"4\">File Location</font></TD><TD align=center><font size=\"4\">Error Method Name</font></TD><TD align=center><font size=\"4\">Error Message</font></TD><TD align=center><font size=\"4\">Error Line No</font></TD></TR>";
 string strTitle = "<h2 align=center>" + "My Website Error Log Information" + "</h2>";
 string strErrorTime = DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Year.ToString();
 string strDBName = "-", strLoginUser = "-";
 string strLogFilePath = strbaseDir + "Logs\\" + "ErrorLog" + "_" + strErrorTime + ".html";

 if (!Directory.Exists(strbaseDir + "Logs\\"))
 {
 Directory.CreateDirectory(strbaseDir + "Logs\\");
 }

 if (File.Exists(strLogFilePath))
 {
 boolErrLog = false;
 }

 StreamWriter sw = new StreamWriter(strLogFilePath, true);

 if (boolErrLog)
 {
 sw.WriteLine(strTitle + "<TABLE rules=\"all\">");
 sw.WriteLine(strErrHeader);
 } 

 if (HttpContext.Current.Session != null)
 {
 if (HttpContext.Current.Session["DATABASE"] != null)
 strDBName = HttpContext.Current.Session["DATABASE"].ToString();
 if (HttpContext.Current.Session["LoginUser"] != null)
 strLoginUser = HttpContext.Current.Session["LoginUser"].ToString();
 }
 strLogFormat = "<TR><TD>" + strDBName + "</TD><TD>" + strLoginUser + "</TD><TD>" + DateTime.Now.ToString() + "</TD><TD>" + strDLLName + "</TD><TD>" + strErrorIn + "</TD><TD>" + strFileName + "</TD><TD align=center>" + strFileLocation + "</TD><TD>" + strErrMethodName + "</TD><TD>" + strErrMessage + "</TD><TD>" + strLineNo + "</TD></TR>";

 sw.WriteLine(strLogFormat);
 sw.Close();
 }

Step 6: How to call this method in our website

in codebehind events, (ex. button click)

try
 {
 throw new Exception("dotnetpgm Exception");
 }
 catch (Exception ex)
 {
 General objGeneral = new General();
 objGeneral.GetErrorDetails(ex);
 Response.Redirect("ErrorPage.aspx");
 }

Step 7: for catching the Application errors add the code in Global.asax

you can create Global.asax by add new item in the website

protected void Application_Error(object sender, EventArgs e)
 {
 General objGeneral = new General();
 Exception objErr = Server.GetLastError().GetBaseException();
 objGeneral.GetErrorDetails(objErr);
 }

Captcha validation in Asp.net 2.0

Captcha validation in Asp.net 2.0.

Before Entering to topic first we must understand about the validation.Why most of the sites are validating the data’s we entered.Like we gave a name with numeric values and special characters like.So these things are really wrong information by mistake wrongly typed.In email id most of the websites how they validate means they see the email id contains ‘@’ followed with some words and having ‘.’ symbol. So we have to give the informations correctly.

Ok, Let us come to the Topic.
most of the web sites having the Captcha validation to their sites.

What is a Captcha code?

Captcha code contains a char and integer values with mixed mode. It is used for validating this code was really typed by the human.

How to create our own captcha code in Asp.net 2.0

First create an image button in a Asp.net web page and in the imageurl give the capthanew.aspx. like this,

<asp:imagebutton id="ImageButton1" runat="server" width="105px" height="35px" imageurl="~/capthanew.aspx">

<asp:TextBox ID="txtcaptha" runat="server" Width="105px" MaxLength="6" CssClass="txtbx2"></asp:TextBox>

<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />

give a text box to enter the captcha text and also a button.

download the capthanew.aspx file from here Download

save the file in your website folder.

In aspx.cs file go to the btnSubmit_Click event to write the validation to check the user given code and captcha code are same.

if (Page.IsValid && (txtcaptha.Text.ToString() != Session["RandomStr"].ToString()))
            {
                Response.Write("Captcha code was wrong.");
            }

This is the implementation of a captcha code if you want to generate the code dynamically means just give a linkbutton near to the Captcha imagebutton and give the path to capthanew.aspx this will give a dynamic code whenever you reload the page by linkbutton.

Actually how this captcha code works means, we just create a random numbers and characters and create a bitmap image and render these two things. We can give our own color also.