Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Tracing via Components

The Page object in your ASP.NET pages contains an instance of the TraceContext class, making it easy to write trace information from your ASP.NET page. But what if you want to write trace information from within a component? Luckily, the .NET Framework makes this task equally easy. Let's take a look at how this would be done. First, you need to build your simple component. Listings 6.11 and 6.12 present the component.

Listing 6.11 Component That Leverages ASP.NET Tracing (C#)

using System;
using System.Web;
namespace Chapter6
{
   public class TestClass
   {
      public void DoStuff()
      {
         HttpContext.Current.Trace.Write
            ("Component", "I'm inside the component");
      }
   }}

Listing 6.12 Component That leverages ASP.NET Tracing (Visual Basic .NET)

Imports System
Imports System.Web
Namespace Chapter6
   Public Class TestClass
      Public Sub DoStuff()
         HttpContext.Current.Trace.Write _
            ("Component", "I'm inside the component")
      End Sub
   End ClassEnd Namespace

Next, compile your component using one of the following compile scripts. The first is for C#, and the second is for Visual Basic .NET.

csc /t:library /out:Chapter6.dll /r:System.Web.dll Chapter6.cs

or

vbc /t:library /out:Chapter6.dll /r:System.Web.dll Chapter6.vb

Finally, you can see that this works by using it in an ASP.NET page.

Listing 6.13 Using Trace-Enabled Component in an ASP.NET Page (C#)

<%@ Page Language="C#" Trace="true" %>
<%@ Import Namespace="Chapter6" %>
<script language="C#" runat="server">
   protected void Page_Load(object Sender, EventArgs e)
   {
      TestClass tc = new TestClass();
      tc.DoStuff();
   }</script>

Listing 6.14 Using Trace-Enabled Component in an ASP.NET Page (Visual Basic .NET)

<%@ Page Language="Visual Basic" Trace="true" %>
<%@ Import Namespace="Chapter6" %>
<script language="Visual Basic" runat="server">
   Protected Sub Page_Load(Sender As Object, e As EventArgs)
      Dim tc As TestClass = New TestClass()
      tc.DoStuff()
   End Sub</script>

When you run this code, you'll get results like those shown in Figure 6.13.

Figure 6.13 Viewing trace information written to the trace output from within a component.

Inside the Trace Information section, you'll see the trace message "I'm inside the component," with a category of Component that was added from within the component. This can be a powerful tool for finding bugs in your ASP.NET web applications.

  • + Share This
  • 🔖 Save To Your Account