Introduction
Often you can catch yourself doing repetitive work. Sometimes I even manage to get annoyed before I realize what the problem is. This article is about my latest idea: automating the "attach to process" from Visual Studio.
Background
Developing a client/server solution will often bring you in a situation where you start debugging the client and then realize that there is a problem with the server, so you start the client (again) and attach Visual Studio to the server in order to debug the problem. After a while, this routine becomes really annoying. While reading through some of the Microsoft pages regarding EnvDTE, I had an idea. The idea is basically to get hold of the running instance of Visual Studio from the client and use EvnDTE to attach to the server.
Using the Code
I created an extension method to extend the System.Diagnostics.Process
. This seemed rational since I had to use a Process
to start the server from the client.
The code is as follows:
public static void Attach(this System.Diagnostics.Process process)
{
DTE dte;
try
{
dte = (DTE) Marshal.GetActiveObject(progId);
} catch (COMException) {
Debug.WriteLine(String.Format(@"Visual studio not found."));
return;
}
int tryCount = 5;
while (tryCount-- > 0)
{
try
{
Processes processes = dte.Debugger.LocalProcesses;
foreach (Process proc in processes.Cast<Process>().Where(
proc => proc.Name.IndexOf(process.ProcessName) != -1))
{
proc.Attach();
Debug.WriteLine(String.Format
("Attached to process {0} successfully.", process.ProcessName));
break;
}
break;
}
catch (COMException)
{
System.Threading.Thread.Sleep(1000);
}
}
}
Using the extension method can be done like this (example):
Process p = new Process();
FileInfo path = new FileInfo(Assembly.GetExecutingAssembly().Location);
string pathToProcessToDebug = Path.Combine
(path.Directory.FullName, @"..\..\..\ProcessToDebug\Bin\Debug\ProcessToDebug.exe");
ProcessStartInfo psi = new ProcessStartInfo(pathToProcessToDebug);
p.StartInfo = psi;
p.Start()
p.Attach();
Points of Interest
The idea could be implemented in any number of ways, but I was keen on using an extension method. I looked at the System.Diagnistics.Debug
class for an appropriate place to add the method - but static
classes cannot be extended.
History
- Version 1.0 (First version).