Diagnostics

The .NET Framework includes two diagnostic classes within the System.Diagnostics namespace: Trace and Debug . These classes derive from the same abstract class and share the same Listeners collection, differing only in the conditions that make each one active. These classes are used to diagnose conditions within an application while it is running.

When you compile an application in the default (Debug) configuration, both the Debug and Trace symbols are defined. This makes both the Trace and Debug classes active. When you're compiling an application in the Release mode, only Trace is defined. In this configuration, the Trace class is active, but the Debug class is disabled. Table 12.1 details some of the more useful members of the Trace and Debug classes. Both classes have the same interface.

Table 12.1. Important Members of the Trace and Debug Classes

Member

Type

Description

Assert

Method

Returns False if the specific condition is not met

AutoFlush

Property

Returns True if the Flush method is called after each write

Close

Method

Flushes the output buffer and closes the listeners

Fail

Method

Returns an error message

Flush

Method

Flushes the output buffer's data to the listeners

Indent

Method

Increments the current indent level by one

IndentLevel

Property

The current indent level

IndentSize

Property

The number of spaces used in an indent

Listeners

Property

The collection of objects monitoring trace output that are shared by both Trace and Debug

Unindent

Method

Decrements the current indent level by one

Write

Method

Writes the specified data to the listeners

WriteIf

Method

Writes the specified data to the listeners if the specified condition is True

WriteLine

Method

Identical to the Write method but adds a carriage return

WriteLineIf

Method

Identical to the WriteIf method but adds a carriage return

Trace Listeners

Trace listeners are classes derived from the TraceListener class that handle the reporting of data provided by the Trace and Debug classes. One or more listener objects can be placed within the Listeners collection shared by the Trace and Debug classes. Several types of listener objects are available within the .NET Framework:

  • DefaultTraceListener class The default object type added to the Listeners collection automatically. Objects of this class send their output to the Output window.

  • TextWriterTraceListener class This listener class can be used to output messages to any object deriving from the Stream class, including external files and the console.

  • EventLogTraceListener class This listener class is used to output messages to the Windows Event Log.

graphics/alert_icon.gif

It is possible to create custom listener objects deriving from the TraceListener class, provided you include at least the Write and WriteLine methods .


Trace Switches

When your application is compiled, you may want to include the ability to turn application tracing off and on when necessary. This can be accomplished by including a TraceSwitch or BooleanSwitch object. These classes derive from the Switch class and can be adjusted by including a directive to set the proper value for the switch object within an application's XML config file.

The BooleanSwitch value is used for a simple trace on/off selection, where any nonzero value represents a "trace on" condition. If you want greater control over tracing, the TraceSwitch class may be used in order to adjust the level of tracing based on the enumerated values of the TraceLevel class, as detailed in Table 12.2.

Table 12.2. The TraceLevel Enumeration

Value

Integer

Type of Trace Messaging

Off

None

Error

1

Error messages only

Warning

2

Error and warning messages

Info

3

Error, warning, and informational messages

Verbose

4

Error, warning, informational, and verbose messages

Table 12.3 details some of the more important properties of the TraceSwitch class.

Table 12.3. Important Properties of the TraceSwitch Class

Property

Description

Description

Description of the switch object.

DisplayName

The name of the switch class instance. This is used in the XML config file to identify the object.

Level

The level of tracing, using one of the enumerated TraceLevel values detailed previously.

TraceError

True if Level is set to 1, 2, 3, or 4 (Error or greater).

TraceInfo

True if Level is set to 3 or 4 (Info or greater).

TraceVerbose

True if Level is set to 4 (Verbose).

TraceWarning

True if Level is set to 2, 3, or 4 (Warning or greater).

This example will show you how to use tracing in an application:

  1. Create a new Visual Basic .NET Windows Application project. Name the project TraceTest.

  2. Place two Label controls, two TextBox controls (txtNumber and txtFactorial) and a Button control (btnCalculate) on the default form (Form1) in the application. Figure 12.1 shows a layout for this form.

    Figure 12.1. A form to demonstrate tracing and debugging.

    graphics/12fig01.jpg

  3. Add the following code to the Click event handler for btnCalculate:

     Private Sub btnCalculate_Click(_  ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles btnCalculate.Click     Dim ts As TraceSwitch = _        New TraceSwitch("TestTrace", _        "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 
  4. In the Solution Explorer, select View All Files from the toolbar. Right-click the bin folder for this project and select Include In Project. Then right-click the bin folder again and select Add, Add New Item. Choose to create an XML file. Name the XML file TraceTest.exe.config .

  5. Use the XML editor to modify this new file so that it looks like this:

     <?xml version="1.0" encoding="utf-8" ?> <configuration>     <system.diagnostics>         <switches>             <add name="FactorialTrace" value="4" />         </switches>     </system.diagnostics> </configuration> 
  6. Run the project using the default Debug configuration. Enter the value 5 ; all messages appear in the Output window. Try entering a negative value and then a large value. You'll see all the error and warning messages. Close the form. Modify the XML file to change the value of TestTrace to 3. You will now see all messages except the ones with TraceLevel set to Verbose. Repeat the process with values of TestTrace in the configuration file changed to 2, 1, and 0.

Conditional Compilation

During compilation, you may want to vary the elements compiled using one of the preprocessing directives. These directives allow you to skip or replace segments of code during compilation while reporting warnings or marking regions of the code. These directives are evaluated before compilation of the underlying application code. Table 12.4 details the preprocessing directives available within Visual Basic .NET.

Table 12.4. .NET Preprocessing Directives

Directives

Description

#If/#Else/#ElseIf#End If

Used to evaluate a condition and then vary which code elements are compiled based on that evaluation

#Const

Used to define a preprocessor constant that is only available to the preprocessing directives

#ExternalSource#End ExternalSource

Used to track line numbers for errors reported during preprocessing

#Region#End Region

Used to specify a region of code that may be easily expanded or collapsed to make the code easier to read within the Visual Studio .NET Integrated Development Environment (IDE)

Methods may also be individually marked for conditional compilation if a symbol ( DEBUG , TRACE , or a custom symbol) is specified in their Conditional attribute. Function methods do not make use of the Conditional attribute.

Here's an example of this type of Conditional attribute formatting using the DEBUG symbol:

 <Conditional("DEBUG")> _ Public Sub InitDebugMode()     lblDebug.Text = "Debug Mode"     lblDebug.Visible = True End Sub 

If the application is compiled in Debug mode, the Label control will display the message "Debug Mode" after compilation.



Developing and Implementing WindowsR-based Applications with Visual BasicR. NET and Visual StudioR. NET Exam CramT 2 (Exam 70-306)
Developing and Implementing WindowsR-based Applications with Visual BasicR. NET and Visual StudioR. NET Exam CramT 2 (Exam 70-306)
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 188

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