Attach to process for lazies

Attaching to a process is something that developers use very often to debug, but what happens when the process (A) you want to debug is launched from another process (B) and you want to debug is the initialization of process A,  Supposing that process A can only run within the context of process B in that case the only way to start process A is to do so from process so classic F5 won't help us to debug the initialization of A.

I had this scenario at work so at first I "trained" myself to do a very fast Alt+Ctrl+P select the process and press Attach button, of course this training didn't help much, after googling a little I found this macro

Sub AttachProcess()
        Dim process As EnvDTE.Process
 
        If Not (DTE.Debugger.DebuggedProcesses Is Nothing) Then
            For Each process In DTE.Debugger.DebuggedProcesses
                If (process.Name.IndexOf("aspnet_wp.exe") <> -1) Then
                    Exit Sub
                End If
            Next
        End If
 
        For Each process In DTE.Debugger.LocalProcesses
            If (process.Name.IndexOf("myprocess.exe") <> -1) Then
                process.Attach()
                Exit Sub
            End If
        Next
    End Sub 


but still it would have to wait for the process to start and then attach to it, so finally I created this Visual Studio add-in, which have this option.
 
The main idea is to wait for the process to start and then attach to it:
 
 
   1:private AttachResult PessimisticAttach(AttachType attachType)
   2:{
   3:     AttachResult res = Attach(attachType);
   4:     DateTime timeout = DateTime.Now.AddSeconds(WaitTimeout);
   5:   
   6:     while(res == AttachResult.NotRunning && timeout > DateTime.Now)
   7:     {
   8:           res = Attach(attachType);
   9:           System.Threading.Thread.Sleep(100);
  10:     }
  11:     return res;
  12:}
  13:   
  14:private AttachResult Attach(AttachType attachType)
  15:{
  16:     string engine =attachTypesMap[attachType];
  17:     if(IsBeingDebugged())
  18:     {
  19:          return AttachResult.BeingDebugged;
  20:     }
  21:   
  22:     Debugger2 dbg = dte.Debugger as Debugger2;
  23:     Transport trans = dbg.Transports.Item("Default");
  24:     Engine eng;
  25:   
  26:     eng = trans.Engines.Item(engine);
  27:   
  28:     EnvDTE80.Process2 proc = null;
  29:   
  30:     try
  31:     {
  32:          proc = dbg.GetProcesses(trans, "").Item(processName) 
  33:              as EnvDTE80.Process2;
  34:     }
  35:     catch(Exception ex)
  36:     {
  37:          if(ex.Message.Contains("Invalid index."))
  38:          {
  39:              return AttachResult.NotRunning;
  40:          }
  41:     }
  42:   
  43:     proc.Attach2(eng);
  44:     return AttachResult.Attached;
  45:}
 
I wrote the add-in using Declarative Visual Studio addin buttons with icons which saved me a lot of time and pain.
 

2 Comments

Comments have been disabled for this content.