public ReAttachDebugger(IReAttachPackage package) { _package = package; _debugger = package.GetService(typeof(SVsShellDebugger)) as IVsDebugger; _dte = _package.GetService(typeof(SDTE)) as DTE2; if (_dte != null) { _dteDebugger = _dte.Debugger as Debugger2; } if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { _package.Reporter.ReportError( "Unable to get required services for ReAttachDebugger in ctor."); return; } if (_debugger.AdviseDebuggerEvents(this, out _cookie) != VSConstants.S_OK) { _package.Reporter.ReportError("ReAttach: AdviserDebuggerEvents failed."); } if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) { _package.Reporter.ReportError("AdviceDebugEventsCallback call failed in ReAttachDebugger ctor."); } foreach (Engine engine in _dteDebugger.Transports.Item("Default").Engines) { _engines.Add(Guid.Parse(engine.ID), engine.Name); } }
public DebugManager(ExcelDnaToolsPackage package, ExcelConnection connection) { _package = package; _connection = connection; var packageServiceProvider = (IServiceProvider)package; _debugger = packageServiceProvider.GetService(typeof(SVsShellDebugger)) as IVsDebugger; // var dgr = Package.GetGlobalService(typeof(SVsShellDebugger)) ; // _debugger = dgr as IVsDebugger; _dte = packageServiceProvider.GetService(typeof(SDTE)) as DTE; if (_dte != null) { _dteDebugger = _dte.Debugger as Debugger2; } if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { Debug.Fail("DebugManager setup failed"); return; } if (_debugger.AdviseDebuggerEvents(this, out _debuggerEventsCookie) != VSConstants.S_OK) { Debug.Fail("DebugManager setup failed"); } if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) { Debug.Fail("DebugManager setup failed"); } }
public ReAttachDebugger(IReAttachPackage package) { _package = package; _debugger = package.GetService(typeof(SVsShellDebugger)) as IVsDebugger; _dte = _package.GetService(typeof(SDTE)) as DTE2; if (_dte != null) _dteDebugger = _dte.Debugger as Debugger2; if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { _package.Reporter.ReportError( "Unable to get required services for ReAttachDebugger in ctor."); return; } // TODO: Unadvise, or did I find something telling me otherwise? if (_debugger.AdviseDebuggerEvents(this, out _cookie) != VSConstants.S_OK) _package.Reporter.ReportError("ReAttach: AdviserDebuggerEvents failed."); if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) _package.Reporter.ReportError("AdviceDebugEventsCallback call failed in ReAttachDebugger ctor."); foreach (Engine engine in _dteDebugger.Transports.Item("Default").Engines) { var engineId = Guid.Parse(engine.ID); if (ReAttachConstants.IgnoredDebuggingEngines.Contains(engineId)) continue; _engines.Add(engineId, engine.Name); } }
private void OnProcessComboGetList(object sender, EventArgs e) { if ((null == e) || (e == EventArgs.Empty)) { // --- We should never get here; EventArgs are required. throw (new ArgumentNullException(Resources.EventArgsRequired)); } OleMenuCmdEventArgs eventArgs = e as OleMenuCmdEventArgs; if (eventArgs == null) { throw (new ArgumentException(Resources.EventArgsRequired)); } if (eventArgs.InValue != null) { throw (new ArgumentException(Resources.ParamNull)); } if (eventArgs.OutValue != IntPtr.Zero) { DTE dte = (DTE)this.GetService(typeof(DTE)); Debugger2 debugger = dte.Debugger as Debugger2; Processes processes = debugger.GetProcesses(m_Transport, m_Qualifier); m_ProcessNames.Clear(); foreach (Process p in processes) { m_ProcessNames.Add(p.Name); } Marshal.GetNativeVariantForObject(m_ProcessNames.ToArray(), eventArgs.OutValue); } }
/// <summary> /// 连接远程计算机,并附加到进程 /// </summary> /// <param name="ip">远程计算机ip</param> /// <param name="remotePort">远程调试工具的端口</param> /// <returns></returns> public static bool AttachProcess(DTE2 dte, string ip, string remotePort) { Debugger2 debug = (Debugger2)dte.Debugger; DteTransport = debug.Transports.Item(2); Processes processes = debug.GetProcesses(DteTransport, ip + ":" + remotePort); Logger.Instance.Info("成功连接到远程计算机,并获取远程目标机上所有进程"); bool found = false; foreach (Process2 process in processes) { if (process.ProcessID == int.Parse(RemoteDebug.PidString)) { foreach (Engine engine in DteTransport.Engines) { //{FB0D4648-F776-4980-95F8-BB7F36EBC1EE}这是托管4.5模式下的调试器 if (new[] { "{FB0D4648-F776-4980-95F8-BB7F36EBC1EE}", }.Any(temp => string.Equals(engine.ID, temp))) { process.Attach2(new[] { engine }); } } found = true; break; } } if (!found) { MessageBox.Show("Selected processes are not running. Try to run your application first.", "Debug Attach History Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } return(true); }
/// <inheritdoc /> public AttachDebuggerResult AttachToProcess(Process process) { if (process == null) { throw new ArgumentNullException("process"); } AttachDebuggerResult result = AttachDebuggerResult.CouldNotAttach; try { IVisualStudio visualStudio = GetVisualStudio(true, logger); if (visualStudio != null) { visualStudio.Call(dte => { EnvDTE.Process dteProcess = FindProcess(dte.Debugger.DebuggedProcesses, process); if (dteProcess != null) { result = AttachDebuggerResult.AlreadyAttached; } else { dteProcess = FindProcess(dte.Debugger.LocalProcesses, process); if (dteProcess != null) { Process2 dteProcess2 = dteProcess as Process2; Debugger2 dteDebugger2 = dte.Debugger as Debugger2; if (dteProcess2 != null && dteDebugger2 != null) { IList <Guid> engineGuids = GetEngineGuids(); Engine[] engines = GetEngines(dteDebugger2, engineGuids); dteProcess2.Attach2(engines); } else { dteProcess.Attach(); } result = AttachDebuggerResult.Attached; } else { logger.Log(LogSeverity.Debug, "Failed to attach Visual Studio debugger to process because it was not found in the LocalProcesses list."); } } }); } } catch (VisualStudioException ex) { logger.Log(LogSeverity.Debug, "Failed to attach Visual Studio debugger to process.", ex); } return(result); }
private static EnvDTE.Processes GetDebugProcesses(string remoteServer, long?remoteServerPort) { if (string.IsNullOrEmpty(remoteServer)) { return(((Debugger2)DebugAttachManagerPackage.DTE.Debugger).LocalProcesses); } Debugger2 db = (Debugger2)DebugAttachManagerPackage.DTE.Debugger; Transport trans = db.Transports.Item("Default"); return(db.GetProcesses(trans, remoteServerPort == null ? remoteServer : $"{remoteServer}:{remoteServerPort}")); }
private void ConnectOnClick(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtServerName.Text)) { MessageBox.Show("Server name is required.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (PortNumber == -1) { MessageBox.Show("Invalid port number.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } Debugger2 db = (Debugger2)DebugAttachManagerPackage.DTE.Debugger; Transport trans = db.Transports.Item("Default"); try { db.GetProcesses(trans, PortNumber == null ? txtServerName.Text : $"{txtServerName.Text}:{_portNumber}"); } catch { MessageBox.Show($"Unable to connect to {txtServerName.Text}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } ConnectionOptions options = new ConnectionOptions { Impersonation = ImpersonationLevel.Default, EnablePrivileges = true, Authentication = AuthenticationLevel.PacketPrivacy }; var scope = new ManagementScope($@"\\{txtServerName.Text}\root\cimv2", options); try { scope.Connect(); } catch { MessageBoxResult result = MessageBox.Show($"Unable to connect to {txtServerName.Text} WMI service. Please check permissions. You can use WBEMTest.exe to test your WMI access. If you are not in a Domain, UAC on remote machine will prevent remote access.", "Warning", MessageBoxButton.OKCancel, MessageBoxImage.Warning); if (result == MessageBoxResult.Cancel) { return; } } DialogResult = true; Settings.Default.RemoteServer = txtServerName.Text; Settings.Default.Save(); Close(); }
public async Task InitializeAsync(ReAttachPackage package, ReAttachHistory history, CancellationToken cancellationToken) { _history = history; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _ui = (await package.GetServiceAsync(typeof(ReAttachUi))) as ReAttachUi; if (_ui == null) { ReAttachUtils.ShowStartupError("Unable to obtain reference to UI."); return; } var debugger = (await package.GetServiceAsync(typeof(IVsDebugger))) as IVsDebugger; if (debugger == null) { ReAttachUtils.ShowStartupError("Unable to obtain reference to debugger."); return; } if (debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) { ReAttachUtils.ShowStartupError("Unable to subscribe on debug events."); return; } if (debugger.AdviseDebuggerEvents(this, out _cookie) != VSConstants.S_OK) { ReAttachUtils.ShowStartupError("Unable to subscribe on debugger mode changes."); return; } var dte = await package.GetServiceAsync(typeof(EnvDTE.DTE)) as DTE2; if (dte == null) { ReAttachUtils.ShowStartupError("Unable to get obtain reference to automation object model (DTE2)."); return; } _dteDebugger = dte.Debugger as Debugger2; if (_dteDebugger == null) { ReAttachUtils.ShowStartupError("Unable to get reference to debugger from automation object."); return; } _engines = GetTransportEngines(); }
public ReAttachDebugger(IReAttachPackage package) { _package = package; _debugger = package.GetService(typeof(SVsShellDebugger)) as IVsDebugger; _dte = _package.GetService(typeof(SDTE)) as DTE2; if (_dte != null) { _dteDebugger = _dte.Debugger as Debugger2; } if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { _package.Reporter.ReportError( "Unable to get required services for ReAttachDebugger in ctor."); return; } // TODO: Unadvise, or did I find something telling me otherwise? if (_debugger.AdviseDebuggerEvents(this, out _debuggerCookie) != VSConstants.S_OK) { _package.Reporter.ReportError("ReAttach: AdviserDebuggerEvents failed."); } if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) { _package.Reporter.ReportError("AdviceDebugEventsCallback call failed in ReAttachDebugger ctor."); } try { foreach (Transport transport in _dteDebugger.Transports) { //foreach (Engine engine in _dteDebugger.Transports.Item("Default").Engines) foreach (Engine engine in transport.Engines) { var engineId = Guid.Parse(engine.ID); if (ReAttachConstants.IgnoredDebuggingEngines.Contains(engineId) || _engines.ContainsKey(engineId)) { continue; } _engines.Add(engineId, engine.Name); _package.Reporter.ReportTrace("ReAttach found debugging engine {0}.", engine.Name); } } } catch (Exception e) { _package.Reporter.ReportError("ReAttach was unable to detect debugging engines: {0}.", e.Message); } }
/// <summary> /// Determines whether [is process available by name] [the specified process name]. /// </summary> /// <param name="processName">Name of the process.</param> /// <returns> /// <c>true</c> if [is process available by name] [the specified process name]; otherwise, <c>false</c>. /// </returns> public bool IsProcessAvailableByName(String processName) { Debugger2 debugger = CurrentDTE.Application.Debugger as Debugger2; if (debugger != null) { foreach (EnvDTE80.Process2 process in debugger.LocalProcesses) { if (process.Name.ToUpper().LastIndexOf(processName.ToUpper()) == (process.Name.Length - processName.Length)) { return(true); } } } return(false); }
/// <summary> /// Attach the debugger to all running instances of w3wp.exe /// Added Feb 2008 by Tom Clarkson /// Based on http://weblogs.asp.net/koenv/archive/2008/02/14/quick-attach-and-detach-debugger.aspx /// </summary> protected override void Execute() { Debugger2 debugger = (Debugger2)DTEInstance.Application.Debugger; Processes processes = debugger.LocalProcesses; foreach (Process2 process in processes) { if (process.Name.EndsWith("w3wp.exe")) { process.Attach(); } if (process.Name.EndsWith("W3SVC.exe")) { process.Attach(); } } }
private void Execute() { var model = ShowWacProcessesList(); if (model == null || !model.SelectedProcesses.Any()) { return; } model.DebuggerEngines.PersistSelectionToRegistry(); Processes envProcesses; if (model.Host == Environment.MachineName) { envProcesses = _dte.Debugger.LocalProcesses; } else { Debugger2 debugger = (Debugger2)_dte.Debugger; Transport transport = debugger.Transports.Item("Remote (No Authentication)"); string transportQualifier = model.Host; if (!string.IsNullOrWhiteSpace(model.Port)) { transportQualifier += ":" + model.Port; } envProcesses = debugger.GetProcesses(transport, transportQualifier); } var manuallySelectedDebuggerEngineIds = model.DebuggerEngines.ManuallySelectedEngines.Select(debuggerEngine => debuggerEngine.ID).ToArray(); var selectedProcesses = envProcesses.Cast <Process2>().Where(p => model.SelectedProcesses.Contains(p.ProcessID)); foreach (var process in selectedProcesses) { if (model.DebuggerEngines.IsAutomatic) { process.Attach(); } else { process.Attach2(manuallySelectedDebuggerEngineIds); } } }
private static Engine[] GetEngines(Debugger2 debugger, IList <Guid> engineGuids) { Transport transport = debugger.Transports.Item("Default"); Engines engines = transport.Engines; List <Engine> selectedEngines = new List <Engine>(); // Iterate by index rather than query by GUID because the latter does not // work, contrary to what the MSDN states. -- Jeff. for (int i = 1; i <= engines.Count; i++) { Engine engine = engines.Item(i); if (engineGuids.Contains(new Guid(engine.ID))) { selectedEngines.Add(engine); } } return(selectedEngines.ToArray()); }
private void OnAttach(object sender, EventArgs e) { try { DTE dte = (DTE)this.GetService(typeof(DTE)); Debugger2 debugger = dte.Debugger as Debugger2; Processes processes = debugger.GetProcesses(m_Transport, m_Qualifier); Process process = null; try { process = processes.Item(m_ProcessName); } catch (System.ArgumentException) { throw (new System.Exception(Resources.ProcessNameNotFound)); } process.Attach(); } catch (System.Exception ex) { CallMessageBox(ex.Message); } }
public ReAttachDebugger(IReAttachPackage package) { _package = package; _debugger = package.GetService(typeof(SVsShellDebugger)) as IVsDebugger; _dte = _package.GetService(typeof(SDTE)) as DTE2; if (_dte != null) _dteDebugger = _dte.Debugger as Debugger2; if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { _package.Reporter.ReportError( "Unable to get required services for ReAttachDebugger in ctor."); return; } if (_debugger.AdviseDebuggerEvents(this, out _cookie) != VSConstants.S_OK) _package.Reporter.ReportError("ReAttach: AdviserDebuggerEvents failed."); if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) _package.Reporter.ReportError("AdviceDebugEventsCallback call failed in ReAttachDebugger ctor."); }
public bool AttachToProcess(int processId) { Debugger2 dbg = _dteReference.Debugger as Debugger2; Transport trans = dbg.Transports.Item("Default"); Engine eng; eng = trans.Engines.Item("Managed"); try { var processes = dbg.GetProcesses(trans, ""); foreach (EnvDTE80.Process2 process in processes) { try { int pid = process.ProcessID; string name = process.Name; if (process.ProcessID == processId) { process.Attach2(eng); return(true); } } catch { } } } catch (Exception ex) { if (ex.Message.Contains("Invalid index.")) { return(false); } } return(false); }
private static IEnumerable <ProcessExt> GetProcesses(string remoteServer, long?remoteServerPort) { var result = new List <ProcessExt>(); if (string.IsNullOrEmpty(remoteServer)) { foreach (EnvDTE.Process p in ((Debugger2)DebugAttachManagerPackage.DTE.Debugger).LocalProcesses) { result.Add(new ProcessExt(p.Name, p.ProcessID, remoteServer, remoteServerPort)); } } else { Debugger2 db = (Debugger2)DebugAttachManagerPackage.DTE.Debugger; Transport trans = db.Transports.Item("Default"); foreach (EnvDTE.Process p in db.GetProcesses(trans, remoteServerPort == null ? remoteServer : $"{remoteServer}:{remoteServerPort}")) { result.Add(new ProcessExt(p.Name, p.ProcessID, remoteServer, remoteServerPort)); } } return(result); }
protected Process GetProcess(object applicationObject) { DTE2 applicationObjectCast = applicationObject as DTE2; if (applicationObjectCast == null) { UTGHelper.ErrorHandler.ShowMessage("Failed to attach to process. Cast Failed"); return null; } Debugger2 lDebugger = (Debugger2)applicationObjectCast.Debugger; foreach (Process lLocalProcess in lDebugger.LocalProcesses) { if (lLocalProcess.Name.IndexOf(ConsoleName) >= 0) { return lLocalProcess; } } return null; }
private static Process2 AttachAndWaitForMode(VisualStudioApp app, SD.Process processToAttach, object debugEngines, dbgDebugMode expectedMode) { Debugger2 dbg2 = (Debugger2)app.Dte.Debugger; System.Threading.Thread.Sleep(1000); Process2 result = null; Transport t = dbg2.Transports.Item("Default"); bool foundit = false; foreach (Process2 p in dbg2.LocalProcesses) { if (p.ProcessID == processToAttach.Id) { foundit = true; p.Attach2(debugEngines); result = p; break; } } Assert.IsTrue(foundit, "The process to attach [{0}] could not be found in LocalProcesses (did it exit immediately?)", processToAttach.Id); DebugProject.WaitForMode(app, expectedMode); return(result); }
public ReAttachDebugger(IReAttachPackage package) { _package = package; _debugger = package.GetService(typeof(SVsShellDebugger)) as IVsDebugger; _dte = _package.GetService(typeof(SDTE)) as DTE2; if (_dte != null) _dteDebugger = _dte.Debugger as Debugger2; if (_package == null || _debugger == null || _dte == null || _dteDebugger == null) { _package.Reporter.ReportError( "Unable to get required services for ReAttachDebugger in ctor."); return; } if (_debugger.AdviseDebuggerEvents(this, out _cookie) != VSConstants.S_OK) _package.Reporter.ReportError("ReAttach: AdviserDebuggerEvents failed."); if (_debugger.AdviseDebugEventCallback(this) != VSConstants.S_OK) _package.Reporter.ReportError("AdviceDebugEventsCallback call failed in ReAttachDebugger ctor."); foreach (Engine engine in _dteDebugger.Transports.Item("Default").Engines) _engines.Add(Guid.Parse(engine.ID), engine.Name); }
protected override void Initialize() { base.Initialize(); OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; //Attach button { OleMenuCommand attachCommand = new OleMenuCommand(new EventHandler(OnAttach), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidAttach)); mcs.AddCommand(attachCommand); } //"Transport" combobox { OleMenuCommand comboCommand = new OleMenuCommand(new EventHandler(OnTransportCombo), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidTransportCombo)); comboCommand.ParametersDescription = "$"; mcs.AddCommand(comboCommand); MenuCommand comboGetListCommand = new OleMenuCommand(new EventHandler(OnTransportComboGetList), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidTransportComboGetList)); mcs.AddCommand(comboGetListCommand); } //"Qualifier" combobox" { OleMenuCommand comboCommand = new OleMenuCommand(new EventHandler(OnQualifierCombo), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidQualifierCombo)); comboCommand.ParametersDescription = "$"; mcs.AddCommand(comboCommand); } //"Process" combobox { OleMenuCommand comboCommand = new OleMenuCommand(new EventHandler(OnProcessCombo), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidProcessesCombo)); comboCommand.ParametersDescription = "$"; mcs.AddCommand(comboCommand); MenuCommand comboGetListCommand = new OleMenuCommand(new EventHandler(OnProcessComboGetList), new CommandID(GuidList.guidAttachToCmdSet, (int)PkgCmdIDList.cmdidProcessesComboGetList)); mcs.AddCommand(comboGetListCommand); } //initialize some locals { DTE dte = (DTE)this.GetService(typeof(DTE)); Debugger2 debugger = dte.Debugger as Debugger2; foreach (Transport t in debugger.Transports) { m_Transports.Add(t); if (m_Transport == null || t.Name.StartsWith("Default")) { m_Transport = t; } } } }
private static Engine[] GetEngines(Debugger2 debugger, IList<Guid> engineGuids) { Transport transport = debugger.Transports.Item("Default"); Engines engines = transport.Engines; List<Engine> selectedEngines = new List<Engine>(); // Iterate by index rather than query by GUID because the latter does not // work, contrary to what the MSDN states. -- Jeff. for (int i = 1; i <= engines.Count; i++) { Engine engine = engines.Item(i); if (engineGuids.Contains(new Guid(engine.ID))) selectedEngines.Add(engine); } return selectedEngines.ToArray(); }
static void Main(string[] args) { String prjTemplDir = Path.Combine(vsInstallPath, @"Common7\IDE\ProjectTemplates"); List <String> vsTemplates = Directory.GetFiles(prjTemplDir, "*.vstemplate", SearchOption.AllDirectories).Select(x => x.Substring(prjTemplDir.Length + 1)).ToList(); Regex re = new Regex("^(.*?)" + Regex.Escape(@"\")); Func <String, String> untilBackSlash = (s) => { return(re.Match(s).Groups[1].ToString()); }; List <String> languages = vsTemplates.Select(x => untilBackSlash(x)).ToList(); List <String> vsNames = new List <string>(); for (int i = 0; i < vsTemplates.Count; i++) { bool keep = true; String lang = languages[i]; if (lang != "CSharp" && lang != "VC" && lang != "Javascript") { keep = false; } if ( vsTemplates[i].Contains("WebTemplate") // has wizard || vsTemplates[i].Contains("WapProj") // hangs ) { keep = false; } if (!keep) { vsTemplates.RemoveAt(i); languages.RemoveAt(i); i--; continue; } vsTemplates[i] = vsTemplates[i].Substring(languages[i].Length + 1); vsNames.Add(vsTemplates[i].Replace("\\", "_").Replace("1033_", "").Replace(".vstemplate", "").Replace(".", "")); } //var procs = System.Diagnostics.Process.GetProcesses().Where(x => x.ProcessName == "devenv").ToArray(); //String devenvPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\devenv.exe"; //Assembly asm = Assembly.LoadFile(devenvPath); DTE2 dte = null; try { //String[] allPaths = { // Path.Combine(vsInstallPath, @"Common7\IDE\PublicAssemblies"), // // VCProjectShim is here. // Path.Combine(vsInstallPath, @"Common7\IDE\CommonExtensions\Microsoft\VC\Project") //}; //AppDomain.CurrentDomain.AssemblyResolve += (s, asmArgs) => //{ // String dllName = new AssemblyName(asmArgs.Name).Name + ".dll"; // foreach (String dir in allPaths) // { // string path = Path.Combine(dir, dllName); // if (!File.Exists(path)) // continue; // return Assembly.LoadFrom(path); // } // Console.WriteLine("Warning: Required assembly not found: " + dllName); // return null; //}; //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.10.0"), true); //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.12.0"), true); //dte = (DTE)Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.DTE.16.0"), true); bool bNormalStart = false; MessageFilter.Register(); if (bNormalStart) { dte = (DTE2)Activator.CreateInstance(Type.GetTypeFromProgID(vsId), true); } else { //Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService() bool bAttached = false; int processId = 0; Process2 processToAttachTo = null; for (int iTry = 0; iTry < 2; iTry++) { dte = (DTE2)Marshal.GetActiveObject(debuggerVsId); var processes = dte.Debugger.LocalProcesses.Cast <EnvDTE.Process>().ToArray(); Debugger2 debugger2 = (Debugger2)dte.Debugger; // // https://varionet.wordpress.com/tag/debug/ // Attach2 sometimes triggers error: 8971001E, need to detach from all processes. // Something to do debugging multiple processes? // debugger2.DetachAll(); int c = debugger2.Transports.Count; Transport transport = debugger2.Transports.Item(1 /* Default transport */); //foreach (var ix in transport.Engines) //{ // Engine e = ix as Engine; // String name = e.Name; // Console.WriteLine("'" + name + "'"); //} // Otherwise will get timeout while trying to evaluate any com object in visual studio watch window String debuggerType = "Managed (v3.5, v3.0, v2.0)"; //String debuggerType = "Managed (v4.6, v4.5, v4.0)"; //String debuggerType = "Managed"; Engine[] engines = new Engine[] { transport.Engines.Item(debuggerType) }; foreach (var process in processes) { String name = Path.GetFileNameWithoutExtension(Utils.call(() => (process.Name))).ToLower(); if (name != "devenv") { continue; } processId = Utils.call(() => (process.ProcessID)); String cmdArgs = GetProcessCommandLine(processId); if (cmdArgs == null || !cmdArgs.Contains("-Embedding")) { continue; } processToAttachTo = process as Process2; //Console.ReadKey(); Console.WriteLine("Attaching to: " + processId); Utils.callVoidFunction(() => { processToAttachTo.Attach2(engines); }); // Apparently it takes some time for debugger to attach to process, otherwise missing breakpoints. // Not sure if some sort of wait could be triggerred. //System.Threading.Thread.Sleep(2000); bAttached = true; break; } if (bAttached) { break; } { if (iTry == 1) { Console.WriteLine("Error: Failed to launch vs2017/2019."); return; } // Analogue of // Activator.CreateInstance(Type.GetTypeFromProgID(vsId), true); // only with experimental visual studio version. Start_devenv_Embedded(); } } dte = (DTE2)GetDTE(processId, 120); //dte = null; } String edition = dte.Edition; Console.WriteLine("Edition: " + edition); Console.WriteLine("-----------------------------------------------"); // Make it visible. if (!dte.MainWindow.Visible) { dte.MainWindow.Visible = true; dte.UserControl = true; } Solution2 sln2 = (Solution2)dte.Solution; //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution2.sln"); //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution.sln"); //sln2.Open(@"C:\PrototypingQuick\ProjectGen\Solution1.sln"); //sln2.Close(); // Add existing project to solution //String projPath = @"D:\PrototypingQuick\ProjectGen\Dll1\Dll1.vcxproj"; //String projPath = @"D:\PrototypingQuick\ProjectGen\Dll1\Dll2.vcxproj"; //sln2.AddFromFile(projPath); //sln2.SolutionBuild.Build(); //Microsoft.VisualStudio.OLE.Interop.IServiceProvider serv = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte; //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile", "args"); //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile"); //dte.ExecuteCommand("File.InvokeOpenSyncProjectFile", "thisIsArg1"); //dte.ExecuteCommand("Tools.InvokeExecuteScript", @"D:\Prototyping\cppscriptcore\Tools\vsDev\bin\Debug\vsDev.dll"); //int cmdCount = Utils.call(() => (dte.Commands.Count)); //for( int i = 1; i <= cmdCount; i++) //{ // Command c = Utils.call(() => dte.Commands.Item(i)); // Console.WriteLine(Utils.call(() => c.Name)); // Console.WriteLine( " " + Utils.call(() => c.ID)); // Console.WriteLine( " " + Utils.call(() => c.Guid.ToString()) ); // Console.WriteLine(); //} //Guid service = new Guid("89BE061A-1103-4D1D-8293-A51F8480E202"); //Guid serviceApi = new Guid("89BE061A-1103-4D1D-8293-A51F8480E201"); //IntPtr obj = IntPtr.Zero; //int r = serv.QueryService(ref service, ref serviceApi, out obj); //Console.WriteLine("[ Press any key to close ... ]"); //Console.ReadKey(); /* * // Generate huge amount of temporary projects. * Solution2 sln2 = (Solution2)dte.Solution; * String mainDir = @"d:\Prototyping\testsln"; * String slnTempDir = Path.Combine(mainDir, "slnTemp"); * * * for (int i = 0; i < vsTemplates.Count; i++) * { * String name = vsNames[i]; * String dir = Path.Combine(mainDir, name); * bool bKeepProject = true; * * if (Directory.Exists(dir)) * Directory.Delete(dir, true); * * Console.Write("Project '" + name + "... " ); * Directory.CreateDirectory(dir); * sln2.Create(slnTempDir, name); * * try * { * string csTemplatePath = sln2.GetProjectTemplate(vsTemplates[i], languages[i]); * sln2.AddFromTemplate(csTemplatePath, dir, name, false); * Console.WriteLine("ok." ); * } * catch (Exception ex) * { * Console.WriteLine("Project '" + name + ": " + ex.Message); * bKeepProject = false; * } * if(bKeepProject) * sln2.SaveAs(Path.Combine(dir, name + ".sln")); * sln2.Close(bKeepProject); * * if (!bKeepProject) * Directory.Delete(dir, true); * } */ Solution sln = dte.Solution; /* * String slnPath = @"c:\Prototyping\testsln"; * if( !sln.IsOpen ) * sln.Create(slnPath, "test"); * Solution2 sln2 = (Solution2) sln; * Solution3 sln3 = (Solution3) sln; * * int nCount = sln.Projects.Count; * * dte.Events.SolutionEvents.ProjectAdded += SolutionEvents_ProjectAdded; * dte.Events.SolutionItemsEvents.ItemAdded += SolutionItemsEvents_ItemAdded; * dynamic events = dte.Events.GetObject("CSharpProjectItemsEvents"); * //Events2 events2 = dte.Events as Events2; * //events2.ProjectItemsEvents.ItemAdded += Pievents_ItemAdded; * pievents = events as ProjectItemsEvents; * pievents.ItemAdded += Pievents_ItemAdded; * * * if (nCount <= 0) * { * string csTemplatePath = sln2.GetProjectTemplate(@"Windows\1033\ConsoleApplication\csConsoleApplication.vstemplate", "CSharp"); * sln.AddFromTemplate(csTemplatePath, slnPath + "\\prj", "Foo", false); * dte.ExecuteCommand("File.SaveAll"); * } */ //sln.Open(@"D:\PrototypingQuick\ConsoleApplication2\ConsoleApplication2.sln"); while (sln.Projects.Count == 0) { Console.WriteLine("Please open solution in newly opened visual studio and then press enter to continue..."); Console.ReadLine(); } // Enumerate available configurations within a project Project p = sln2.Projects.Item(1); // // Get / set .NET framework version, https://blogs.msdn.microsoft.com/visualstudio/2010/02/25/how-to-retarget-a-project-using-dte/ // // ".NETFramework,Version=v4.7.2" // String DotNetVersion = p.Properties.Item("TargetFrameworkMoniker").Value; var oConfs = p.ConfigurationManager.Cast <Configuration>().ToArray(); var confs = oConfs.Select(x => x.ConfigurationName + "|" + x.PlatformName).ToArray(); foreach (String c in confs) { Console.WriteLine("- " + c); } // C#/C++ project properties scanning //Project p = sln.Projects.Item(1); //Dictionary<String, Object> d = new Dictionary<string, object>(); //foreach (Property prop in p.Properties) //{ // try // { // d[prop.Name] = prop.Value; // } // catch (Exception) // { // } //} // C++ project model scanning //VCProject vcProject = p.Object as VCProject; //VCProject vcProject = (VCProject)p.Object; //if (vcProject == null) //{ // MessageFilter.Revoke(); // Console.WriteLine("Not a C++ project or vs2017 or later (registry moved to file problem)."); // Console.WriteLine("[Press any key to close]"); // Console.ReadLine(); // return; //} //VCProjectEngine peng2 = vcProject.VCProjectEngine as VCProjectEngine; //VCProjectEngineShim peng = peng2 as VCProjectEngineShim; //var sp = peng.VsServiceProvider; // Scan for all subprojects. List <Project> projects = GetProjects(sln); foreach (Project genProj in projects) { #if !OLD_VS VSProject2 sharpProj = genProj.Object as VSProject2; #else VSProject2 sharpProj = genProj.Object as VSProject2; //VSProject3 sharpProj = genProj.Object as VSProject3; //VSProject4 sharpProj = genProj.Object as VSProject4; #endif VCProject cppProj = genProj.Object as VCProject; String name = genProj.Name; Console.Write("Project: " + name + " - language( ~" + genProj.Kind + "): "); if (sharpProj == null && cppProj == null) { Console.WriteLine("Unknown"); continue; } if (sharpProj != null) { Console.WriteLine("C#"); } if (cppProj != null) { Console.WriteLine("C++ "); } //foreach (Reference r in ((References)vsp2.References).Cast<Reference>()) //{ // Console.WriteLine(r.Path); // Console.WriteLine("CopyLocal = " + r.CopyLocal); //} } Console.WriteLine("[Press any key to close]"); Console.ReadLine(); // Get project GUID //IVsSolution service = GetService( dte, typeof(IVsSolution)) as IVsSolution; //String uname = p.UniqueName; //IVsHierarchy hierarchy; //service.GetProjectOfUniqueName(uname, out hierarchy); //Guid projectGuid; //hierarchy.GetGuidProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid); //Console.WriteLine("Project guid: " + projectGuid.ToString()); // Add file in programming language independent manner. //p.ProjectItems.AddFromFile(@"D:\Prototyping\cppscriptcore\cppscript\cppscript.cpp"); //if (vcProject != null) //{ //foreach (object oFile in (IVCCollection)vcProject.Files) //{ // VCFile file = oFile as VCFile; // Console.WriteLine(file.Name); // Console.WriteLine(" " + file.RelativePath); // foreach (var _conf in (IVCCollection)file.FileConfigurations) // { // VCFileConfiguration conf = _conf as VCFileConfiguration; // Console.WriteLine(conf.Name); // VCCLCompilerTool compilerTool = conf.Tool as VCCLCompilerTool; // if (compilerTool == null) // continue; // Console.WriteLine("Defines: " + compilerTool.PreprocessorDefinitions); // } //} //VCFilter f = null; //foreach (object oItem in (IVCCollection)vcProject.Items) //{ // VCFile file = oItem as VCFile; // VCFilter fitem = oItem as VCFilter; // if (fitem != null && fitem.Name == "Test1") // f = fitem; //} //if( f == null ) // f = vcProject.AddFilter("Test1") as VCFilter; //f.AddFile(@"D:\Prototyping\cppscriptcore\cppscript\cppscript.cpp"); // Recursive files / folder adding / C++ project //String fromDir = @"C:\Prototyping\vlc-3.0.2"; //List<String> files = Directory.GetFiles(fromDir, "*.c", SearchOption.AllDirectories).ToList(); //files.AddRange(Directory.GetFiles(fromDir, "*.h", SearchOption.AllDirectories)); //files = files.Select(x => x.Substring(fromDir.Length + 1)).ToList(); //Stopwatch sw = Stopwatch.StartNew(); //foreach (String file in files) //{ // String[] pp = file.Split('\\'); // IVCCollection items = (IVCCollection)vcProject.Items; // VCFilter parent = null; // VCFilter filter = null; // for (int i = 0; i < pp.Length - 1; i++) // { // filter = items.OfType<VCFilter>().Where(x => x.Name == pp[i]).FirstOrDefault(); // if (filter == null) // if (i == 0) // filter = (VCFilter)vcProject.AddFilter(pp[i]); // else // filter = (VCFilter)parent.AddFilter(pp[i]); // parent = filter; // items = (IVCCollection)parent.Items; // } // String fullpath = Path.Combine(fromDir, file); // if (filter == null) // vcProject.AddFile(fullpath); // else // filter.AddFile(fullpath); //} //sw.Stop(); //Console.WriteLine(sw.ElapsedMilliseconds); //} MessageFilter.Revoke(); //Console.WriteLine(); //Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); Console.WriteLine("Stack trace: " + ex.StackTrace); Console.ReadKey(); } finally { // Need to close solution, so devenv.exe would not remain hanging in memory. //if (dte != null) // dte.Solution.Close(); } }
/// <summary> /// Client side - see ConnectDebugger description. /// Server side - starts ipc channel / monitors for newly attaching ipc connections. /// </summary> /// <param name="csScript">C# script</param> public static void ScriptServer_ConnectDebugger( Object _mainArg = null, CodeType codetype = CodeType.Managed, IEnumerable <String> csScripts = null, String hostExePath = null, String additionCommandLineArguments = "") { mainArg = _mainArg; //--------------------------------------------------------------- // Detect Visual studio, which is debugging us. //--------------------------------------------------------------- Process currentProcess = Process.GetCurrentProcess(); Process debuggerProcess = null; debuggerProcess = GetParentProcess(currentProcess); // // Visual studio is either debug process by itself, or it starts msvsmon.exe, when we locate // parent of parent approach. // if (debuggerProcess != null && debuggerProcess.ProcessName.ToLower() == "msvsmon") { debuggerProcess = GetParentProcess(debuggerProcess); } if (debuggerProcess != null && debuggerProcess.ProcessName.ToLower() != "devenv") { debuggerProcess = null; // Not a visual studio, e.g. cmd } DTE2 dte = null; if (debuggerProcess != null) { MessageFilter.Register(); dte = GetDTE(debuggerProcess.Id); } string[] args = Environment.GetCommandLineArgs(); if (args.Contains(serverSwitch)) { // Breakpoint here will not work, Debugger is not yet attached. for (int i = 0; i < 100; i++) { if (Debugger.IsAttached) { break; } Thread.Sleep(50); } // Breakpoint will start to work after this point. System.Threading.Tasks.Task.Run(() => { IpcServerLoop(); }); if (dte != null) { MessageFilter.Revoke(); } return; } //--------------------------------------------------------------- // Self hosting if not embedded in application //--------------------------------------------------------------- if (hostExePath == null) { hostExePath = Assembly.GetExecutingAssembly().Location; } if (dte != null) { MessageFilter.Register(); if (dte.Debugger.DebuggedProcesses.Count > 1) { // If starting debug with two processes, then wait a little for second to start so 3-rd process won't start Thread.Sleep(500); } bool bAttached = false; String debuggerTypes = "Managed (v4.6, v4.5, v4.0)"; switch (codetype) { case CodeType.Managed: debuggerTypes = "Managed (v4.6, v4.5, v4.0)"; break; case CodeType.Mixed: debuggerTypes = "Managed (v4.6, v4.5, v4.0)|Native"; // Application will terminate when detached from debugger. break; case CodeType.Native: debuggerTypes = "Native"; break; } Debugger2 debugger2 = (Debugger2)dte.Debugger; Transport transport = debugger2.Transports.Item(1 /* Default transport */); String[] debTypes = debuggerTypes.Split('|').ToArray(); Engine[] engines = new Engine[debTypes.Length]; for (int i = 0; i < engines.Length; i++) { engines[i] = transport.Engines.Item(debTypes[i]); } for (int iTry = 0; iTry < 2; iTry++) { var processes = dte.Debugger.LocalProcesses.Cast <Process2>().ToArray(); var exeNames = processes.Select(x => x.Name).ToArray(); for (int i = 0; i < exeNames.Length; i++) { var process = processes[i]; if (exeNames[i] == hostExePath) { var processId = process.ProcessID; String cmdArgs = GetProcessCommandLine(processId); if (cmdArgs == null || !cmdArgs.Contains(serverSwitch)) { continue; } // No need to attach if debugging multiple processes if (dte != null && dte.Debugger.DebuggedProcesses.Count <= 1) { process.Attach2(engines); } foreach (String csScript in csScripts) { new IpcChannel(process.ProcessID).Send(csScript); } bAttached = true; break; } } if (bAttached) { break; } ProcessStartInfo procStartInfo = new ProcessStartInfo(); procStartInfo.Arguments = serverSwitch + " " + additionCommandLineArguments; procStartInfo.CreateNoWindow = true; procStartInfo.FileName = hostExePath; procStartInfo.WorkingDirectory = Environment.CurrentDirectory; Process.Start(procStartInfo); Console.WriteLine("Starting process '" + hostExePath + "'"); //System.Threading.Thread.Sleep(1000); } //for } if (dte != null) { MessageFilter.Revoke(); } Environment.Exit(0); }
internal ShellDebugger(Debugger2 debugger) { _debugger = debugger; }
public AttachToolbarController(DTE2 dte) { _env = dte; _dbg = _env.Debugger as Debugger2; }
/// <summary> /// Client side - see ConnectDebugger description. /// Server side - starts ipc channel / monitors for newly attaching ipc connections. /// </summary> /// <param name="csScript">C# script</param> public static void ScriptServer_ConnectDebugger(CodeType codetype = CodeType.Managed, String csScript = null, String hostExePath = null, String additionCommandLineArguments = "") { //--------------------------------------------------------------- // Detect Visual studio, which is debugging us. //--------------------------------------------------------------- Process currentProcess = Process.GetCurrentProcess(); Process debuggerProcess = null; debuggerProcess = GetParentProcess(currentProcess); // // Visual studio is either debug process by itself, or it starts msvsmon.exe, when we locate // parent of parent approach. // if (debuggerProcess != null && debuggerProcess.ProcessName.ToLower() == "msvsmon") { debuggerProcess = GetParentProcess(debuggerProcess); } if (debuggerProcess != null && debuggerProcess.ProcessName.ToLower() != "devenv") { debuggerProcess = null; // Not a visual studio, e.g. cmd } DTE2 dte = null; if (debuggerProcess != null) { MessageFilter.Register(); dte = GetDTE(debuggerProcess.Id); } string[] args = Environment.GetCommandLineArgs(); if (args.Contains("-Embedding")) { // Breakpoint here will not work, Debugger is not yet attached. for (int i = 0; i < 100; i++) { if (Debugger.IsAttached) { break; } Thread.Sleep(50); } // Breakpoint will start to work after this point. Task.Run(() => { IpcServerLoop(); }); if (csScript == null) { Console.WriteLine("Started with command line arguments: '" + String.Join(" ", args) + "'"); Console.WriteLine("[ Press enter to close host ]"); //Console.ReadLine(); while (true) { if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar == 13) { break; } } // Needed for AppDomain.Unload Application.DoEvents(); Thread.Sleep(50); } } if (dte != null) { MessageFilter.Revoke(); } return; } //--------------------------------------------------------------- // Self hosting if not embedded in application //--------------------------------------------------------------- if (hostExePath == null) { hostExePath = Assembly.GetExecutingAssembly().Location; } if (dte != null) { MessageFilter.Register(); if (dte.Debugger.DebuggedProcesses.Count > 1) { // If starting debug with two processes, then wait a little for second to start so 3-rd process won't start Thread.Sleep(500); } bool bAttached = false; String debuggerTypes = "Managed (v4.6, v4.5, v4.0)"; switch (codetype) { case CodeType.Managed: debuggerTypes = "Managed (v4.6, v4.5, v4.0)"; break; case CodeType.Mixed: debuggerTypes = "Managed (v4.6, v4.5, v4.0)|Native"; // Application will terminate when detached from debugger. break; case CodeType.Native: debuggerTypes = "Native"; break; } Debugger2 debugger2 = (Debugger2)dte.Debugger; Transport transport = debugger2.Transports.Item(1 /* Default transport */); String[] debTypes = debuggerTypes.Split('|').ToArray(); Engine[] engines = new Engine[debTypes.Length]; for (int i = 0; i < engines.Length; i++) { engines[i] = transport.Engines.Item(debTypes[i]); } for (int iTry = 0; iTry < 2; iTry++) { var processes = dte.Debugger.LocalProcesses.Cast <Process2>().ToArray(); var exeNames = processes.Select(x => x.Name).ToArray(); for (int i = 0; i < exeNames.Length; i++) { var process = processes[i]; var processId = process.ProcessID; if (exeNames[i].ToLower() != hostExePath.ToLower()) { continue; } // // Prevents trying to attach to my own process (Normally Visual studio should not be able to see and attach to process // which it debugs, but apparently sometimes it's possible) // String cmdArgs = GetProcessCommandLine(processId); if (cmdArgs == null || !cmdArgs.Contains("-Embedding")) { continue; } // No need to attach if debugging multiple processes if (dte != null && dte.Debugger.DebuggedProcesses.Count <= 1) { process.Attach2(engines); } new IpcChannel(process.ProcessID).Send(csScript); bAttached = true; break; } if (bAttached) { break; } // Don't launch second process if (iTry == 1) { break; } ProcessStartInfo procStartInfo = new ProcessStartInfo(); procStartInfo.Arguments = "-Embedding " + additionCommandLineArguments; procStartInfo.CreateNoWindow = true; procStartInfo.FileName = hostExePath; procStartInfo.WorkingDirectory = Environment.CurrentDirectory; Process.Start(procStartInfo); Console.WriteLine("Starting process '" + hostExePath + "'"); //System.Threading.Thread.Sleep(1000); } //for } if (dte != null) { MessageFilter.Revoke(); } Environment.Exit(0); }