I work on a lot of projects that I cannot directly debug from visual studio, such as windows services and application plug-ins. For debugging, I will normally add in some code to launch the debugger but that can get messy, especially if you need it in more than one place and what about trying to remove it before release?

Since I’ve been working with Aspect Oriented Programming, I decided to make a quick and helpful aspect to ease the this task.


[Serializable]
 public class LaunchDebugger : OnMethodBoundaryAspect
 {
 private bool _break = false;

 public LaunchDebugger() { }

 public LaunchDebugger(bool breakIfAttached)
 {
 _break = breakIfAttached;
 }

#if DEBUG
 public override void OnEntry(MethodExecutionArgs args)
 {

 if (!Debugger.IsAttached)
 {
 Debugger.Launch();
 }
 else
 {
 if (_break)
 {
 Debugger.Break();
 }
 }
 }
#endif

 }

It’s a very simple aspect that takes a bool for a parameter. When this attribute is applied to a method, it hooks into the method start and will check if the debugger is already attached, If not then it will launch it otherwise (based on the setting) it will break execution and go into debug mode.

Notice the compiler directives around the OnEntry() method. If the assembly is built in release mode then this code never happens. You can leave the attributes on the methods and not have to worry about removing them.

Advertisements