65.9K
CodeProject is changing. Read more.
Home

Enable Debug.Assert under ASP.NET

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.06/5 (9 votes)

Jan 3, 2003

viewsIcon

80581

downloadIcon

1133

Enable Debug.Assert under ASP.NET just like under windows Forms

Sample Image - DebugListener.png

Introduction

Class System.Diagnostics.Debug provides a serial of Debug methods, such as Debug.Assert, Debug.Fail. They only work under Windows.Form applications. Under ASP.NET, no popup window will show to alert user that debug version has caught a potential logic error!

Using the code

Edit your root web.config file of your ASP.NET project:

<configuration>
   <system.diagnostics>
      <assert assertuienabled="false" logfilename="c:\Debug.log" />
         <trace autoflush="true" indentsize="0">
            <listeners>
              <add type="AspNetDebugListener.DebugListener,AspNetDebugListener" />
            </listeners>
         </trace>
   </system.diagnostics>
</configuration>

How it works

TraceListener class provides the abstract base class for the listeners who monitor the trace and debug output. So derive a new class that can monitor debug output too.

public class DebugListener : TraceListener 
{
    public DebugListener() : this("Forks Asp.Net DebugTracer")
    {
    }

Filter the output string

DebugListener uses Environment.StackTrace to print out the stacktrace. But it will print out many useless Debug.Assert... calling frame, I use a filter to remove it:

string GetStatckTraceString()
{
    string s = Environment.StackTrace;
    StringBuilder sb = new StringBuilder(s.Length);
    using (StringReader reader = new StringReader(s))
    {
        bool debugFound = false;
        for(;;)
        {
            string line = reader.ReadLine();
            if (line == null)
                break;

            if (line.IndexOf("System.Diagnostics.Debug.Assert") != -1)
            {
                debugFound = true;
                continue;
            }

            if (debugFound)
            {
                sb.Append(line);
                sb.Append(Environment.NewLine);
            }
        }
    }

    return sb.ToString();
}