Wednesday 28 June 2017

TraceSwitch

The TraceSwitch can be used in your code to specify the level of message you want to display to your user.

Integer value Enumerated value
0 Off
1 TraceError
2 TraceWarning
3 TraceInfo
4 TraceVerbose

If we take a look at the following code for a simple WebForms page

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var ts = new TraceSwitch("mySwitch""");

            //if level explicitly set to 0
            if (ts.Level == 0)
                Response.Write("Nothing<br />");

            //inclusively if level > 0
            if (ts.TraceError)
                Response.Write("Error<br />");

            //inclusively if level > 1
            if (ts.TraceWarning)
                Response.Write("Warning<br />");

            //inclusively if level > 2
            if (ts.TraceInfo)
                Response.Write("Info<br />");

            //inclusively if level > 3
            if (ts.TraceVerbose)
                Response.Write("Verbose<br />");
        }
    }
}

The nice thing is you can set the traceswtich value in the webconfig or appconfig.

<configuration>
  <system.diagnostics>
    <switches>
      <add name ="mySwitch" value ="3"/>
    </switches>
  </system.diagnostics>
</
configuration>

would result in



but if we set the value to 0

<configuration>
  <system.diagnostics>
    <switches>
      <add name ="mySwitch" value ="0"/>
    </switches>
  </system.diagnostics>
</
configuration>

Then instead we'd see