private void AttachManagedDebugger() { EnvDTE.DTE dte; try { dte = (EnvDTE.DTE)Marshal.GetActiveObject("VisualStudio.DTE.16.0"); } catch (COMException) { throw new Exception("Visual studio v2019 not found."); } int tryCount = 5; // using a do while because the object is sometimes null.... do { Process.Native.WaitForInputIdle(); try { EnvDTE.Processes processes = dte.Debugger.LocalProcesses; foreach (EnvDTE80.Process2 proc in processes.Cast <EnvDTE80.Process2>().Where(proc => proc.Name.IndexOf(Process.Native.ProcessName) != -1)) { EnvDTE80.Engine debugEngine = proc.Transport.Engines.Item("Managed (v4.6, v4.5, v4.0)"); proc.Attach2(debugEngine); break; } break; } catch { } Thread.Sleep(1000); } while (tryCount-- > 0); }
private void AttachToW3wp(List <int> currentWorkerProcess) { EnvDTE80.Debugger2 dbg2 = _applicationObject.Debugger as EnvDTE80.Debugger2; EnvDTE80.Transport transport = dbg2.Transports.Item("Default"); EnvDTE80.Engine dbgEngine = null; string targetVersion = GetFrameworkVersion(); Trace.WriteLine("Attach Debug Engine: " + targetVersion); foreach (EnvDTE80.Engine item in transport.Engines) { if (item.Name.IndexOf(targetVersion) != -1) { dbgEngine = item; break; } } if (dbgEngine == null) { ShowMessage("Can't determine project's TargetFrameworkVersion - " + targetVersion); return; } Trace.WriteLine("Debug Engine Type: " + dbgEngine.Name); EnvDTE80.Process2 w3wpProcess = null; foreach (var proc in dbg2.LocalProcesses) { EnvDTE80.Process2 process = proc as EnvDTE80.Process2; if (process == null) { continue; } // Skip process in recycle. if (currentWorkerProcess.Contains(process.ProcessID) == true) { continue; } if (process.Name.IndexOf("W3WP.EXE", 0, StringComparison.OrdinalIgnoreCase) != -1) { w3wpProcess = process; break; } } if (w3wpProcess != null) { bool attached = false; string txt = string.Format("{0}({1})", w3wpProcess.Name, w3wpProcess.ProcessID); System.Diagnostics.Trace.WriteLine("Attaching to: " + txt); try { // I don't know why Attach2 method hang // when Visual Studio 2013 try to attach w3wp.exe hosting .NET 2.0/3.0/3.5 Web Application. if (targetVersion == "v2.0") { w3wpProcess.Attach(); } else { w3wpProcess.Attach2(dbgEngine); } attached = true; System.Diagnostics.Trace.WriteLine("Attached to: " + txt); } catch { } if (attached == true) { string startupUrl = GetProjectItemValue("WebApplication.IISUrl"); if (string.IsNullOrEmpty(startupUrl) == false) { RunInternetExplorer(startupUrl); } } } else { ShowMessage("Make sure the AppPool's Start Mode is AlwaysRunning"); } }