diff --git a/ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs b/ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs index aa4c73cfd..443efdd3b 100644 --- a/ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs +++ b/ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs @@ -111,7 +111,7 @@ public override CSharpSyntaxNode VisitCompilationUnit(VBSyntax.CompilationUnitSy foreach (var importClause in importsClauses.OfType()) { importedNamespaces[importClause.Name.ToString()] = importClause.Alias != null ? importClause.Alias.Identifier.ToString() : ""; } - + var attributes = SyntaxFactory.List(node.Attributes.SelectMany(a => a.AttributeLists).SelectMany(ConvertAttribute)); var members = SyntaxFactory.List(node.Members.Select(m => (MemberDeclarationSyntax)m.Accept(TriviaConvertingVisitor))); @@ -161,7 +161,6 @@ IEnumerable ConvertMembers(SyntaxList @@ -37,6 +38,8 @@ public T PortConvertedTrivia(SyntaxNode sourceNode, T destination) where T : destination = destination.ReplaceToken(lastDestToken, WithDelegateToParentAnnotation(sourceNode, lastDestToken)); } + destination = WithAnnotations(sourceNode, destination); + var containingSubModuleBlock = sourceNode.FirstAncestorOrSelf(IsFirstLineOfBlockConstruct); var hasVisitedContainingBlock = containingSubModuleBlock == null; var firstLineOfBlockConstruct = sourceNode.ChildNodes().OfType().FirstOrDefault(IsFirstLineOfBlockConstruct); @@ -54,6 +57,18 @@ public T PortConvertedTrivia(SyntaxNode sourceNode, T destination) where T : return WithTrailingTriviaConversions(destination, sourceNode.Parent?.GetLastToken(), hasVisitedContainingBlock); } + private static T WithAnnotations(SyntaxNode sourceNode, T destination) where T : SyntaxNode + { + destination = sourceNode.CopyAnnotationsTo(destination); + + var sourceChildAnnotations = new HashSet(sourceNode.ChildNodes() + .SelectMany(n => n.GetAnnotations(SelectedNodeAnnotationKind))); + foreach (var annotation in destination.ChildNodes().SelectMany(n => n.GetAnnotations(SelectedNodeAnnotationKind))) { + sourceChildAnnotations.Remove(annotation); + } + return destination.WithAdditionalAnnotations(sourceChildAnnotations); + } + private SyntaxToken MoveChildTrailingEndOfLinesToToken(T destination, SyntaxToken beforeOpenBraceToken) where T : SyntaxNode { diff --git a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs index ae69e3426..615cdf4b5 100644 --- a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs +++ b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using ICSharpCode.CodeConverter.Util; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using ArrayRankSpecifierSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax; using ArrayTypeSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax; @@ -37,11 +36,35 @@ enum TokenContext MemberInInterface } - public static CSharpSyntaxNode ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree) + public static async Task ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree, TextSpan selected) { - return ConvertMultiple(compilation, new[] {syntaxTree}).Values.Single(); + var root = await syntaxTree.GetRootAsync(); + if (selected.Length > 0) { + var annotatedSyntaxTree = GetSyntaxTreeWithAnnotatedSelection(selected, root); + compilation = compilation.ReplaceSyntaxTree(syntaxTree, annotatedSyntaxTree); + syntaxTree = (VBasic.VisualBasicSyntaxTree) annotatedSyntaxTree; + } + + try { + var cSharpSyntaxNode = ConvertSingleUnhandled(compilation, syntaxTree); + var annotatedNode = cSharpSyntaxNode.GetAnnotatedNodes(TriviaConverter.SelectedNodeAnnotationKind).SingleOrDefault(); + if (annotatedNode != null) cSharpSyntaxNode = (CSharpSyntaxNode) annotatedNode; + var formattedNode = Formatter.Format(cSharpSyntaxNode, new AdhocWorkspace()); + return new ConversionResult(formattedNode.ToFullString()); + } catch (Exception ex) { + return new ConversionResult(ex); + } } + private static SyntaxTree GetSyntaxTreeWithAnnotatedSelection(TextSpan selected, SyntaxNode root) + { + var selectedNode = root.FindNode(selected); + var annotatatedNode = selectedNode.WithAdditionalAnnotations(new SyntaxAnnotation(TriviaConverter.SelectedNodeAnnotationKind)); + var syntaxTree = root.ReplaceNode(selectedNode, annotatatedNode).SyntaxTree; + return syntaxTree; + } + + public static Dictionary ConvertMultiple(VBasic.VisualBasicCompilation compilation, IEnumerable syntaxTrees) { var cSharpFirstPass = syntaxTrees.ToDictionary(tree => tree.FilePath ?? "unknown", @@ -50,6 +73,11 @@ public static Dictionary ConvertMultiple(VBasic.Visual return cSharpFirstPass.ToDictionary(cs => cs.Key, cs => new CompilationErrorFixer(cSharpCompilation, cs.Value).Fix()); } + private static CSharpSyntaxNode ConvertSingleUnhandled(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree) + { + return ConvertMultiple(compilation, new[] {syntaxTree}).Values.Single(); + } + private static CSharpSyntaxTree ConvertCompilationTree(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree tree) { var visualBasicSyntaxVisitor = new NodesVisitor(compilation.GetSemanticModel(tree, true)); @@ -65,7 +93,7 @@ public static ConversionResult ConvertText(string text, IReadOnlyCollection references, string text) + private static SyntaxNode ConvertTextUnhandled(IReadOnlyCollection references, string text) { try { @@ -94,7 +122,7 @@ private static SyntaxNode ConvertFullTree(IReadOnlyCollection { var tree = CreateTree(fullTreeText); var compilation = CreateCompilationFromTree(tree, references); - return ConvertSingle(compilation, tree); + return ConvertSingleUnhandled(compilation, tree); } private static VBasic.VisualBasicSyntaxTree CreateTree(string text) diff --git a/ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs b/ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs index 640e566d7..f25e490e4 100644 --- a/ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs +++ b/ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs @@ -404,7 +404,7 @@ public static async Task ReplaceSyntaxAsync( }); // compute replacements for all nodes that will go in the same batch - // only spans that do not overlap go in the same batch. + // only spans that do not overlap go in the same batch. TextSpan previous = default(TextSpan); foreach (var span in spans) { // only add to replacement map if we don't intersect with the previous node. This taken with the sort order diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 7accc19cf..bcaca9d7d 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -1,19 +1,35 @@ -using Microsoft.VisualStudio.Shell; +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using ICSharpCode.CodeConverter; +using ICSharpCode.CodeConverter.CSharp; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.VisualBasic; +using Microsoft.VisualStudio.LanguageServices; +using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; -using System; -using System.Windows; -using ICSharpCode.CodeConverter; +using Task = System.Threading.Tasks.Task; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { - static class CodeConversion + class CodeConversion { + private readonly IServiceProvider serviceProvider; + private readonly VisualStudioWorkspace visualStudioWorkspace; public static readonly string CSToVBConversionTitle = "Convert C# to VB:"; public static readonly string VBToCSConversionTitle = "Convert VB to C#:"; - public static void PerformCSToVBConversion(IServiceProvider serviceProvider, string inputCode) + public CodeConversion(IServiceProvider serviceProvider, VisualStudioWorkspace visualStudioWorkspace) + { + this.serviceProvider = serviceProvider; + this.visualStudioWorkspace = visualStudioWorkspace; + } + + public void PerformCSToVBConversion(string inputCode) { string convertedText = null; try { @@ -46,25 +62,25 @@ public static void PerformCSToVBConversion(IServiceProvider serviceProvider, str // OLEMSGBUTTON.OLEMSGBUTTON_OK, // OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); - WriteStatusBarText(serviceProvider, "Copied converted VB code to clipboard."); + WriteStatusBarText("Copied converted VB code to clipboard."); Clipboard.SetText(convertedText); } - static ConversionResult TryConvertingCSToVBCode(string inputCode) + ConversionResult TryConvertingCSToVBCode(string inputCode) { var codeWithOptions = new CodeWithOptions(inputCode) .SetFromLanguage("C#") .SetToLanguage("Visual Basic") .WithDefaultReferences(); - return CodeConverter.Convert(codeWithOptions); + return ICSharpCode.CodeConverter.CodeConverter.Convert(codeWithOptions); } - public static void PerformVBToCSConversion(IServiceProvider serviceProvider, string inputCode) + public async Task PerformVBToCSConversion(string documentFilePath, Span selected) { string convertedText = null; try { - var result = TryConvertingVBToCSCode(inputCode); + var result = await TryConvertingVBToCSCode(documentFilePath, selected); if (!result.Success) { var newLines = Environment.NewLine + Environment.NewLine; VsShellUtilities.ShowMessageBox( @@ -93,21 +109,23 @@ public static void PerformVBToCSConversion(IServiceProvider serviceProvider, str // OLEMSGBUTTON.OLEMSGBUTTON_OK, // OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); - WriteStatusBarText(serviceProvider, "Copied converted C# code to clipboard."); + WriteStatusBarText("Copied converted C# code to clipboard."); Clipboard.SetText(convertedText); } - static ConversionResult TryConvertingVBToCSCode(string inputCode) - { - var codeWithOptions = new CodeWithOptions(inputCode) - .SetFromLanguage("Visual Basic", 14) - .SetToLanguage("C#", 6) - .WithDefaultReferences(); - return CodeConverter.Convert(codeWithOptions); - } + async Task TryConvertingVBToCSCode(string documentPath, Span selected) + { + //TODO Figure out when there are multiple document ids for a single file path + var documentId = visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(documentPath).Single(); + var document = visualStudioWorkspace.CurrentSolution.GetDocument(documentId); + var compilation = await document.Project.GetCompilationAsync(); + var documentSyntaxTree = await document.GetSyntaxTreeAsync(); - static void WriteStatusBarText(IServiceProvider serviceProvider, string text) + var selectedTextSpan = new TextSpan(selected.Start, selected.Length); + return await VisualBasicConverter.ConvertSingle((VisualBasicCompilation)compilation, (VisualBasicSyntaxTree)documentSyntaxTree, selectedTextSpan); + } + void WriteStatusBarText(string text) { IVsStatusbar statusBar = (IVsStatusbar)serviceProvider.GetService(typeof(SVsStatusbar)); if (statusBar == null) @@ -124,7 +142,7 @@ static void WriteStatusBarText(IServiceProvider serviceProvider, string text) statusBar.FreezeOutput(1); } - static IWpfTextViewHost GetCurrentCSViewHost(IServiceProvider serviceProvider) + IWpfTextViewHost GetCurrentCSViewHost() { IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider); if (viewHost == null) @@ -142,16 +160,16 @@ public static bool IsCSFileName(string fileName) return fileName.EndsWith(".cs", StringComparison.OrdinalIgnoreCase); } - public static ITextSelection GetCSSelectionInCurrentView(IServiceProvider serviceProvider) + public ITextSelection GetCSSelectionInCurrentView() { - IWpfTextViewHost viewHost = GetCurrentCSViewHost(serviceProvider); + IWpfTextViewHost viewHost = GetCurrentCSViewHost(); if (viewHost == null) return null; return viewHost.TextView.Selection; } - static IWpfTextViewHost GetCurrentVBViewHost(IServiceProvider serviceProvider) + public IWpfTextViewHost GetCurrentVBViewHost() { IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider); if (viewHost == null) @@ -169,9 +187,9 @@ public static bool IsVBFileName(string fileName) return fileName.EndsWith(".vb", StringComparison.OrdinalIgnoreCase); } - public static ITextSelection GetVBSelectionInCurrentView(IServiceProvider serviceProvider) + public ITextSelection GetVBSelectionInCurrentView() { - IWpfTextViewHost viewHost = GetCurrentVBViewHost(serviceProvider); + IWpfTextViewHost viewHost = GetCurrentVBViewHost(); if (viewHost == null) return null; diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index e6f473012..021a2d3ba 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -1,9 +1,9 @@ using System; using System.ComponentModel.Design; -using Microsoft.VisualStudio.Shell; using System.IO; +using Microsoft.VisualStudio.Shell; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { /// /// Command handler @@ -32,6 +32,8 @@ public static ConvertCSToVBCommand Instance { private set; } + private readonly CodeConversion codeConversion; + /// /// Gets the service provider from the owner package. /// @@ -57,11 +59,8 @@ public static void Initialize(REConverterPackage package) /// Owner package, not null. ConvertCSToVBCommand(REConverterPackage package) { - if (package == null) { - throw new ArgumentNullException(nameof(package)); - } - - this.package = package; + this.package = package ?? throw new ArgumentNullException(nameof(package)); + codeConversion = new CodeConversion(package, package.VsWorkspace); OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (commandService != null) { @@ -90,7 +89,7 @@ void CodeEditorMenuItem_BeforeQueryStatus(object sender, EventArgs e) var menuItem = sender as OleMenuCommand; if (menuItem != null) { - menuItem.Visible = !CodeConversion.GetCSSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.IsEmpty ?? false; + menuItem.Visible = !codeConversion.GetCSSelectionInCurrentView()?.StreamSelectionSpan.IsEmpty ?? false; } } @@ -101,7 +100,7 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) menuItem.Visible = false; menuItem.Enabled = false; - string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath(); + string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath; var fileInfo = new FileInfo(itemPath); if (!CodeConversion.IsCSFileName(fileInfo.Name)) return; @@ -113,13 +112,13 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) void CodeEditorMenuItemCallback(object sender, EventArgs e) { - string selectedText = CodeConversion.GetCSSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.GetText(); - CodeConversion.PerformCSToVBConversion(ServiceProvider, selectedText); + string selectedText = codeConversion.GetCSSelectionInCurrentView()?.StreamSelectionSpan.GetText(); + codeConversion.PerformCSToVBConversion(selectedText); } async void ProjectItemMenuItemCallback(object sender, EventArgs e) { - string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath(); + string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath; var fileInfo = new FileInfo(itemPath); if (!CodeConversion.IsCSFileName(fileInfo.Name)) return; @@ -127,7 +126,7 @@ async void ProjectItemMenuItemCallback(object sender, EventArgs e) try { using (StreamReader reader = new StreamReader(itemPath)) { string csCode = await reader.ReadToEndAsync(); - CodeConversion.PerformCSToVBConversion(ServiceProvider, csCode); + codeConversion.PerformCSToVBConversion(csCode); } } catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.CSToVBConversionTitle, ex); diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index ede14ecaa..70ebee5f6 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -1,9 +1,12 @@ using System; using System.ComponentModel.Design; -using Microsoft.VisualStudio.Shell; using System.IO; +using System.Linq; +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Text; +using Task = System.Threading.Tasks.Task; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { /// /// Command handler @@ -24,6 +27,8 @@ internal sealed class ConvertVBToCSCommand /// readonly REConverterPackage package; + private CodeConversion codeConversion; + /// /// Gets the instance of the command. /// @@ -62,6 +67,7 @@ public static void Initialize(REConverterPackage package) } this.package = package; + codeConversion = new CodeConversion(package, package.VsWorkspace); OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (commandService != null) { @@ -90,7 +96,7 @@ void CodeEditorMenuItem_BeforeQueryStatus(object sender, EventArgs e) var menuItem = sender as OleMenuCommand; if (menuItem != null) { - menuItem.Visible = !CodeConversion.GetVBSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.IsEmpty ?? false; + menuItem.Visible = !codeConversion.GetVBSelectionInCurrentView()?.StreamSelectionSpan.IsEmpty ?? false; } } @@ -101,7 +107,7 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) menuItem.Visible = false; menuItem.Enabled = false; - string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath(); + string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath; var fileInfo = new FileInfo(itemPath); if (!CodeConversion.IsVBFileName(fileInfo.Name)) return; @@ -111,25 +117,28 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) } } - void CodeEditorMenuItemCallback(object sender, EventArgs e) + async void CodeEditorMenuItemCallback(object sender, EventArgs e) { - string selectedText = CodeConversion.GetVBSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.GetText(); - CodeConversion.PerformVBToCSConversion(ServiceProvider, selectedText); + var span = codeConversion.GetVBSelectionInCurrentView().SelectedSpans.First().Span; + await ConvertVbDocument(codeConversion.GetCurrentVBViewHost().GetTextDocument().FilePath, span); } async void ProjectItemMenuItemCallback(object sender, EventArgs e) { - string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath(); - var fileInfo = new FileInfo(itemPath); + string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath; + await ConvertVbDocument(itemPath, new Span(0,0)); + } + + private async Task ConvertVbDocument(string documentPath, Span selected) + { + var fileInfo = new FileInfo(documentPath); if (!CodeConversion.IsVBFileName(fileInfo.Name)) return; try { - using (StreamReader reader = new StreamReader(itemPath)) { - string csCode = await reader.ReadToEndAsync(); - CodeConversion.PerformVBToCSConversion(ServiceProvider, csCode); - } - } catch (Exception ex) { + await codeConversion.PerformVBToCSConversion(documentPath, selected); + } + catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); } } diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index 2dd45eed1..0d4d5db05 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -1,16 +1,16 @@ -//------------------------------------------------------------------------------ -// -// Copyright (c) Company. All rights reserved. -// -//------------------------------------------------------------------------------ - -using System; +using System; +using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; using System.Runtime.InteropServices; using Microsoft.VisualStudio; +using Microsoft.VisualStudio.ComponentModelHost; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { /// /// This is the class that implements the package exposed by this assembly. @@ -37,6 +37,13 @@ namespace RefactoringEssentials.VsExtension [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")] public sealed class REConverterPackage : Package { + public VisualStudioWorkspace VsWorkspace { + get { + var componentModel = (IComponentModel)GetGlobalService(typeof(SComponentModel)); + return componentModel.GetService(); + } + } + /// /// ConvertCSToVBCommandPackage GUID string. /// @@ -47,12 +54,39 @@ public sealed class REConverterPackage : Package /// public REConverterPackage() { + AppDomain.CurrentDomain.AssemblyResolve += LoadWithoutVersionForOurDependencies; // Inside this method you can place any initialization code that does not require // any Visual Studio service because at this point the package object is created but // not sited yet inside Visual Studio environment. The place to do all the other // initialization is the Initialize method. } + private Assembly LoadWithoutVersionForOurDependencies(object sender, ResolveEventArgs args) + { + var requestedAssemblyName = new AssemblyName(args.Name); + if (requestedAssemblyName.Version != null && IsThisExtensionRequestingAssembly()) { + return LoadAnyVersionOfAssembly(requestedAssemblyName); + } + return null; + + } + + private static Assembly LoadAnyVersionOfAssembly(AssemblyName assemblyName) + { + return Assembly.Load(new AssemblyName(assemblyName.Name){CultureName = assemblyName.CultureName}); + } + + private bool IsThisExtensionRequestingAssembly() + { + return GetPossibleRequestingAssemblies().Contains(GetType().Assembly); + } + + private IEnumerable GetPossibleRequestingAssemblies() + { + return new StackTrace().GetFrames().Select(f => f.GetMethod().DeclaringType?.Assembly) + .SkipWhile(a => a == GetType().Assembly); + } + /// /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. diff --git a/Vsix/VSPackage.resx b/Vsix/VSPackage.resx index 6c5efe145..25c6a537f 100644 --- a/Vsix/VSPackage.resx +++ b/Vsix/VSPackage.resx @@ -26,7 +26,7 @@ [base64 mime encoded string representing a byte array form of the .NET Framework object] This is a comment - + There are any number of "resheader" rows that contain simple name/value pairs. diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index 9f41774b6..ba9acef97 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -1,53 +1,50 @@ -using Microsoft.VisualStudio; +using System; +using System.Runtime.InteropServices; +using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; -using System; -using System.Runtime.InteropServices; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { static class VisualStudioInteraction { - public static bool GetSingleSelectedItem(out IVsHierarchy hierarchy, out uint itemID) + public static VsDocument GetSingleSelectedItemOrDefault() { - hierarchy = null; - itemID = VSConstants.VSITEMID_NIL; - int hresult = VSConstants.S_OK; - var monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; var solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution; + if ((monitorSelection == null) || (solution == null)) - return false; + return null; - IVsMultiItemSelect multiItemSelect = null; IntPtr hierarchyPtr = IntPtr.Zero; IntPtr selectionContainerPtr = IntPtr.Zero; try { - hresult = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemID, out multiItemSelect, out selectionContainerPtr); + var hresult = monitorSelection.GetCurrentSelection(out hierarchyPtr, out uint itemID, out var multiItemSelect, out selectionContainerPtr); if (ErrorHandler.Failed(hresult) || (hierarchyPtr == IntPtr.Zero) || (itemID == VSConstants.VSITEMID_NIL)) - return false; + return null; if (multiItemSelect != null) - return false; + return null; if (itemID == VSConstants.VSITEMID_ROOT) - return false; + return null; - hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; + var hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy; if (hierarchy == null) - return false; + return null; Guid guidProjectID = Guid.Empty; if (ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out guidProjectID))) - return false; + return null; - return true; + return new VsDocument((IVsProject) hierarchy, guidProjectID, itemID); } finally { if (selectionContainerPtr != IntPtr.Zero) { Marshal.Release(selectionContainerPtr); @@ -59,18 +56,6 @@ public static bool GetSingleSelectedItem(out IVsHierarchy hierarchy, out uint it } } - public static string GetSingleSelectedItemPath() - { - IVsHierarchy hierarchy = null; - uint itemID = VSConstants.VSITEMID_NIL; - if (!GetSingleSelectedItem(out hierarchy, out itemID)) - return null; - - string itemPath = null; - ((IVsProject)hierarchy).GetMkDocument(itemID, out itemPath); - return itemPath; - } - public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider) { IVsTextManager txtMgr = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager)); @@ -95,6 +80,11 @@ public static ITextDocument GetTextDocument(this IWpfTextViewHost viewHost) return textDocument; } + public static VisualStudioWorkspace GetWorkspace(IServiceProvider serviceProvider) + { + return (VisualStudioWorkspace) serviceProvider.GetService(typeof(VisualStudioWorkspace)); + } + public static void ShowException(IServiceProvider serviceProvider, string title, Exception ex) { VsShellUtilities.ShowMessageBox( diff --git a/Vsix/VsDocument.cs b/Vsix/VsDocument.cs new file mode 100644 index 000000000..ca7360da1 --- /dev/null +++ b/Vsix/VsDocument.cs @@ -0,0 +1,27 @@ +using System; +using Microsoft.VisualStudio.Shell.Interop; + +namespace CodeConverter.VsExtension +{ + class VsDocument + { + private readonly IVsProject hierarchy; + private readonly uint itemId; + public Guid ProjectGuid { get; } + + public VsDocument(IVsProject hierarchy, Guid projectGuid, uint itemId) + { + this.hierarchy = hierarchy; + ProjectGuid = projectGuid; + this.itemId = itemId; + } + + public string ItemPath { + get { + string itemPath = null; + hierarchy.GetMkDocument(itemId, out itemPath); + return itemPath; + } + } + } +} \ No newline at end of file diff --git a/Vsix/Vsix.csproj b/Vsix/Vsix.csproj index 6924ca142..8d97ca313 100644 --- a/Vsix/Vsix.csproj +++ b/Vsix/Vsix.csproj @@ -124,11 +124,39 @@ False + + ..\packages\ManagedEsent.1.9.4\lib\net40\Esent.Interop.dll + + + ..\packages\Microsoft.CodeAnalysis.Common.2.6.1\lib\netstandard1.3\Microsoft.CodeAnalysis.dll + + + ..\packages\Microsoft.CodeAnalysis.CSharp.2.6.1\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.dll + + + ..\packages\Microsoft.CodeAnalysis.CSharp.Workspaces.2.6.1\lib\netstandard1.3\Microsoft.CodeAnalysis.CSharp.Workspaces.dll + + + ..\packages\Microsoft.CodeAnalysis.Elfie.0.10.6\lib\net46\Microsoft.CodeAnalysis.Elfie.dll + + + ..\packages\Microsoft.CodeAnalysis.VisualBasic.2.6.1\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.dll + + + ..\packages\Microsoft.CodeAnalysis.VisualBasic.Workspaces.2.6.1\lib\netstandard1.3\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll + + + ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.6.1\lib\net46\Microsoft.CodeAnalysis.Workspaces.dll + + + ..\packages\Microsoft.CodeAnalysis.Workspaces.Common.2.6.1\lib\net46\Microsoft.CodeAnalysis.Workspaces.Desktop.dll + False + ..\packages\Microsoft.VisualStudio.CoreUtility.15.0.26201\lib\net45\Microsoft.VisualStudio.CoreUtility.dll True @@ -141,6 +169,9 @@ ..\packages\Microsoft.VisualStudio.Imaging.15.0.26201\lib\net45\Microsoft.VisualStudio.Imaging.dll True + + ..\packages\Microsoft.VisualStudio.LanguageServices.2.6.1\lib\net46\Microsoft.VisualStudio.LanguageServices.dll + ..\packages\Microsoft.VisualStudio.OLE.Interop.7.10.6070\lib\Microsoft.VisualStudio.OLE.Interop.dll True @@ -232,11 +263,79 @@ False + + ..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll + True + + + ..\packages\System.Collections.Immutable.1.4.0\lib\netstandard2.0\System.Collections.Immutable.dll + + + + ..\packages\System.Console.4.3.0\lib\net46\System.Console.dll + + + ..\packages\System.Diagnostics.FileVersionInfo.4.3.0\lib\net46\System.Diagnostics.FileVersionInfo.dll + + + ..\packages\System.Diagnostics.StackTrace.4.3.0\lib\net46\System.Diagnostics.StackTrace.dll + + + ..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll + True + + + ..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll + + + ..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll + + + + ..\packages\System.Reflection.Metadata.1.5.0\lib\netstandard2.0\System.Reflection.Metadata.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.1\lib\net461\System.Security.Cryptography.Algorithms.dll + True + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.2\lib\net461\System.Security.Cryptography.X509Certificates.dll + True + + + ..\packages\System.Text.Encoding.CodePages.4.4.0\lib\net461\System.Text.Encoding.CodePages.dll + + + ..\packages\System.Threading.Thread.4.3.0\lib\net46\System.Threading.Thread.dll + + + ..\packages\System.ValueTuple.4.4.0\lib\net461\System.ValueTuple.dll + True + + + + ..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll + + + ..\packages\System.Xml.XmlDocument.4.3.0\lib\net46\System.Xml.XmlDocument.dll + + + ..\packages\System.Xml.XPath.4.3.0\lib\net46\System.Xml.XPath.dll + + + ..\packages\System.Xml.XPath.XDocument.4.3.0\lib\net46\System.Xml.XPath.XDocument.dll + @@ -254,6 +353,7 @@ + @@ -268,6 +368,10 @@ ICSharpCode.CodeConverter + + + + diff --git a/Vsix/app.config b/Vsix/app.config index d471e21cd..585ef867b 100644 --- a/Vsix/app.config +++ b/Vsix/app.config @@ -8,7 +8,7 @@ - + @@ -30,6 +30,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Vsix/packages.config b/Vsix/packages.config index 0c130f32b..2ad417764 100644 --- a/Vsix/packages.config +++ b/Vsix/packages.config @@ -1,8 +1,20 @@  + + + + + + + + + + + + @@ -25,4 +37,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file