Problem
I recently had to debug an extremely complex Web Application (WebForms), and needed to see what was going on in the start up of the application, in particular the Global class.
In the normal run of things I would use Visual Studio, go to the Debug menu, select Attach to Process, find the w3wp.exe, set breakpoints – and Bob’s your uncle.
Not for this though. The attach would happen too late for my purposes, as I needed to attach on start up.
Solution
What I needed was the Visual Studio and the Debugger to be invoked as soon as the Global class is instantiated, so the solution is to invoke the Debugger in the constructor of the Global class.
The only issue is that this is potentially useful but dangerous code: I really would like to keep it in the code but only invoke it if I needed to, the solution to this is to use Conditional Compilation Attributes.
Really what I wanted was the Debugger invoked only when a Conditional Compilation directive was invoked, and definitely only in Debug builds. Unfortunately the Conditional Compilation Attributes are supported as single attributes or OR’ed together. The fix is to invoke one method with Conditional Debug, and the other with the specific conditional thus:
namespace WebApplication { public class Global : System.Web.HttpApplication { public Global() { DebugProcessing(); } [Conditional("DEBUG")] private static void DebugProcessing() { AttachDebugger(); } [Conditional("STARTUPDEBUGGER")] private static void AttachDebugger() { Debugger.Launch(); } protected void Application_Start(object sender, EventArgs e) { } protected void Session_Start(object sender, EventArgs e) { } // Other Functions removed for brevity } }
The result, if both DEBUG and STARTUPDEBUGGER are defined during compilation, the Web Application will invoke the Debugger on start up (actually in the constructor of the Global class), otherwise that application starts as normal. Useful and Safe.