Resetting Trace

The ASP.NET tracing system has a configurable requestLimit that stops the tracing system from processing requests after a specified number of requests.  I was asked today how to programmatically reset the trace, just as you can through a browser by clicking on the “clear current trace” link on the trace.axd page.  I know of two ways.

The first way is to simulate what happens when that link is clicked.  Simply issue an HttpWebRequest to “https://server/app/trace.axd?clear=1” which will cause the TraceHandler registered to process requests for trace.axd to issue a call to HttpRuntime.Profile.Reset().

The second way is to invoke HttpRuntime.Profile.Reset() programmatically.  The problem is that the Profile property on HttpRuntime, the Profiler class returned from that property, and the Reset method on that class are all internal to System.Web.  So to get at this functionality, you need to use reflection:

///

<summary>Resets the HttpRuntime trace profile.</summary>
    public static void Reset()
{
        // Set the binding flags
        BindingFlags flags =
BindingFlags.Instance | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic;

        // Get the profiler
        PropertyInfo piProfile = typeof(HttpRuntime).GetProperty("Profile", flags);
MethodInfo getProfiler = piProfile.GetGetMethod(true);
        object profiler = getProfiler.Invoke(null, null);

        // Use it to reset the tracing profile
        MethodInfo reset = profiler.GetType().GetMethod("Reset", flags);
reset.Invoke(profiler, null);
}

As always, using reflection like this to access non-public methods and data is NOT a recommended approach:
a) There's a reason they weren't exposed in the first place.  Maybe there are strict requirements about the pre- and post- conditions for calling the methods.  Maybe they can only be used in certain scenarios.  Maybe they were only tested for certain scenarios.  Etc.
b) Accessing non-public members like this requires the appropriate ReflectionPermissions which requires a high-level of trust.
c) There are no guarantees that future versions of System.Web.dll will even contain these members, will keep them with the same signatures, or will require the same environment/conditions for calling them.
etc.

That said, for testing purposes and/or for accomplishing something quick and dirty today, sometimes it's the way to go.  Don't blame me when it breaks, though.