Generate a Stack Trace Anytime, Anywhere

Validate a program's logic, record information about different states of the application, and take the pulse of what's happening inyour app.

Don Kiely

October 30, 2009

4 Min Read
ITPro Today logo in a gray background | ITPro Today

Troubleshooting Tricks

LANGUAGES: VB .NET

TECHNOLOGIES:Stack Trace | Exceptions

 

Generate a Stack Trace Anytime, Anywhere

Validate a program's logic, record information aboutdifferent states of the application, and take the pulse of what's happening inyour app.

 

By Don Kiely

 

In a recent article (Probethe Secrets of the Stack Trace), I talked about using the stack trace -that cryptic list of object names, line numbers, and gobbledy-gook that seemslike too much work to analyze and grok to solve debugging problems. Hopefully Iconvinced you that there are valuable nuggets of information there, at leastfor problems that aren't solved quickly by examining the offending line of codeor its neighbors.

 

A stack trace is a useful tool, and not only when anexception arises. You can use it to validate a program's logic, recordinformation about different states of the application, and take the pulse ofwhat's happening in the app. If you're stepping through your code, you can usethe Call Stack window (see Figure 1) to see exactly where you are in programexecution.

 


Figure 1. Double-click on any entryin the Call Stack window to go directly to the code.

 

Like most things in the .NET Framework, Microsoft made thecall stack available as a class you can use anytime to get a snapshot of whereyou are in an application. It's named the StackTrace class, and you'll find itin the System.Diagnostic namespace. This class has three interface features ofinterest in custom code:

 

  • The FrameCountproperty: A stack frame is one entry in the trace, containing all therelevant information about that code location. This property, of course,returns the number of frames currently in the stack.

  • The GetFramemethod: Takes an integer and returns the specified stack frame. These arenumbered from zero, which is the last frame pushed onto the stack, to thecurrent code position.

  • The ToStringmethod: This is overridden to generate a readable representation of thestack trace, which is what you see in the default exception page generated byASP.NET.

 

One thing you should be aware of is the stack tracechanges with each line of code you execute. So the StackTrace class takes asnapshot of the trace when you create the object, letting you read its contentswithout changing dynamically.

 

The StackFrame class gives basic information about theframe, including source-code filenames and locations if the app was compiledwith debug symbols. What really makes it powerful is if you use .NET Reflectionto get additional information about the type. This is particularly useful forframes that represent a framework method rather than your custom methods.

 

Using these classes is fairly straightforward. Figure 2shows the results of running a sample application to build a table withinformation about the stack trace, as well as the readable default trace that.NET generates (keep in mind that I'm a coder and my graphics design gene wasremoved at birth).

 


Figure 2. This table results fromrunning the sample application (available for download) with information aboutthe stack trace.

 

Start by instantiating a new instance of the StackTraceclass. It has several constructors to customize exactly what is saved in thesnapshot. Here I'm using a version that includes all available stack frames andcapturing source code information if available (in the code that follows, I'momitting the lines that create new table rows and cells):

 

Dim sTrace As New StackTrace(True)

 

Then the code loops through the collection of frames andreading properties:

 

While iCount < sTrace.FrameCount

      Dim frame =sTrace.GetFrame(iCount)

 

      tblCol.Text =frame.GetFileName

      tblCol.Text =frame.GetMethod.Name

      tblCol.Text =frame.GetFileColumnNumber

      tblCol.Text =frame.GetFileLineNumber

      tblCol.Text =frame.GetMethod.ToString

 

      iCount += 1

End While

 

Two of the interesting lines use the GetMethod method ofthe StackFrame class. This technique returns the method in which the frame isexecuting, returning a MethodBase object, which is part of theSystem.Reflection namespace. Using this object, you have access to all themetadata about both your custom code and the .NET Framework code - a deep poolof interesting information.

 

Using code like this you can explore the depths of .NETcode and build your own exploration tools. And you'll get to the heart of anyproblems your code is having.

 

The sample code in thisarticle is available for download.

 

Don Kiely is senior technology consultant forInformation Insights, a business and technology consultancy in Fairbanks,Alaska. E-mail him at mailto:[email protected].

 

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like