Sunday, March 30, 2008

Sample of C# Trace.Fail() method.

        Often we don't check input parameters, because we have a contract and expect valid parameters values. But sometimes, we want to control critical parameters and somehow inform about invalid input parameters.

In this case, we can use method Debug.Fail() or Trace.Fail().

static int CheckArgument(string argument)
    if (argument == null)
        Trace.Fail("CheckArgument(): argument cannot be bull", "CheckArgument()");
        return 0;
    return argument.Length;
Method CheckArgument doesn't expect to receive null, but if input parameter argument will be null, we call method Trace.Fail() with relevant message. By default, next message will be shown:


The message will be relevant in debug mode, but in production mode, we don't want to show message to user, but want to inform developer about the problem.

So, we want to change behavior of Fail.

First of all, let's implement new class MyTraceListener and override method Fail (actually 2 method Fails):

public class MyTraceListener : DefaultTraceListener
public override void Fail(string message)
public override void Fail(string message, string detailMessage)
SendNotification(message + ", detailMessage: " + detailMessage);

void SendNotification(string message)
// here should be implemented sending email
StackTrace stackTrace = new StackTrace(1, true);
Trace.WriteLine("MyTraceListener notification: " + message + " in " + stackTrace);

Now, we should define the implemented MyTraceListener as single TraceListenerClass:

MyTraceListener listener = new MyTraceListener();

"Output Visual Studio" Window demonstrates possible notification's output:



TraceListener.Fail Method

StackTrace Class

Sources can be found in "Code project C# tips samples" in project Debug, method sample_TraceFail().

No comments: