Tracing

   


Implement tracing.

  • Configure and use trace listeners and trace switches.

  • Display trace output.

Instrument and debug a Windows service, a serviced component, a .NET Remoting object, and an XML Web service: Create and apply debugging code to components and applications.

The process of testing can reveal the presence of errors in a program; but to find the actual cause of a problem, you sometimes need the program to generate information about its own execution. Analysis of this information might help you understand why the program is behaving in a particular way and might lead to a possible resolution of the error.

This process of collecting information about program execution is called tracing . You can trace a program's execution in Visual Basic .NET by generating messages about the program's execution with the use of the Debug and Trace classes.

The Trace and Debug classes have several things in common:

  • They both belong to the System.Diagnostics namespace.

  • They have members with the same names .

  • All their members are static.

  • They are conditionally compiled (that is, their statements are included in the object code only if a certain symbol is defined).

The only difference between the Debug and Trace classes is that the members of the Debug class are conditionally compiled, but only when the DEBUG symbol is defined. On the other hand, members of the Trace class are conditionally compiled, but only when the TRACE symbol is defined.

Visual Basic .NET provides two basic configurations for a project: Debug and Release . Debug is the default configuration. When you compile a program by using the Debug configuration, both TRACE and DEBUG symbols are defined, as shown in Figure 9.2. When you compile a program in the Release configuration, only the TRACE symbol is defined. You can switch between the Debug and Release configurations using the Solution Configurations combo box on the standard toolbar (as shown in Figure 9.3) or by using the Configuration Manager dialog box (as shown in Figure 9.4) from the project's Property Pages dialog box.

Figure 9.2. Both the TRACE and DEBUG symbols are defined in the Debug configuration.

Figure 9.3. The standard toolbar of Visual Studio .NET contains a Solution Configurations combo box to allow users to easily change the solution configuration.

Figure 9.4. The Configuration Manager dialog box allows you to set configuration properties for the projects in a solution.

Later in this chapter, you will learn how to make these changes from within the programthrough command-line compilation options and configuration files.

When you compile a program by using the Debug configuration, the code that uses the Debug and the Trace classes is included in the compiled code. When you run such a program, both the Debug and Trace classes generate messages. On the other hand, when a program is compiled by using the Trace configuration, it does not include any calls to the Debug class. Thus, when such a program is executed, you get only the messages generated by using the Trace class.

Table 9.1 summarizes the members of both the Trace and Debug classes.

Table 9.1. Members of Debug and Trace Classes

Member

Type

Description

Assert

Method

Asserts that a particular logical condition evaluates to True at runtime. If not, it displays a message.

AutoFlush

Property

Automatically calls the Flush method after every write to the Listeners collection.

Close

Method

Severs the connection with the Listeners collection after flushing any remaining output.

Fail

Method

Displays an error message.

Flush

Method

Writes all buffered data to the Listeners collection.

Indent

Method

Increments the IndentLevel property.

IndentLevel

Property

Specifies the indent level.

IndentSize

Property

Specifies the number of spaces in an indent.

Listeners

Property

The collection of Listener objects that will receive the trace output.

Unindent

Method

Decrements the IndentLevel property.

Write

Method

Writes the given information to the trace listeners in the Listeners collection.

WriteIf

Method

Writes the given information to the trace listeners in the Listeners collection only if a condition is true.

WriteLine

Method

Same as Write , but appends the information with a newline character.

WriteLineIf

Method

Same as WriteIf , but appends the information with a newline character.

NOTE

Tracing Helps in Resolving Hard-to-Reproduce Errors When programs run in a production environment, they sometimes report errors (mostly related to performance or threading problems) that are difficult to reproduce in a simulated testing environment. Tracing a production application can help you get runtime statistics for the program; this might help you in trapping these hard-to-reproduce errors.


Using Trace and Debug to Display Information

Step by Step 9.1 demonstrates how to use some of the methods of the Trace and Debug classes.

STEP BY STEP

9.1 Using the Trace and Debug Classes to Display Debugging Information

  1. Launch Visual Studio .NET. Select File, New, Blank Solution and name the new solution 310C09 .

  2. Add a new Visual Basic .NET Windows application named StepByStep9-1 to the solution.

  3. In the Solution Explorer, rename the default Form1.vb to FactorialCalculator.vb . Open the form in code view and change all occurrences of Form1 to refer to FactorialCalculator instead.

  4. Add four Label controls (including a control named lblHeading with an empty Text property), two TextBox controls ( txtNumber and txtFactorial ), and a Button control ( btnCalculate ) to the form and arrange the controls as shown in Figure 9.5.

    Figure 9.5. Design of a form that calculates the factorial of a given number.

  5. Switch to code view and add the following Imports directive:

     Imports System.Diagnostics 
  6. Double-click the Button control and add the following code to its Click event handler:

     Private Sub btnCalculate_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) _  Handles btnCalculate.Click     ' Write a debug message     Debug.WriteLine(_      "Inside Button Click event handler")     ' Start indenting messages now     Debug.Indent()     Dim intNumber As Integer = _      Convert.ToInt32(txtNumber.Text)     ' Make a debug assertion     Debug.Assert(intNumber >= 0, "Invalid value", _      "negative value in debug mode")     ' Write a trace assertion     Trace.Assert(intNumber >= 0, _      "Invalid value", _     "negative value in trace mode")     Dim intFac As Integer = 1     Dim intI As Integer     Try         For intI = 2 To intNumber             intFac = intFac * intI             ' Write a debug message             Debug.WriteLine(intI, _              "Factorial Program Debug, Value of intI")         Next     Catch ex As Exception         ' Write a trace message         ' if the condition is true         Trace.WriteLineIf(_          TypeOf ex Is System.OverflowException, _          "There was an overflow", _          "Factorial Program Trace")         ' Write a debug message         ' if the condition is true         Debug.WriteLineIf(_          TypeOf ex Is System.OverflowException, _          "There was an overflow", _          "Factorial Program Debug")     End Try     txtFactorial.Text = intFac.ToString()     ' Decrease the indent level     Debug.Unindent()     ' Write a debug message     Debug.WriteLine(_      "Done with computations, returning...") End Sub 
  7. Set the form as the startup form for the solution. Run the solution by pressing F5. Keep the program running and switch to the Visual Studio .NET Integrated Development Environment (IDE). Select View, Other Windows, Output. Push the pin on the title bar of the output window so that it does not hide automatically. Now switch to the running program; enter 5 in the text box and click the Calculate button. You should see tracing messages that are generated by the program (see Figure 9.6).

    Figure 9.6. Debug and Trace messages are always displayed by default in the Output window.

  8. Now switch to the running program, enter the value 100 and click the Calculate button. Messages from both the Debug class and the Trace class (overflow message) are displayed in the output window. Note that the default configuration is the Debug configuration, where both the TRACE and DEBUG symbols are defined.

  9. Enter a negative value, such as -1 , and click the Calculate button. This causes the assertion to fail, and you see a dialog box that shows an assertion failed message, as shown in Figure 9.7. This message box is generated by the Debug.Assert() method in the code. The dialog box gives you three choices: Abort, to terminate the program; Retry, to break the program execution so that you can debug the program; and Ignore, to continue the execution as if nothing has happened . Click Ignore, and you see another Assertion Failed dialog box. This one was generated by the Trace.Assert() method in the code. Click the Abort button to terminate the program execution.

    Figure 9.7. The Assertion Failed dialog box is displayed when an assertion made in the Assert() method fails.

  10. From the Solution Configurations combo box on the standard toolbar, select the Release configuration (remember, the Release configuration defines only the TRACE symbol). Run the program again. Enter the value 5 and click the Calculate button. The factorial is calculated, but no messages appear in the output window. Enter the value 100 and click the Calculate button. You should now see the overflow message generated by the Trace class in the output window. Finally, try calculating the factorial of -1 . You should see just one dialog box, showing an assertion failed message. Click the Abort button to terminate the program.

Note from Step by Step 9.1 that you can use the methods of the Debug and Trace classes (for example, the WriteIf() and WriteLineIf() methods) to display messages based on conditions. This can be a very useful technique if you are trying to understand the flow of logic of a program. Step by Step 9.1 also demonstrates the use of the Assert() method. The Assert() method tests your assumption about a condition at a specific place in the program. When an assertion fails, the Assert() method pinpoints the code that is not behaving according to your assumptions. A related method is Fail() ; the Fail() method displays a dialog box similar to the one that Assert() shows, but it does not work conditionally. The Fail() method signals unconditional failure in a branch of code execution.

Trace Listeners

Listeners are the classes responsible for forwarding, recording, and displaying the messages generated by the Trace and Debug classes. You can have multiple listeners associated with the Trace and Debug classes by adding Listener objects to their Listeners property. The Listeners property is a collection capable of holding any number of objects derived from the TraceListener class. Both the Debug and the Trace classes share the Listeners collection, so an object added to the Listeners collection of the Debug class is automatically available in the Trace class and vice versa.

The TraceListener class is an abstract class that belongs to the System.Diagnostics namespace. It has three implementations :

  • DefaultTraceListener An object of this class is automatically added to the Listeners collection. Its behavior is to write messages on the output window.

  • TextWriterTraceListener An object of this class can write messages to any class that derives from the Stream class which includes the console or a file.

  • EventLogTraceListener An object of this class writes messages to the Windows event log.

EXAM TIP

The Same Listeners for Debug and Trace Messages sent through the Debug and Trace objects are directed through each Listener object in the Listeners collection. Debug and Trace share the same Listeners collection, so any Listener object that is added to the Trace.Listeners collection is also added to the Debug.Listeners collection.


If you want a Listener object to perform differently from these three Listener classes, you can create your own class that inherits from the TraceListener class. When doing so, you must at least implement the Write() and WriteLine() methods.

Step by Step 9.2 shows how to create a custom listener class that implements the TraceListener class to send messages generated by the Debug and Trace class through email.

STEP BY STEP

9.2 Creating a Custom TraceListener Object

  1. Add a new Visual Basic .NET Windows application named StepByStep9-2 to the solution.

  2. Add a reference to System.Web.dll to the project.

  3. Add a new class to the project named EmailTraceListener.vb . Modify the class with the following code (changing the From address to an appropriate email address):

     Imports System Imports System.Diagnostics Imports System.Text Imports System.Web.Mail Public Class EmailTraceListener     Inherits TraceListener     ' Mmessage log will be sent to this address     Private mstrMailTo As String     ' Storage for the message log     Private mmessage As StringBuilder     Public Sub New(ByVal MailTo As String)         mstrMailTo = MailTo     End Sub     ' A custom listener must override Write method     Public Overloads Overrides Sub Write(_      ByVal message As String)         If mmessage Is Nothing Then             mmessage = New StringBuilder()         End If         mmessage.Append(message)     End Sub     ' A custom listener must override WriteLine method     Public Overloads Overrides Sub WriteLine(_      ByVal message As String)         If mmessage Is Nothing Then             mmessage = New StringBuilder()         End If         mmessage.Append(message)         mmessage.Append(vbCrLf)     End Sub     ' Use the close method to send the mail.     Public Overrides Sub Close()         Flush()         Dim msg As MailMessage = New MailMessage()         msg.To = mstrMailTo         msg.From = "Administrator@test"         msg.Subject = _          "Factorial Program Debug/Trace output"         If Not mmessage Is Nothing Then             msg.Body = mmessage.ToString()         Else             msg.Body = ""         End If         ' Send the mail         SmtpMail.Send(msg)     End Sub     Public Overrides Sub Flush()         ' Nothing much to do here         ' Just call the base class's implementation         MyBase.Flush()     End Sub End Class 

    NOTE

    Sending Email Messages The types in the System.Web.Mail namespace can be used from any managed application, including both Web and Windows applications. This functionality is supported only in the Windows 2000, Windows XP Professional, and Windows .NET Server operating systems. For other operating systems, you can send email messages by manually establishing an SMTP connection through the System.NET.TcpClient class. In addition, several component vendors sell custom SMTP client classes.

  4. In Solution Explorer, copy the FactorialCalculator.vb form from the StepByStep9-1 project to the current project. Change the Text property of the form to Factorial Calculator 9-2 . Set the form as the startup object for the project. Delete the default Form1.vb from the project.

  5. Double-click the form and add the following code to the Load event of the FactorialCalculator form, changing the email address Insert@youraddress.here to a real address that can receive email:

     Private Sub FactorialCalculator_Load(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles MyBase.Load     ' Add a custom listener to     ' the Listeners collection     Trace.Listeners.Add(New EmailTraceListener(_      "Insert@youraddress.here")) End Sub 
  6. Attach an event handler to the Closing event of the FactorialCalculator form and add the following code to the event handler:

     Private Sub FactorialCalculator_Closing(_  ByVal sender As Object, _  ByVal e As System.ComponentModel.CancelEventArgs) _  Handles MyBase.Closing     ' Call the close methods for all listeners     Trace.Close() End Sub 
  7. Set the project StepByStep9-2 as the startup project.

  8. Run the solution using the default Debug configuration. Enter a value and click the Calculate button. Close the form. Note that both Debug and Trace messages appear on the output window, and they are emailed to the specified address via the local SMTP server. Run the project again in Release mode. Enter a large value, such as 100 , and click the Calculate button. The overflow message appears in the output window. Close the form. While you are closing the form, the messages generated by the Trace class are sent to the specified email address.

Trace Switches

So far, you have learned that the Trace and Debug classes can be used to display valuable information related to program execution. You have also learned that it is possible to capture the messages in a variety of formats by using TraceListener objects. In this section, you'll learn how to control the nature of messages that you get from a program.

Trace switches allow you to set the parameters that can control the level of tracing that needs to be done in a program. These switches are set in an XML-based external configuration file. This is especially useful when the application is in production mode. You might not normally want your application to generate any trace messages. However, if the application has problems or you just want to check on the health of the application, you can instruct the application to emit a particular type of trace information by just changing the configuration file. There's no need to recompile the application. The application will automatically pick up the changes from the configuration file the next time you run the application.

There are two predefined classes for creating trace switches: the BooleanSwitch class and the TraceSwitch class. Both classes derive from the abstract Switch class. You can also define your own trace switch class by deriving a class from the Switch class.

The BooleanSwitch class is used to differentiate between two modes of tracing: trace-on and trace-off. Its default value is zero, which corresponds to the trace-off state. A class value set to any nonzero value corresponds to a trace-on state.

Unlike the BooleanSwitch class, the TraceSwitch class provides five different levels of tracing switches. These levels are defined by the TraceLevel enumeration, listed in Table 9.2. The default value of TraceLevel for a trace switch is ( Off ).

Table 9.2. The TraceLevel Enumeration

Enumerated Value

Integer Value

Type of Tracing

Off

None

Error

1

Only error messages

Warning

2

Warning messages and error messages

Info

3

Informational messages, warning messages, and error messages

Verbose

4

Verbose messages, informational messages, warning messages, and error messages

EXAM TIP

Out-of-Range Values for BooleanSwitch and TraceSwitch For a BooleanSwitch object, if any nonzero (negative or positive) value is specified in the configuration file, the Enabled property of the object is set to True. For a TraceSwitch object, if a value greater than 4 is specified, the Level property of the object is set to TraceLevel.Verbose (4). But if a negative value is specified for a TraceSwitch object, a StackOverflow exception will occur at runtime.


Table 9.3 displays the important properties of the TraceSwitch class.

Table 9.3. Important Properties of the TraceSwitch Class

Property

Description

Description

Describes the switch (inherited from Switch ).

DisplayName

Identifies the switch (inherited from Switch ).

Level

Specifies the trace level that helps in selecting which trace and debug messages will be processed . Its value is one of the TraceLevel enumeration values (refer to Table 9.2).

TraceError

Returns True if Level is set to Error , Warning , Info , or Verbose ; otherwise , returns False .

TraceInfo

Returns True if Level is set to Info or Verbose ; otherwise, returns False .

TraceVerbose

Returns True if Level is set to Verbose ; otherwise, returns False .

TraceWarning

Returns True if Level is set to Warning , Info , or Verbose ; otherwise, returns False .

Step by Step 9.3 demonstrates how to use trace switches in an application.

STEP BY STEP

9.3 Using the TraceSwitch Class

  1. Add a new Visual Basic .NET Windows application named StepByStep9-3 to the solution.

  2. In the Solution Explorer window, right-click Form1.vb and select Delete from the context menu.

  3. Using the Solution Explorer window, drag the FactorialCalculator.vb form from the StepByStep9-1 project to the new project. While dragging, hold down the Ctrl key so that the form is copied to the current project instead of being moved. Change the Text property of the form to Factorial Calculator 9-3 .

  4. Modify the Click event handler for the btnCalculate button so that it looks like this:

     Private Sub btnCalculate_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnCalculate.Click     Dim ts As TraceSwitch = _        New TraceSwitch("FactorialTrace", _        "Trace the factorial application")     If ts.TraceVerbose Then         ' Write a debug message         Debug.WriteLine(_          "Inside Button Click event handler")     End If     ' Start indenting messages now     Debug.Indent()     Dim intNumber As Integer = _      Convert.ToInt32(txtNumber.Text)     If ts.TraceError Then         ' Make a debug assertion         Debug.Assert(intNumber >= 0, "Invalid value", _          "negative value in debug mode")         ' Write a trace assertion         Trace.Assert(intNumber >= 0, "Invalid value", _          "negative value in trace mode")     End If     Dim intFac As Integer = 1     Try         Dim i As Integer         For i = 2 To intNumber             intFac = intFac * i             If ts.TraceInfo Then                 ' Write a debug message                 Debug.WriteLine(i, _                  "Factorial Program Debug, Value of i")             End If         Next         txtFactorial.Text = intFac.ToString()     Catch ex As System.OverflowException         If ts.TraceWarning Then             ' Write a trace message             Trace.WriteLine("There was an overflow", _              "Factorial Program Trace")             ' Write a debug message             Debug.WriteLine("There was an overflow", _              "Factorial Program Debug")         End If         intFac = 0     Catch ex As Exception         If ts.TraceWarning Then             ' Write a trace message             Trace.WriteLine(_              "An unknown exception was thrown", _              "Factorial Program Trace")             ' Write a debug message             Debug.WriteLine(_              "An unknown exception was thrown", _              "Factorial Program Debug")         End If         intFac = 0     End Try     If ts.TraceWarning Then         ' Write a conditional message         Trace.WriteLineIf(intFac = 0, _          "Unable to calculate", _          "Factorial Program Trace")         Debug.WriteLineIf(intFac = 0, _          "Unable to calculate", _          "Factorial Program Trace")     End If     ' Decrease the indent level     Debug.Unindent()     If ts.TraceVerbose Then         ' Write a debug message         Debug.WriteLine(_          "Done with computations, returning...")     End If End Sub 
  5. Add an XML file named StepByStep9-3.exe.config to the current project. In the XML editor, type the following configuration data in the XML file:

     <?xml version="1.0" encoding="utf-8" ?> <configuration>     <system.diagnostics>         <switches>             <add name="FactorialTrace" value="4" />         </switches>     </system.diagnostics> </configuration> 
  6. In Solution Explorer, select Show All Files from the toolbar. Navigate to the bin\ folder. Move the StepByStep9-3.exe.config file from the project folder to the bin\ folder.

    EXAM TIP

    Switches in a Web Application or a Web Service To enable trace switches in a Web application or a Web service, you need to add the <system.diagnostics> element to the application configuration file, web.config .

  7. Set project StepByStep9-3 as the startup project and set the form as the startup object for the project.

  8. Run the project, using the default Debug configuration. Enter the value 5 ; note that all messages appear in the output window. Enter a negative value and then a large value, and you see all the errors and warning messages. Close the form. Modify the XML file to change the value of FactorialTrace to 3 . Run the project again; you should now see all messages except the one set with TraceLevel as Verbose . Repeat the process with the values of FactorialTrace in the configuration file changed to 2 , 1 , and .

  9. Modify the program to change all Debug statements to Trace statements. Copy the XML configuration file to the bin\Release folder in the project and then repeat step 9, using the Release configuration.

Conditional Compilation

The Visual Basic .NET programming language provides a set of preprocessing directives. You can use these directives to skip sections of source files for compilation, to report errors and warnings, or to mark distinct regions of the source code.

Table 9.4 summarizes the preprocessing directives that are available in Visual Basic .NET.

Table 9.4. Visual Basic .NET Preprocessing Directives

Directives

Description

#If , #Else , #ElseIf , and #End If

These directives conditionally skip sections of code. The skipped sections are not the part of compiled code.

#Const

This directive defines a preprocessor constant. This constant can be used only within a conditional compilation directive, not in regular code.

#ExternalSource and #End ExternalSource

These directives are used by the compiler to track line numbers for compiler error messages. You won't use them in your own code.

#Region and #End Region

These directives mark sections of code. A common example of these directives is the code generated by the Windows Forms Designer. This marking can be used by visual designers such as Visual Studio .NET to show, hide, and format code.

In addition to the preprocessing directives, Visual Basic .NET also provides a ConditionalAttribute class.

You can mark a method as conditional by applying the Conditional attribute to it. The Conditional attribute takes one argument that specifies a symbol. The conditional method is either included or omitted from the compiled code, depending on the definition of the specified symbol at that point. If the symbol definition is available, the call to that method is included; otherwise, the method call is excluded from the compiled code.

Careful use of conditional compilation directives, as well as methods with Conditional attributes, allows you to keep debugging-related code in the source code while you're developing an application but exclude it from the compiled version. That way, no extraneous messages are generated in shipping code, and production programs do not encounter a performance hit due to processing additional code. If you want to resolve some errors, you can easily activate the debugging code by defining a symbol and recompiling the program.

EXAM TIP

Conditional Method Limitation A method must be a Sub rather than a Function to have the Conditional attribute applied to it.


Step by Step 9.4 demonstrates the use of the Conditional attribute and the conditional compilation directives.

STEP BY STEP

9.4 Using Conditional Compilation

  1. Create a new Windows application project in your solution. Name the project StepByStep9-4 .

  2. In the Solution Explorer window, right-click Form1.vb and select Delete from the context menu.

  3. Using the Solution Explorer window, drag the FactorialCalculator.vb form from the StepByStep9-1 project to the new project. While dragging, hold down the Ctrl key so that the form is copied to the current project instead of being moved. Change the Text property of the form to Factorial Calculator 9-4 .

  4. Add the following two conditional methods to the class definition:

     <Conditional("DEBUG")> _ Public Sub InitializeDebugMode()     lblHeading.Text = "Factorial Calculator: Debug Mode" End Sub <Conditional("TRACE")> _ Public Sub InitializeReleaseMode()     lblHeading.Text = "Factorial Calculator Version 1.0" End Sub 
  5. Add an event handler to the form's Load event and add the following code:

     Private Sub FactorialCalculator_Load(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles MyBase.Load #If Debug Then         Debug.WriteLine(_          "Program started in debug mode")         InitializeDebugMode() #Else         Trace.WriteLine(_          "Program started in release mode")         InitializeReleaseMode() #End If     End Sub 
  6. Set the form as the startup object for the project and set the project as the startup project for the solution.

  7. Run the project using the default Debug configuration. The heading of the form displays Factorial Calculator: Debug Mode (see Figure 9.8). The Output window displays the string "Program started in debug mode." Close the program, and then start it again in Release mode. A different heading appears for the form, and a different message appears in the Output window (see Figure 9.9).

    Figure 9.8. A program conditionally compiled for Debug configuration.

    Figure 9.9. A program conditionally compiled for Release configuration.

The DEBUG and TRACE symbols can be defined for the compiler in the following ways:

  • Modifying the project's Property Pages window.

  • Using the #Const directive in the beginning of the code file.

  • Using the /define ( /d for short) option with the command-line Visual Basic .NET compiler ( vbc.exe ).

Step By Step 9.4 demonstrates conditional compilation with the DEBUG and TRACE symbols. You can also use any other custom defined symbols you like to perform conditional compilation.

GUIDED PRACTICE EXERCISE 9.1

In this exercise, you will add an EventLogTraceListener object to the Factorial Calculator program so that it writes all Trace and Debug messages to the Windows event log.

You should try doing this on your own first. If you get stuck, or if you'd like to see one possible solution, follow these steps:

  1. Add a new Visual Basic .NET Windows application named GuidedPracticeExercise9-1 to the solution.

  2. In the Solution Explorer window, right-click Form1.vb and select Delete from the context menu.

  3. Using the Solution Explorer window, drag the FactorialCalculator.vb form from the StepByStep9-1 project to the new project. While dragging, hold down the Ctrl key so that the form is copied to the current project instead of being moved. Change the Text property of the form to Factorial Calculator Guided 9-1 .

  4. Double-click the form to add an event handler for the Load event. Add the following code to the event handler:

     Private Sub FactorialCalculator_Load(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles MyBase.Load     ' Add a event log listener     ' to the Listeners collection     Trace.Listeners.Add(New EventLogTraceListener(_      "FactorialCalculator")) End Sub 
  5. Set the form as the startup object for the project and set the project as the startup project for the solution.

  6. Run the project. Enter a value for finding a factorial, and then click the Calculate button. Close the program. Select View, Server Explorer. In the Server Explorer window, navigate to your computer, and expand the Event Logs, Application, FactorialCalculator node. You will see that the messages generated by the Trace and Debug classes have been added to the Application event log, as shown in Figure 9.10.

    Figure 9.10. You can view the Windows Event Log from Server Explorer.

REVIEW BREAK

  • The Trace and Debug classes can be used to display informative messages in an application when the DEBUG and TRACE symbols are defined, respectively, at the time of compilation.

  • By default, both the TRACE and DEBUG symbols are defined in the Debug configuration for compilation and only the TRACE symbol is defined for the Release configuration of compilation.

  • Listeners are objects that receive trace and debug output. By default, there is one listener, DefaultTraceListener , attached to the Trace and Debug classes. This listener displays the messages in the Output window.

  • Debug and Trace objects share the same Listeners collection. Therefore, any Listener object added to the Trace.Listeners collection is also added to the Debug.Listeners collection.

  • Trace switches allow you to change the type of messages traced by a program, depending on a value stored in the XML configuration file. You need not recompile the application for this change to take effect; you just restart it. You need to implement code to display the messages, depending on the value of the switch.

  • Visual Basic .NET preprocessor directives allow you to define symbols in an application, mark regions of code, and conditionally skip code for compilation.

  • The Conditional attribute allows you to conditionally add or skip a method for compilation, depending on the value of the symbol passed as a parameter to the attribute.


   
Top


MCAD. MCSD Training Guide (Exam 70-310. Developing XML Web Services and Server Components with Visual Basic. NET and the. NET Framework)
MCAD/MCSD Training Guide (70-310): Developing XML Web Services and Server Components with Visual Basic(R) .NET and the .NET Framework
ISBN: 0789728206
EAN: 2147483647
Year: 2002
Pages: 166

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