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.
using System; using System.Web; namespace Chapter6 { public class TestClass { public void DoStuff() { HttpContext.Current. Trace.Write ("Component", "I'm inside the component"); } } } |
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 Class End 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.
<%@ 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> |
<%@ 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.
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.