Debugging an ASP. NET web application, Part I-tracing...

Source: Internet
Author: User
ArticleDirectory
    • Introduction
    • Tracing
    • System. Web. tracecontext
    • System. Diagnostics
    • Conditional compilation
    • Conclusion
    • References

Debugging an ASP. NET web application, Part I-tracing...

Bugs are a fact of the programmer's life. How can we deal with them efficiently? In this series of two articles I'm going to look at two main areas of finding and fixing errors in your program-tracing and debugging.

By: Chris Sully date: May 31,200 3 Printer friendly version

Introduction

Bugs are a fact of the programmer's life. How can we deal with them efficiently? In this series of 2 articles I'm going to look at two main areas in order to address this question:

    1. Tracing: the process of collecting information about a program's execution and
    2. Debugging: the overlapping topic of finding and fixing errors in your program

We shall look both at the inherent supporting features provided by the. NET Framework and ASP. NET and the additional tools provided by vs. net over the course of the two articles.

Part I shall focus on tracing, Part II on debugging, though as I 've already stated these are overlapping areas as you shall see.

Tracing

Tracing is the ability of an application to generate information about its own execution. the idea is that subsequent analysis of this information may help us understand why a part of the application is not behaving as it shoshould and allow identification of the source of the error.

We shall look at two different ways of implementing tracing in. net

    1. Via the system. Web. tracecontext class
    2. Via the system. Diagnostics. Trace and system. Diagnostics. debug classes

Tracing can be thought of as a better (more featureful and automated) alternative to the response. writes you used to put in your old asp3.0 code to help debug pages!

System. Web. tracecontext

The tracecontext class is responsible for gathering the execution details of a Web request. the tracecontext object for the current request can be accessed through the trace property of the page class. you are thus able to access the functionality exposed by the object's members, for example writing to the trace log.

By default, tracing is not enabled. it may be enabled at the page level via the trace attribute of the page directive. when set to true the page appends the tracing information of the current Web request to its output.

The output of a page with the trace attribute set to 'true' will include a host of information in addition to the actual page output, as follows:

Request details: Summary details of the page request

Trace Information: Messages either generated by the ASP. net engine or by you the programmer by making use of the write or warn methods in code. four column output: category, message, time from the first trace item, duration of this trace item.

Control tree: The entire collection of controls in the ASP. NET page displayed hierarchically.

Collection information: Any defined members of the following collections will also be displayed:

    • Session state
    • Cookies
    • Headers
    • Form
    • Querystring
    • Server Variables

when tracing is enabled the programmer may add information to the trace information section abve via the trace. warn and trace. write. the only difference between these methods is that the warn method displays its text in red, thus allowing the programmer a basic facility to differentiate between the severity of tracing messages. finally at the page level you may change the order of presentation of trace messages from the default time order ('sortbytime') to be based on an alternate via the tracemode attribute. in fact the only other option is 'sortbycategory '.

As well as enabling tracing at the page level it can be enabled at the application level using the trace element within the web. config file. this introduces an extra facility: it allows viewing of trace information in a separate page instead of displaying it with the page output. this page is trace. axd which will be located in the application root and is termed 'trace viewer '-it lists all the page requests to an application along with summary details and a link to view the full trace log the request. it also includes a link to clear the current trace information of all page requests.

Note that the page level directive overrides the application level setting. So if you disable tracing for a special page you will not see corresponding information via trace. axd.

You can imagine this facility is quite a resource hit and shoshould be used wisely. In the particle the facility shocould be disabled before deployment of the application, when it shoshould be redundant anyway!

Let's finish of this section with a few examples:

1. Use of trace. Write/trace. Warn:

 
Trace. Write ("[Category]","[Message]")

2. Setting up page level tracing by category:

 
 <%@ Page Language ="VB"Trace ="True"Tracemode ="Sortbycategory" %>

3. Setting up application level tracing (syntax ):

 
 <Trace Enabled= "True | false"Localonly= "True | false"Pageoutput= "True | false"Requestlimit= "Integer"Tracemode= "Sortbytime | sortbycategory" /> 

SettingLocalonlyTo true makes the trace Viewer (trace. axd) available only on the host web server.RequestlimitIs the number of trace requests to store on the server. The default is 10.

System. Diagnostics

tracing in VB. net can also be implemented via generating messages with the use of the debug and trace classes. the messages generated by default by these classes are viewable in the. net output window, though you will see this is writable able shortly.

The two classes are closely related. all their members are conditionally compiled on the basis of whether the debug or trace symbols are specified respectively. visual Basic. net/. net provide two basic configurations for a project-Debug (the default) and release. when you compile a program using the debug configuration both the trace and debug Conditional compilation symbols are defined, I. e. when you compile the project any debug or trace code in your application will be added and compiled. in the release configuration only trace information is compiled. these modes are retriable via the property pages of your. net solution. they may also be specified within the program and via command line compilation options.

Some of the members of the debug and trace classes you may choose to use are:

Methods:

Assert: Checks for a condition and displays a message if false

Fail: Displays an error message

Indent/Unindent: Increases/decreases the current indent level by one

Write/Writeif/Writeline/Writelineif: Write information to the trace listeners in the listeners collection-conditional or unconditional; with a newline character or.

Some examples:

 
Debug. Assert (value <0,"Invalid value","Negative value employed in debug mode") Trace. writeline (value,"Program trace, value of value")

Properties:

Listeners: The collection of listeners that is monitoring the Trace Output

See the SDK documentation for full details of the members available.

Which brings us nicely...

Listeners

Listeners are the classes for forwarding, recording or displaying messages generated by the trace and debug classes. you can have multiple listeners associated with the trace and debug classes by adding multiple listener objects to their listeners property.

The listener property is a collection capable of holding objects of any type derived from the tracelistener class. This is an abstract class that belongs to the system. Diagnostics namespace that has three implementations.

    1. Defaulttracelistener: an object instantiated from this class is automatically added to the listeners collection of the trace and debug classes. It writes messages to the output window.
    2. Textwritertracelistener: writes the messages to any class that derives from the stream class. This includes des the console or a file.
    3. Eventlogtracelistener: writes the messages to the Windows event log.

Here's a brief code snippet relating to implementation 2:

 'Create a new text writer using the output stream, and add it 'The trace listeners. DimMyfileAsStream = file. Create ("Testfile.txt")DimMytextlistenerAs NewTextwritertracelistener (myfile) trace. listeners. Add (mytextlistener)'Write output to the fileTrace. Write ("Test output")

If you require a listener object which acts differently to these you can create your own class, deriving from the tracelistener class to do so.

You may also add tracelisteners from your application web. config file, e.g.

  < Configuration  >   <  System. Diagnostics  >     <  Trace  >       <  Listeners  >         <  Add   Name  = "Mylistener"   Type  = "System. Diagnostics. textwritertracelistener, system"   Initializedata  = "C: \ mylistener. log"   />        <  Remove   Type  = "System. Diagnostics. defaulttracelistener, system"  />       </  Listeners  >     </  Trace  >   </  System. Diagnostics  >   </  Configuration  >  

Any trace information enabled wowould then be written to the specified file.

Trace Switches

Trace switches allow you to set the parameters that can control the level of tracing that needs to be passed med within a program. these are set via an XML-based configuration file, the web. config File in fact. this might be special useful if the application is in production mode and develops a fault you need to resolve. you cocould instruct a program to generate the particle trace messages simply by altering the config file. the changes, as in most situations. net, will be picked up automatically.

There are two predefined classes for creating trace switches: The booleanswitch class and the traceswitch class-both derive from the abstract switch class. as ever, you cocould also define your own class by deriving from the switch class.

The booleanswitch class differentiates between two modes of tracing: On (non zero) and off (zero, default ). in comparison the traceswitch class provides 5 different levels of tracing switches defined by the Trace Level enumeration with the following members:

Off 0
Error 1
Warning 2
Info 3
Verbose 4

Where each adds an extra level of information to the output.

In your code you cocould have the following:

 DimTSAsTraceswitch ([displayname], [description])IfTS. traceverboseThenDebug. writeline ("nasty bigError!")End If 

And you coshould configure web. config with the following:

  <  Configuration  >     <  System. Web  > ... </  System. Web  >     < System. Diagnostics  >       <  Switches  >         <  Add   Name = "[ Displayname ]" Value =" 4 " />       </  Switches  >     </  System. Diagnostics  >   </ Configuration  >  

Thus, with this configuration verbose error messages will be output. when you don't want such messages you wowould simply reduce the trace level to a lower value within web. config. remember that the location of the output of these messages is down to the rest of your system configuration, as described above.

Conditional compilation

VB. NET provides a set of pre-processing directives which

    • Enable you to skip sections of source files for compilation, for example to omit testing code in the released compiled version of your software
    • Report errors or warnings
    • Mark sections of your code (a la vs. Net windows Form Designer)

In addition to the pre-processing directives, VB. net also provides the programmer with the conditionalattribute class via which you can mark Class Members for Conditional compilation dependent on symbol values. A symbol value is simply an arbitrary name used for this purpose.

Careful use of these features allow the programmer to keep debugging related code in the source code whilst you are developing an application but to easily exclude it from the finished compiled code. this will remove the associated performance hit from production applications. further, shocould the production system encounter an issue you can re-enable the debugging code via a simple switch and recompilation.

Pre-processing directives Summary

# If, # else, # elseif, # endif: Allow conditional skipping of sections of code that will then not be compiled.

# Const: Defines a pre-processor constant only viable within a Conditional compilation directive.

# Externalsource, # End externalsource: Used by the compiler to track line numbers for Compiler error messages.

# Region, # End Region: Used to mark sections of code. Commonly Used by ides to show, hide and format code.

Conditionalattribute usage example

 
<Conditional ("debug")>Public SubInitializedebugmode () lbldebug. Text = "debug mode"End Sub 

In this example, if the symbol is set the sub will be encoded in the project compilation. The pre-processing directives can be used similarly.

The debug and trace symbols may be modified

    • Modifying the Vs. Net project's property pages
    • Using the # const directive at the beginning of the Code File
    • Using the/define (/d for short) option with vbc.exe

You are also not restricted to these two symbols for Conditional compilation. You can provide your own definm defined symbols via the # const directive.

Conclusion

I hope that the above has proved a useful overview of the tracing related debugging functionality provided by. net Framework and available to the ASP. net programmer and that you will find these features useful. in the second part of this series of two articles I shall continue on to examine debugging 'proper ', in particle the use of debugging tools.

References

ASP. NET: tips, tutorial and code
Scott Mitchell et al.
SAMs

developing and implementing Web applications with VB. NET and vs. Net
http://www.dotnetjohn.com/articles.aspx? ArticleID = 55

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.