Debugging in .net

xiaoxiao2021-03-06  85

Summary

Writing high quality code is the goal of every programmer dreams of, and many programmers are spending the time on the bug and even far more than the time to write code. Many of the domestic software companies have also begun to pay more attention to the quality of software, equipped with specialized testers to fully test software quality. As software is getting bigger and bigger, the structure is more complicated, even if it is discovered and solving a small bug, it will cost a lot of manpower and time. In order to better prevent and monitor the generation of bugs, an excellent programmer should develop good programming habits, add DEBUG code in their own procedures to facilitate capture and positioning bugs. All this is simple in .NET Framework.

This article will introduce the use of the DEBUG class and the Trace class in the .NET Framework class library, and help everyone can master their usage through some examples.

table of Contents

introduction

TRACE METHOD

TRACE LEVEL

TRACE OUTPUT

TRACE VS. Debug

Assert

summary

More information

introduction

The process of software development is also the process of continuous struggle with BUG. By writing Unit Test, program developers can test whether there is bug in the code, and once the Unit Test fails, developers can easier positioning and debug bugs through the Debug code in the program.

The TRACE class and the Debug class in .NET Framework have almost contain all the features you need to use by the Debug code, and will be introduced one by one.

TRACE METHOD

Trace is a very useful technology that helps us track and share all the details of the application to help us get useful information. In the .NET class library, Trace is a static class that does not require instantiation. TRACE provides four output methods: Write, WriteLine, Writeif, WriteLineif. WriteLine automatically wraps when the output is output, and the conditional judgment function provided by WriteIf and WriteLineif is available. Below is an example of the simplest TRACE output:

// A simple example of a paragraph

Trace.WriteLine ("string matching is successful!");

/ / Directly use WriteLineIf to judge

TRACE.WRITELINEIF (IsshowTrace, "starting position is:" myIndex.toString ());

// Judgment using the IF statement

IF (True == IsshowTrace)

{

TRACE.WRITELINE (ISSHOWTRACE, "starting position is:" myIndex.toString ());

}

In the simple example above, it is determined whether to output myIndex according to whether ISSHOWTRACE is TRUE.

TRACE OUTPUT

If you run the just example program, the output of Trace is oriented to the command line window. If it is a DEBUG in vs.net, the output of Trace is oriented to the Output window. The .NET Framework provides three TRACE LISTENERS for redirects for Trace output: DefaultTracelistener, EventLogTraceListener, and TextWritrtracelistener. By default it is defaulttracelistener. We can also use TextWritertraceListener to direct TRACE output to the specified text file, using EventLogTraceListener to direct TRACE output to the specified type of system event log record (support only in WinNT, Windows2000, WindowsXP, and .NET Server). You can change Trace Listener in the program or in the config file. Please see the example below: / / Demos how to use Listener

Using system;

Using system.diagnostics;

Namespace Listener

{

Class Application

{

[Stathread]

Static void main (string [] args)

{

Trace.writeline ("TRACE LISTENER Test");

}

}

}

In the following config file, remove the default listener, add an EventLogTraceListener and a TextWritertracelistener:

Initializedata = "mylistener.log" />

Initializedata = "Application" />

Examples to do it, you can see in myListener.log files:

TRACE LISTENER Test

Open the event viewer, you can see in the Application log:

In this way, you can output Trace information to the specified place by changing the listener of TRACE.

Tracing Level

Software development throughout the team, too much Trace will make a significant effect on the performance of the program. At the same time, all the contents of Trace output is equally valid in the final release, too much output content will only make users feel confused. Therefore, you can specify TRACE's Level, determine the output of Trace according to the level of Switches. Please see the example below: USING SYSTEM;

Using system.diagnostics;

Namespace Switching

{

Class SampleClass

{

// Establish a Switch whose value is configured by the config file

Static TraceSwitch Generalswitch = New Traceswitch ("Coolswitch", "Global Scope");

Static Public Void SampleMethod ()

{

// If the switch state is set to TraceError, output the message

Trace.writelineif (Generalswitch.TraceError, "TraceError Message";

// If the switch state is set to TraceWarning, output the message

TRACE.WRITELINEIF (Generalswitch.TraceWarning, "TraceWarning Message";

// If the switch state is set to TraceInfo, output the message

Trace.WriteLineif (Generalswitch.TraceInfo, "TraceInfo Message");

// If the switch state is set to TraceverBose, output the message

Trace.writelineif (Generalswitch.TraceverBose, "Traceverbose Message");

}

Public static void main (string [] args)

{

SampleMethod ();

}

}

}

TraceSwitch has four properties: TraceError, TraceInfo, TraceverBose and TraceWarning. If the status of the Switch is higher than or equal to the corresponding attribute level, the corresponding attribute value is TRUE, and it is false. For example, when the status value of Switch is 2, the TraceError and TraceWarning properties are TRUE. Below is a comparison table of the Switch status value:

The value of Switch can specify in the config file:

Run the above example code, the output is:

TraceError Message

TraceWarning Message

You can set the Switche's Level. When a bug appears, the Switche's Level is reduced in the configuration file to get more information.

The method in the TRACE VS. DEBUGTRACE class is exactly the same as the method in the Debug class. So what do you have to use the TRACE class or use the Debug class? Or when do you use the DEBUG class with the Trace class?

The simplest difference is that all methods of the Debug class are only executed in the Debug version, and there will be no debug code execution in the final release. The TRACE class will execute in Debug and Release version (of course, you can also manually modify the default configuration of vs.net, but there is no meaning). Although both classes provide the same approach, I still recommend that the use of the Trace class, the use of the TRACE class is limited to the place to track the code, otherwise it will affect the performance of the final release version. At the same time, it is best to define a separate TraceSwitch for each class (source file) to facilitate minimize the impact on the performance of the entire product performance when adjusting the TRACE SWITCH LEVEL.

Overall, it is recommended that you use the Trace class when you record the log file to the system's event log or the product's log file, because the functions of these records still need (you can set the default Trace Switch Level), For program debugging, capture the Assert code of bugs, it is recommended that you use the Debug class. Of course, you can also decide according to your actual needs, but once you set down, you will follow the unified standard, keep the code consistency.

Assert

Assert is most common when writing Debug code. One of the guidelines for writing high quality codes is not to have any assumptions. Any place with "hypothesis" should be used to use Assert. As mentioned above, I recommend you use the Assert method of the Debug class.

DEBUG is also the listener of TRACE, and the information is output to MessGebox by default.

Public Bool FindCustomer (int Customerid)

{

Debug.Assert (Customerid> 0, "FindCustomer error", "CustomerID should be greater than 0");

// more code ...

Return True;

}

When the FindCustomer method is called, the incoming parameter CustomerID is less than 0, the assertion filebox pops up the assertion failed:

Users can choose to exit, retry, or ignore.

Any failure of Assertion should be treated as a bug. It should be noted that do not confuse the processing of Assert and Exception (Try ... catch ... Finally), ASSERT processes some error conditions that should not occur, and Exception is processed for various reasons (such as network environments, server DOWN machines) , Database Crash, etc.) produce an exception.

In general, Assert can be used in the following cases:

1. Call parameters validity

2. Return value validity

3. Data validity

4. Algorithm effectiveness

The above example is checked for the validity of the call parameters. Below is an example of the validity of the return value:

IF (SetCustomerValid (Customerid))

{

Debug.assert (Customerisvalid);

Usercustom;

Else

{

Debug.Assert (! Customerisvalid (Customerid);

ReleaseCustomer (CUSTOMERID);

}

In addition, Assert can also be used to check the validity, integrity of the object, integrity, for example, the following example first calls the IMOK method to check the integrity of this object itself when calling a public method:

[Conditional ("Debug")]]

Private void imok ()

{

Debug.assert (this! = Null, "test object status", "this can't be null");

// more here.

}

Public Bool SetCustomerValid (int Customerid)

{

IMOK ();

Debug.Assert (Customerid> 0, "FindCustomer error", "CustomerID should be greater than 0");

// more code ...

Return True;

}

When designing or implementing an algorithm, the correctness of the algorithm is also ensured. For example, when designing a fast sorting algorithm, the sort result of two different algorithms can be compared, and if different, one of the error is indicated, and the assertion failed. Or set a set of initial values ​​in advance, comparing the calculation results with the prediction result. Verification of the correctness of the algorithm is no longer exemplified.

summary

This paper briefly introduces the usage of the Trace class and the Debug class in .NET Framework, and gives the specific example code to help readers understand. For an excellent programmer, write Debug code is one of the fundamental skills of life. I hope this article can help everyone, improve the efficiency of programming, and develop high quality software.

More information

Please visit the following chain to get more information:

1. .NET Framework Class Library: TRACE CLASS

Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdiagnostricstraceclasstopic.asp

2. .NET Framework Class Library: Debug Class

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdiagnosticsdebugclasstopic.asp

转载请注明原文地址:https://www.9cbs.com/read-106390.html

New Post(0)