views:

41

answers:

1

I have a Visual Studio 2010 extension, a .vsix file. I can obtain the DTE instance for my particular instance of Visual Studio, which I confirm by printing the dte_instance.Solution.Fullname. But for my DTE2 instance it appears to be giving me information about the wrong Visual Studio instance.

Here is the work flow: Visual Studio development IDE open, has code for the extension. Launch the project, which causes a new Visual Studio instance to launch which has the extension installed in it. Click my menu button (in the new IDE) that runs the following code:

DTE dte;
DTE2 dte2, dte2Macros;
dte = (DTE)GetService(typeof(DTE));
dte2 = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
dte2Macros = (DTE2)dte2.MacrosIDE;

//this returns what I expect, the solution name in the newer IDE.
MessageBox.Show("solution name: " + dte.Solution.FullName);

//code to get the startup project from MSDN
//http://msdn.microsoft.com/en-us/library/ms228782.aspx
SolutionBuild2 sb = (SolutionBuild2)dte2.Solution.SolutionBuild;
string msg = "";
Int32 configs = sb.SolutionConfigurations.Count;
foreach (String item in (Array)sb.StartupProjects)
{
    msg += item;
}

//this returns a project from the development IDE, the one I don't want.
System.Windows.Forms.MessageBox.Show("startup project is: " + msg);
Project startupProject = dte2.Solution.Item(msg);

I found several references to acquiring the DTE2 object in an addin with the connect() method, but I could not locate a similar callback for extensions.

The question: how does one get the DTE2 instance for the IDE an extension is executing in?

+2  A: 

Try this, which uses an imported service provider, or just use Package.GetGlobalService:

DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;

Noah Richards
Works perfectly, thank you.
Adam
I am having the exact same issue, and I was using the exact same approach as he was, but when I try your solution I get "The name 'Package' does not exist in the current context". What is the correct usage of it ?
MarceloRamires
You'll need a reference to `Microsoft.VisualStudio.Shell.10.0.dll`, and a `using` for `Microsoft.VisualStudio.Shell`.
Noah Richards