views:

135

answers:

1

I'm writing a Visual Studio editor extension using the VS 2010 SDK RC. I'd like to be able to figure out what the references of the current project are. How do I get access to the project corresponding to the current editor?

The documentation on editor extensions doesn't seem to include information on how to access non-editor parts of Visual Studio. I did some searching and it looks like in VS2008 you could write add-ins that would access the project system, but I'm trying to get at this functionality from a MEF editor extension.

+3  A: 

Daniel --

Getting from the editor to the project is a multiple step process. First, you get the filename of the file in the editor, and from there you can find the containing project.

Assuming you've got an IWPFTextView, you can get the filename like this:

public static string GetFilePath(Microsoft.VisualStudio.Text.Editor.IWpfTextView wpfTextView)
{
    Microsoft.VisualStudio.Text.ITextDocument document;
    if ((wpfTextView == null) ||
            (!wpfTextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(Microsoft.VisualStudio.Text.ITextDocument), out document)))
        return String.Empty;

    // If we have no document, just ignore it.
    if ((document == null) || (document.TextBuffer == null))
        return String.Empty;

    return document.FilePath;
}

Once you've got a filename, you can get it's parent project like this:

using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Interop;

public static Project GetContainingProject(string fileName)
{
    if (!String.IsNullOrEmpty(fileName))
    {
        var dte2 = (DTE2)Package.GetGlobalService(typeof(SDTE));
        if (dte2 != null)
        {
            var prjItem = dte2.Solution.FindProjectItem(fileName);
            if (prjItem != null)
                return prjItem.ContainingProject;
        }
    }
    return null;
}

From the project you can get to the codemodel, and I assume the references, but I haven't needed to do that yet.

Hope this helps...

~ Cameron

Cameron Peters
Thanks! To get the references, you need to get a VSProject object. You can cast the Project.Object to a VSProject: if (project.Object is VSProject) { var vsProject = (VSProject)project.Object; /* ... */ }
Daniel Plaisted