What is Debugging?
Debugging allows programmers to see how the code works systematically, how the values of variables change, how objects are created and destroyed, etc. Debugging is the method of inserting breakpoints, and the breakpoints are used to pause running a program from running.
Let us take an example to understand Debugging. The program displays a text “debugging is running” to the user.
Suppose when we run the application, the string is not displayed. To find the problem, we need to add a breakpoint to the code line that displays the string. This breakpoint will then pause the execution of the program, and the programmer can see what is possibly going wrong. The programmer rectifies the program accordingly.
In the following example, we will see
- How to display a string for the demo request.
- How to create an interface breakpoints
- Use this breakpoint to debug the query.
Step 1: Ensure we have opened our visual Studio and ensure our project file is open.
Step 2: Open WebForm1.aspx.cs File and write code.
namespace DataProject { public partial class WebForm1 : System.Web.UI.Page { protected void PageLoad(object sender, EventArgs e) { Response.Write("debugging is running"); } } }
Step 3: Step 3: Now, we will add a breaking point. To add a breakpoint, click on the column where you want the breakpoint to be inserted. Therefore, in our case, we want our program to stop at the code line “Response.Write”.
Once done, you will see that the code is marked in red. Also, a red bubble will be visible in the column next to the code line.
Multiple Breakpoints can also be added in a program.
Step 4: Now, run your program in Debug mode by choosing the menu option Debug and click on Start Debugging.
Output:
When all the Debug execution steps are completed, then visual studio marks breakpoint yellow. If the programmer thinks that the code is incorrect, the execution can be stopped.
What is Tracing?
Tracing follows the execution path and show the diagnostic information related to a specific Asp. Net web page or program on the webserver. Tracing also tracks irregular incidents during the execution of an application and helps during training and after delivery to identify problems. In case of unusual trace log events, an application may also write a message using Trace class. It also allows you to view a single request diagnostic information for an ASP.NET page.
Tracing is disabled by default in Asp. Net. Tracing can be done at two levels:
- Page-Level Tracing: We can control whether tracing is enabled or disabled for individual pages. If tracing is enabled, when the page is requested, ASP.NET appends to the page a series of tables containing execution details about the page request.
- Application Level Tracing: Application-level tracing allows enabling tracing for an entire application, and the tracing information will not be displayed on the page. It is collected and stored in memory for a short amount of time. We can review the recently traced information by requesting a special URL.
Application Level Tracing:
Let us look at how to enable Application-Level Tracing.
Step 1: Open the web.config file of your project.
Step 2: Now add the below code in the file.
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.5.2"/> <httpRuntime targetFramework="4.5.2"/> <trace enable="true" pageOutput="false" requestLimit="50" localOnly="false"/> </system.web> </configuration>
RequestLimit is used with a tag trace to specify the number of pages to be traced.
Step 3: Run Your Project for output.
If you open the URL – http://localhost:55687/trace.axd, you will see the information for each request and any errors that occur in an application. The following information are shown:
- The time of the request.
- The name of the web page that is being requested.
- The status code of the web request. (status code 200 implies that the request is successful).
- The View details that allows you to view more details about the web request. One important detailed information is the header information that shows what is the information sent in the header of each web request.
Page-Level Tracing:
Page tracing shows all the information about a web page being processed and is useful in debugging if the page does not work for any reason.
Visual Studio provides detailed information about various aspects of the page such as the time for each method that is used in the web request. If your web application is facing a performance issue, this information can be used to debug the problem and is displayed when the application run’s in Visual Studio.
It is enabled by using including Trace=”true” in <%@ Page Title=”” Language=”C#”…%> directive.
Let us look at how to enable tracing for an application at a page level.
Step 1: Let us work on our data project. Open the WebForm1.aspx file from the Solution Explorer.
Step 2: Add the below code to enable page tracing.
<%@ Page Language="C#" Trace="true" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DataProject.Demo" %> <!DOCTYPE html> <html xmlns="https://www.w3.ore/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server”> </form> </body> </html>
Output:
Displaying a Custom Error Page:
In ASP.Net, you also have custom error pages displayed to the users. If an application contains any error, a custom page will display this error page to the user.
In the below example, we will first add an HTML page that will display a text “We are looking into the problem.” We will then add some error codes to our demo.aspx so that the error page is displayed.
Let us follow the below-mentioned steps:
Step 1: Let us work on our DemoApplication. Let us add an HTML page to the application. Right-click on the DemoApplication in Solution Explorer. Choose the menu option Add > HTML Page.
Step 2: Next we will provide a name to the new HTML page. Provide the name as ‘ErrorPage.’ Click the ‘OK’ button to proceed.
Step 3: Add the line “We are looking into the problem” to the HTML page.
<!DOCTYPE html> <html xmlns="https://www.w3.ore/1999/xhtml"> <head runat="server"> <title></title> </head> <body> We are looking into the problem </body> </html>
Step 4: Now make a change in the web.config file that will notify whenever an error occurs in the application.
The customErrors tag allows defining a custom error page.
<configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <httpRuntime targetFramework="4.0” /> <customErrors mode="On" defaultRedirect="ErrorPage.html"> </customErrors> </system.web> </configuration>
- DefaultRedirect: Here we will pass the URL of the custom error page if we want to redirect to our custom error page instead of that annoying Yellow Screen Of Death(YSOD).
- Mode: There are three modes depending upon where the user visited that screen locally or remotely:
- On: Custom error page or runtime YSOD is visible to local and remote users.
- Off: Exception details YSOD are visible to local and remote users when an exception occurs.
- RemoteOnly: Custom error or runtime errors YSOD is shown to all the users (visitors), whether local or remote.
Step 5: Now, let us add some faulty code to the demo.aspx.cs page. Open this page by double-clicking the file in Solution Explorer. Add the below code to the file Demo.aspx.cs. These lines are designed to read the lines of a text from a file and is supposed to be located in the drive D with the name Example.txt.
However, in our situation, this file does not exist. Therefore, this code will result in an error page when the application runs.
namespace DemoApplication { public partial class Demo : System.Web.UI.Page { protected void PageLoad(object sender, EventArgs e) { String path = @"D:\Example.txt"; string[] lines; lines = File.ReadAllLines(path); } } }
Now execute the code in Visual Studio to get the below output.
The above image shows that an error was triggered in the application and thus the Error.html page is displayed to the user.
ASP.NET Unhandled Exception:
Suppose if a user browses the wrong page in the application that cannot be predicted. In those cases, ASP.Net can redirect the user to the page errorpage.html.
Let us see an example on this. We are going to use our same ‘DemoApplication,’ which has the page Errorpage.html. We will then try to view a web page that does not exist in our application.
We should be then redirected to our ErrorPage.html page in this case. Let us now see the steps to achieve this.
Step 1: Let’s work on our DemoApplication. Open the Global.asax.cs file from the Solution Explorer.
The global.asax.cs file is used to add the code that will be applicable throughout all pages in the application.
Step 2: Add the code to the global.asax.cs. These lines are used to check for errors and display the page ErrorPage.html accordingly.
namespace DemoApplication { public partial class Demo : System.Web.UI.Page { protected void ApplicationError(object sender, EventArgs e) { HttpException lastErrorWrapper = Server.GetLastError() as HttpException; if(lastErrorWrapper.GetHttpCode() == 404) Server.T ransfer("~/ErrorPage.html"); } } }
Here, the ApplicationError event handler is called whenever an error occurs in an application. The event name has to be ApplicationError.
Next, we will define an object of the class type HttpException that will hold all the details of the error. We then use the Server.GetLastError method to get all details of the last error which has occurred in the application.
We will then check if the error code of the last error is 404. (The error code 404 is actually a standard code that is returned when a user browses to a page which is not found). We will then transfer the user to the page ErrorPage.html if the error code matches.
Now run the code in Visual Studio to get the below output.
Browse the URL http://localhost:53003/Demo1.aspx. Since the Demo1.aspx does not exist in our application. You will then get the below output.
ASP.NET Error logging:
Logging the application errors helps the developer to debug and resolve the error at a later point of time and is done in the Global.asax.cs file when the error is captured. During the process of capturing, the error message can be written into the log file.
Let us see an example where we are going to use our same DemoApplication, which has Errorpage.html. And we are trying to view a web page that does not exist in our application. Here, we should be redirected to our ErrorPage.html page. Let us see the steps to achieve this.
Step 1: Let us work on our DemoApplication. Open the Global.asax.cs file from the Solution Explorer.
Step 2: Add the code to the global.asax.cs that will check for errors and display the ErrorPage.html page. Also, we will log the error details in a file called AllErrors.txt. In the below example, we will write code to have this file created on the D drive.
namespace DemoApplication { public partial class Demo : System.Web.UI.Page { protected void ApplicationError(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"); } } }
Here, the first line is to get the error itself by using the Server.GetLastError method. This is then assigned to the variable exc.
We will then create an empty string variable called str. We can get the actual error message using the exc.Message property that will have the exact message for any error which occurs while running the application which is then assigned to the string variable.
Next, we will define the file called AllErrrors.txt where all the error messages will be sent. We write the string str that contains all the error messages to this file.
Finally, we will transfer the user to the ErrorPage.html file.
Output:
Browse the URL http://localhost:53003/Demo1.aspx. Since the Demo1.aspx does not exist in our application, we should get the below output.
If you open the AllErrors.txt file, you will see the below information.
The error message can then be passed to the developer at a later point in time for debugging purposes.