calling Roslyn from VSIX command
Frank's answer works great. I found it hard to figure out what the type-names are, so here's Frank's code with fully qualified typenames:
using System.Linq;
var dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
var activeDocument = dte?.ActiveDocument;
if (activeDocument != null)
{
var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
var workspace = (Microsoft.CodeAnalysis.Workspace)componentModel.GetService<Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>();
var documentId = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName).FirstOrDefault();
if (documentId != null)
{
var document = workspace.CurrentSolution.GetDocument(documentId);
}
}
And here are the references to find those types:
- nuget: Microsoft.VisualStudio.Shell.14.0
- nuget: Microsoft.CodeAnalysis
- nuget: Microsoft.VisualStudio.LanguageService
- framework: EnvDTE (version 8.0, and set Embed Interop Types to false)
- framework: Microsoft.VisualStudio.ComponentModelHost
I hope the two framework references can be replaced with NuGet references to VSSDK.DTE and VSSDK.ComponentModelHost, but when I tried, it gave build warnings about assembly version mismatches so I gave up.
You can use workspace.CurrentSolution.GetDocumentIdsWithFilePath() to get the DocumentId(s) matching a file path. From that you can get the document itself using workspace.CurrentSolution.GetDocument()
private Document GetActiveDocument()
{
var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
var activeDocument = dte?.ActiveDocument;
if (activeDocument == null) return null;
var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var workspace = (Workspace) componentModel.GetService<VisualStudioWorkspace>();
var documentid = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName).FirstOrDefault();
if (documentid == null) return null;
return workspace.CurrentSolution.GetDocument(documentid);
}