Recipe 13.4. Pinpointing the Cause of an Exception


Problem

You want to identify problems only when an exception occurs.

Solution

Dynamically turn on page-level tracing from within the Catch block of your exception handler and write to the trace log.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Set Page.Trace.IsEnabled = true in the Catch block of your exception handler.

  2. Write to the trace log by using a TRace.Write of the form TRace.Write("Exception", "Message", exc).

Figure 13-3 shows the appearance of some exception information in the trace sequence. Examples 13-4, 13-5 through 13-6 show the .aspx file and VB and C# code-behind files for the application that produces this result.

Discussion

ASP.NET processes and displays trace statements only when tracing is enabled. However, what if you don't want to see the trace log all the time but only when an exception occurs? The answer is to turn tracing on dynamically for the page. You can then write the exception information to the trace log and debug the problem from there.

Our example that illustrates this solution is primitive, in that it forces an exception. Though this is not something you would normally do in production code, it does allow us to show the infrastructure needed to control tracing at runtime.

When the exception occurs, the exception handler enables the trace output by setting TRace.IsEnabled to true. For the exception information to appear in the trace sequence, you must use a TRace.Write of the form trace.Write("Exception", "Message", exc) where exc is the Exception object defined in the catch statement.

Additionally, the code limits who sees the trace sequence, something you might want to consider if you are loathe to show tracing information to remote users when an exception occurs. Before activating tracing, the program checks to see whether the application is being run from the local machine (i.e., the browser making the request is on the machine serving the request). It does so by using the Request object to get the local IP address from the server variables. It compares this local address to the loopback address, a special IP number (127.0.0.1) that is designated for the software loopback interface of a machine. If it is not equal to the loopback address, a further comparison will be made to see if the local IP address from the server variables is the same as the local IP address that accompanied the request. The results of the comparison are used to determine whether to enable tracing and display the exception information in the trace sequence.

Figure 13-3. Exception information in the trace sequence


The URLs for page requests on the local machine can be in the form http://localhost/site/page or http://<server>/site/page (where <server> is the local server name), so it is necessary to check for the loopback IP address as well as the IP address. If the page were requested using the server name in the URL, it would not be detected as a local request if the second check were not performed.


See Also

Search IPAddress.IsLoopback method in the MSDN library for another similar approach.

Example 13-4. Pinpointing the cause of an exception (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH13TestDynamicPageTracingVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH13TestDynamicPageTracingVB" Title="Test Dynamic Page Tracing" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Pinpointing the Cause of an Exception (VB) </div> <table width="90%" align="center" border="0"> <tr> <td align="center" > <br /> <input  runat="server" type="checkbox" /> Show Only If Request Is Local </td> </tr> <tr> <td align="center"> <br /> <input  runat="server" type="button" value="Cause Exception" onserverclick="btnCauseException_ServerClick" /> </td> </tr> </table> </asp:Content> 

Example 13-5. Pinpointing the cause of an exception code-behind (.vb)

 Option Explicit On Option Strict On Imports System Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH13TestDynamicPageTracingVB.aspx ''' </summary> Partial Class CH13TestDynamicPageTracingVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the cause exception ''' button click event. It is responsible for causing an exception ''' to demonstrate dynamic tracing ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnCauseException_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim list As ArrayList Try 'force an exception by accessing the list without creating it first list.Add(0) Catch exc As Exception 'enable tracing and output the exception information If ((Not chkOnlyLocal.Checked) OrElse _ ((chkOnlyLocal.Checked) And (requestIsFromLocalMachine( )))) Then Trace.IsEnabled = True Trace.Write("Exception", _ "Demonstration of dynamic tracing", _ exc)   End If End Try End Sub 'btnCauseException_ServerClick '''*********************************************************************** ''' <summary> ''' This routine checks to see if the page request came from the local ''' machine. ''' </summary> ''' ''' <returns>True if the request is from the local machine. Else, False ''' </returns> ''' ''' <remarks> ''' NOTE: Since requests on a local machine can be in the form ''' http://localhost/site/page or http://server/site/page, ''' two checks are required. The first is for the localhost ''' loopback IP address (127.0.0.1) and the second is for the actual ''' IP address of the requestor. ''' </remarks> Private Function requestIsFromLocalMachine( ) As Boolean Dim isLocal As Boolean Dim localAddress As String ' Is browser fielding request from localhost? isLocal = Request.UserHostAddress.Equals("127.0.0.1") If (Not isLocal) Then ' Get local IP address from server variables localAddress = Request.ServerVariables.Get("LOCAL_ADDR") ' Compare local IP with IP address that accompanied request isLocal = Request.UserHostAddress.Equals(localAddress) End If Return (isLocal) End Function 'IsRequestFromLocalMachine End Class 'CH13TestDynamicPageTracingVB End Namespace 

Example 13-6. Pinpointing the cause of an exception code-behind (.cs)

 using System; using System.Collections; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH13TestDynamicPageTracingCS.aspx /// </summary> public partial class CH13TestDynamicPageTracingCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the cause exception /// button click event. It is responsible for causing an exception /// to demonstrate dynamic tracing /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnCauseException_ServerClick(object sender, System.EventArgs e) { ArrayList list = null; try { // force an exception by accessing the list without creating it first list.Add(0); } // try catch (Exception exc) { // enable tracing and output the exception information if ((!chkOnlyLocal.Checked) || ((chkOnlyLocal.Checked) &&(requestIsFromLocalMachine( )))) { Trace.IsEnabled = true; Trace.Write("Exception", "Demonstration of dynamic tracing", exc); } } // catch } // btnCauseException_ServerClick ///*********************************************************************** /// <summary> /// This routine checks to see if the page request came from the local /// machine. /// </summary> /// /// <returns>True if the request is from the local machine. Else, False /// </returns> /// /// <remarks> /// NOTE: Since requests on a local machine can be in the form /// http://localhost/site/page or http://server/site/page, /// two checks are required. The first is for the localhost /// loopback IP address (127.0.0.1) and the second is for the actual /// IP address of the requestor. /// </remarks> private Boolean requestIsFromLocalMachine( ) { Boolean isLocal; string localAddress; // Is browser fielding request from localhost? isLocal = Request.UserHostAddress.Equals("127.0.0.1"); if (!isLocal) { // Get local IP address from server variables localAddress = Request.ServerVariables.Get("LOCAL_ADDR"); // Compare local IP with IP address that accompanied request isLocal = Request.UserHostAddress.Equals(localAddress); } return (isLocal); } // IsRequestFromLocalMachine } // CH13TestDynamicPageTracingCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net