Asp.Net Page Level Tracing, Debugging, Error Handling [Example]

In any application, errors are bound to occur during the development process. It is important to be able to discover errors at an early stage.

In Visual Studio, it is possible to do this for ASP.Net applications. Visual Studio is used for Debugging and has error handling techniques for ASP.Net.

What is Debugging in ASP.NET?

Debugging is the process of adding breakpoints to an application. These breakpoints are used to pause the execution of a running program. This allows the developer to understand what is happening in a program at a particular point in time.

Let’s take an example of a program. The program displays a string “We are debugging” to the user. Suppose when we run the application, for some reason, the string is not displayed. To identify the problem we need to add a breakpoint. We can add a breakpoint to the code line which displays the string. This breakpoint will pause the execution of the program. At this point, the programmer can see what is possibly going wrong. The programmer rectifies the program accordingly.

Here in the example, we will use our ‘DemoApplication’ that was created in earlier chapters. In the following example, we will see

  • How to make the demo application display a string.
  • How to add breakpoints to an application.
  • How to debug the application using this breakpoint.

How To Debug an application in ASP.NET

Below are the steps to make a demo application, add breakpoints and debug in ASP.Net:

Step 1) Open the application in Visual Studio
Let’s first ensure we have our web application open in Visual Studio. Ensure the DemoApplication is open in Visual Studio.

 Debug an application in ASP.NET

Step 2) Now open the Demo.aspx.cs file and add the below code line.

  • We are just adding the code line Response.Write to display a string.
  • So when the application executes, it should display the string “We are debugging” in the web browser.

 Debug an application in ASP.NET

namespace DemoApplication
{  
  public partial class Demo : System.Web.UI.Page  
		{  
		  protected void Page_Load(object sender, EventArgs e)  
		  {
		    Response.Write("We are debugging"); 
		  }
		}
}

Step 3) Add a breakpoint to the application
A breakpoint is a point in Visual Studio where you want the execution of the program to stop.

 Debug an application in ASP.NET

  1. To add a breakpoint, you need to click the column where you want the breakpoint to be inserted. So in our case, we want our program to stop at the code line “Response.Write”. You don’t need to add any command to add a breakpoint. You just need to click on the line on which you want to add a breakpoint.
  2. Once this is done, you will notice that the code gets marked in red. Also, a red bubble comes up in the column next to the code line.

Note: – You can add multiple breakpoints in an application

Step 4) Run application in Debugging mode
Now you need to run your application using Debugging Mode. In Visual Studio, choose the menu option Debug->Start Debugging.

 Debug an application in ASP.NET

Output:-

 Debug an application in ASP.NET

When you perform all the steps correctly, the execution of the program will break. Visual Studio will go to the breakpoint and mark the line of code in yellow.

Now, if the programmer feels that the code is incorrect, the execution can be stopped. The code can then be modified accordingly. To continue proceeding the program, the programmer needs to click the F5 button on the keyboard.

What is Tracing in ASP.NET?

Application tracing allows one to see if any pages requested results in an error. When tracing is enabled, an extra page called trace.axd is added to the application. (See image below). This page is attached to the application. This page will show all the requests and their status.

Tracing in ASP.NET

How to Enable tracing for an application in ASP.NET

Let’s look at how to enable tracing for an ASP.Net application:

Step 1) Let’s work on our ‘DemoApplication’. Open the web.config file from the Solution Explorer.

 Enable tracing for an application in ASP.NET

Step 2) Add the below line of code to the Web.config file.

The trace statement is used to enable tracing for the application.

  • The ‘requestLimit’ in trace statement is used. It specifies the number of page requests that has to be traced.
  • In our example, we are giving a limit of 40. We give limit because a higher value will degrade the performance of the application.

Enable tracing for an application in ASP.NET

<?xml version="1.0" encoding="utf-8"?>
<! --
For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 
-->
<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0" />
		<httpRuntime targetFramework="4.0” />
		
		 <trace enable="true" pageOutput="false" requestLimit="40" localOnly="false"/>
		
	</system.web>
</configuration>

Run the “demoapplication” in Visual Studio.

Output:-

 Enable tracing for an application in ASP.NET

If you now browse to the URL – http://localhost:53003/trace.axd , you will see the information for each request. Here you can see if any errors occur in an application. The following types of information are shown on the above page

  1. The time of the request for the web page.
  2. The Name of the web page being requested.
  3. The status code of the web request. (status code of 200 means that the request is successful).
  4. The View details which you allow to view more details about the web request. An example of this is shown below. One important detailed information provided is the header information. This information shows what is the information sent in the header of each web request.

Enable tracing for an application in ASP.NET

Page Level Tracing in ASP.NET

Page Level Tracing in ASP.Net shows all the general information about a web page when it is being processed. This is useful in debugging if a page does not work for any reason. Visual Studio provides detailed information about various aspects of the page and information such as the time for each method that is called in the web request.

For example, if your web application is having a performance issue, this information can help in debugging the problem. This information is displayed when the application run’s in Visual Studio.

How to Enable tracing at Page level in ASP.NET

Let’s look at how to enable page level tracing for an ASP.Net application:

Step 1) Let’s work on our DemoApplication. Open the demo.aspx file from the Solution Explorer

Page Level Tracing in ASP.NET

Step 2) Add the below line of code to enable page tracing. In the Page declaration, just append the line Trace=”true”. This code line will allow page level tracing.

Page Level Tracing in ASP.NET

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="DemoApplication.Demo" %>

	<!DOCTYPE html>
<html xmlns="http://www.w3.ore/1999/xhtml">
<head runat="server">
	<title></title>
</head>	
	<body>
	  <form id="form1" runat="server”>
	  </form>
</body>
</html>

Run the application in Visual Studio.

Output:-

Page Level Tracing in ASP.NET

Now when the web page Demo.aspx is displayed, you will get a whole lot of information about the page. Information such as the time for each aspect of the page lifecycle is displayed on this page.

Error Handling: Displaying a Custom Error Page

In ASP.Net, you can have custom error pages displayed to the users. If an application contains any sort of error, a custom page will display this error to the user.

In our example, we are first going to add an HTML page. This page will display a string to the user “We are looking into the problem”. We will then add some error code to our demo.aspx page so that the error page is shown.

Let’s follow the below mentioned steps

Step 1) Let’s work on our DemoApplication. Let’s add an HTML page to the application

  1. Right-click on the DemoApplication in Solution Explorer
  2. Choose the menu option ‘Add’->HTML Page

Error Handling in ASP.Net

Step 2) In the next step, we need to provide a name to the new HTML page.

  1. Provide the name as ‘ErrorPage.’
  2. Click the ‘OK’ button to proceed.

Error Handling in ASP.Net

Step 3) The Errorpage will automatically open in Visual Studio. If you go to the Solution Explorer, you will see the file added.

Error Handling in ASP.Net

Add the code line “We are looking into the problem” to the HTML page. You don’t need to close the HTML file before making the change to the web.config file.

Error Handling in ASP.Net

<!DOCTYPE html>
<html xmlns="http://www.w3.ore/1999/xhtml">
<head runat="server">
	<title></title>
</head>	
	<body>
	  We are looking into the problem
	</body>
</html>

Step 4) Now you need to make a change in the web.config file. This change will notify that whenever an error occurs in the application, the custom error page needs to be displayed.

The ‘customErrors’ tag allows defining a custom error page. The defaultRedirect property is set to the name of our custom error’s page created in the previous step.

Error Handling in ASP.Net

<configuration>
	<system.web>
		<compilation debug="true" targetFramework="4.0" />
		<httpRuntime targetFramework="4.0” />
		
		 <customErrors mode="On" defaultRedirect="ErrorPage.html">
</customErrors>

		
	</system.web>
</configuration>

Step 5) Now let’s add some faulty code to the demo.aspx.cs page. Open this page bydouble-clickingg the file in Solution Explorer

Error Handling in ASP.Net

Add the below code to the Demo.aspx.cs file.

  • These lines of code are designed to read the lines of a text from a file.
  • The file is supposed to be located in the D drive with the name ‘Example.txt.’
  • But in our situation, this file does not really exist. So this code will result in an error when the application runs.

Error Handling in ASP.Net

namespace DemoApplication
{  

  public partial class Demo : System.Web.UI.Page  
		{  
		  protected void Page_Load(object sender, EventArgs e)  
		  {
		   String path = @"D:\Example.txt";
		   string[] lines;
		   lines = File.ReadAllLines(path);
		  }
		}
}

Now execute the code in Visual Studio and you should get the below output.

Output:-

Error Handling in ASP.Net

The above page shows that an error was triggered in the application. As a result, the Error.html page is displayed to the user.

ASP.NET Unhandled Exception

Even in the best of scenarios, there can be cases of errors which are just not forseen.

Suppose if a user browses to the wrong page in the application. This is something that cannot be predicted. In such cases, ASP.Net can redirect the user to the errorpage.html.

Let’s see an example on this.

  • We are going to use our same ‘DemoApplication’ which has the Errorpage.html.
  • And we will try to view a web page which does not exist in our application.
  • We should be redirected to our ErrorPage.html page in this case. Let’s see the steps to achieve this.

Step 1) Let’s work on our DemoApplication. Open the Global.asax.cs file from the Solution Explorer

ASP.NET Unhandled Exception

NOTE: The global.asax.cs file is used to add code that will be applicable throughout all pages in the application.

Step 2) Add the below line of code to the global.asax.cs. These lines will be used to check for errors and display the ErrorPage.html page accordingly.

ASP.NET Unhandled Exception

namespace DemoApplication
{  

  public partial class Demo : System.Web.UI.Page  
		{  
		  protected void Application_Error(object sender, EventArgs e)  
		  {
		?    HttpException lastErrorWrapper = Server.GetLastError() as HttpException;

			if(lastErrorWrapper.GetHttpCode() == 404)
			Server.T ransfer("~/ErrorPage.html");
		  }
		}
}

Code Explanation:-

  1. The first line is the Application_Error event handler. This event is called whenever an error occurs in an application. Note that the event name has to be ‘Application_Error’. And the parameters should be as shown above.
  2. Next, we define an object of the class type HttpException. This is a standard object which will hold all the details of the error. We then use the Server.GetLastError method to get all the details of the last error which occurred in the application.
  3. We then check if the error code of the last error is 404. (The error code 404 is the standard code returned when a user browses to a page which is not found). We then transfer the user to the ErrorPage.html page if the error code matches.

Now run the code in Visual Studio and you should get the below output

Output:-

Browse the page http://localhost:53003/Demo1.aspx . Remember that Demo1.aspx does not exist in our application. You will then get the below output.

Unhandled Exception in ASP.NET

The above page shows that an error was triggered in the application. As a result, the Error.html page is displayed to the user.

ASP.NET Error logging

By logging application errors, it helps the developer to debug and resolve the error at a later point of time. ASP.Net has the facility to log errors. This is done in the Global.asax.cs file when the error is captured. During the capturing process, the error message can be written into a log file.

Let’s see an example on this.

  • We are going to use our same DemoApplication which has the Errorpage.html.
  • And we will try to view a web page which does not exist in our application.
  • We should be redirected to our ErrorPage.html page in this case.
  • And at the same time, we will write the error message to a log file. Let’s see the steps to achieve this.

Step 1) Let’s work on our DemoApplication. Open the Global.asax.cs file from the Solution Explorer

ASP.NET Error logging

Step 2) Add the below line of code to the global.asax.cs. It will check for errors and display the ErrorPage.html page accordingly. Also at the same time, we will log the error details in a file called ‘AllErrors.txt.’ For our example, we will write code to have this file created on the D drive.

ASP.NET Error logging

namespace DemoApplication
{  

  public partial class Demo : System.Web.UI.Page  
		{  
		  protected void Application_Error(object sender, EventArgs e)  
		  {
		   Exception exc = Server.GetLastError();
		   String str ="";
		   str = exc.Message;
		   
		   String path = @"D:\AllErrors.txt";
		  File.WriteAllTest(path,str);
		  Server.trrasfer("~/ErrorPage.html");
		  }
		}
}

Code Explanation:-

  1. The first line is to get the error itself by using the ‘Server.GetLastError’ method. This is then assigned to the variable ‘exc’.
  2. We then create an empty string variable called ‘str’. We get the actual error message using the ‘exc.Message’ property. The exc.Message property will have the exact message for any error which occurs when running the application. This is then assigned to the string variable.
  3. Next, we define the file called ‘AllErrrors.txt.’ This is where all the error messages will be sent. We write the string ‘str’ which contains all the error messages to this file.
  4. Finally, we transfer the user to the ErrorPage.html file.

Output:-

Browse the page http://localhost:53003/Demo1.aspx . Remember that Demo1.aspx does not exist in our application. You will then get the below output.

ASP.NET Error logging

And at the same time, if you open the ‘AllErrors.txt’ file you will see the below information.

ASP.NET Error logging

The error message can then be passed on to the developer at a later point in time for debugging purposes.

Summary

  • ASP.Net has the facility to perform debugging and Error handling.
  • Debugging can be achieved by adding breakpoints to the code. One then runs the Start with Debugging option in Visual Studio to debug the code.
  • Tracing is the facility to provide more information while running the application. This can be done at the application or page level.
  • At the page level, the code Trace=true needs to be added to the page directive.
  • At the application level, an extra page called Trace.axd is created for the application. This provides all the necessary tracing information.