From 381e006d210a19eb8c3569e171acd99174c5228b Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Thu, 11 Jan 2018 22:37:07 +0000 Subject: [PATCH 01/11] Load workspace --- Vsix/REConverterPackage.cs | 9 ++++ Vsix/Vsix.csproj | 103 +++++++++++++++++++++++++++++++++++++ Vsix/app.config | 62 +++++++++++++++++++++- Vsix/packages.config | 58 +++++++++++++++++++++ 4 files changed, 231 insertions(+), 1 deletion(-) diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index 2dd45eed1..f43964dc5 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -5,9 +5,13 @@ //------------------------------------------------------------------------------ using System; +using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis; using Microsoft.VisualStudio; +using Microsoft.VisualStudio.ComponentModelHost; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; namespace RefactoringEssentials.VsExtension @@ -37,6 +41,8 @@ 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; private set; } + /// /// ConvertCSToVBCommandPackage GUID string. /// @@ -52,6 +58,7 @@ public REConverterPackage() // not sited yet inside Visual Studio environment. The place to do all the other // initialization is the Initialize method. } + /// /// Initialization of the package; this method is called right after the package is sited, so this is the place @@ -61,6 +68,8 @@ protected override void Initialize() { ConvertCSToVBCommand.Initialize(this); ConvertVBToCSCommand.Initialize(this); + var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel)); + VsWorkspace = componentModel.GetService(); base.Initialize(); } } diff --git a/Vsix/Vsix.csproj b/Vsix/Vsix.csproj index 6924ca142..ce0a44f03 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 + @@ -268,6 +367,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 From 52380dff3d13b4099d6525253004fdf41db2acb4 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Thu, 11 Jan 2018 22:16:19 +0000 Subject: [PATCH 02/11] Create first class type instead of two out parameters --- Vsix/VisualStudioInteraction.cs | 35 +++++++++++---------------------- Vsix/VsDocument.cs | 27 +++++++++++++++++++++++++ Vsix/Vsix.csproj | 1 + 3 files changed, 40 insertions(+), 23 deletions(-) create mode 100644 Vsix/VsDocument.cs diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index 9f41774b6..3101c3bb6 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -12,42 +12,38 @@ namespace RefactoringEssentials.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); @@ -61,14 +57,7 @@ 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; + return GetSingleSelectedItemOrDefault()?.ItemPath; } public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider) diff --git a/Vsix/VsDocument.cs b/Vsix/VsDocument.cs new file mode 100644 index 000000000..fb53579ad --- /dev/null +++ b/Vsix/VsDocument.cs @@ -0,0 +1,27 @@ +using System; +using Microsoft.VisualStudio.Shell.Interop; + +namespace RefactoringEssentials.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 ce0a44f03..8d97ca313 100644 --- a/Vsix/Vsix.csproj +++ b/Vsix/Vsix.csproj @@ -353,6 +353,7 @@ + From 6c63decdc00ece34aed8d5bfd1593b773c259bcc Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Thu, 11 Jan 2018 23:02:16 +0000 Subject: [PATCH 03/11] Stash away workspace --- .../CSharp/VisualBasicConverter.cs | 21 +++++++--- Vsix/CodeConversion.cs | 39 ++++++++++++------- Vsix/ConvertCSToVBCommand.cs | 11 ++++-- Vsix/ConvertVBToCSCommand.cs | 13 ++++--- Vsix/VisualStudioInteraction.cs | 7 ++++ 5 files changed, 62 insertions(+), 29 deletions(-) diff --git a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs index ae69e3426..8477e8390 100644 --- a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs +++ b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs @@ -37,9 +37,15 @@ enum TokenContext MemberInInterface } - public static CSharpSyntaxNode ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree) + public static ConversionResult ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree) { - return ConvertMultiple(compilation, new[] {syntaxTree}).Values.Single(); + try { + var cSharpSyntaxNode = ConvertSingleUnhandled(compilation, syntaxTree); + var formattedNode = Formatter.Format(cSharpSyntaxNode, new AdhocWorkspace()); + return new ConversionResult(formattedNode.ToFullString()); + } catch (Exception ex) { + return new ConversionResult(ex); + } } public static Dictionary ConvertMultiple(VBasic.VisualBasicCompilation compilation, IEnumerable syntaxTrees) @@ -50,6 +56,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 +76,7 @@ public static ConversionResult ConvertText(string text, IReadOnlyCollection references, string text) + private static SyntaxNode ConvertTextUnhandled(IReadOnlyCollection references, string text) { try { @@ -94,7 +105,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/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 7accc19cf..7d0bd3b82 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -5,15 +5,24 @@ using System; using System.Windows; using ICSharpCode.CodeConverter; +using Microsoft.VisualStudio.LanguageServices; namespace RefactoringEssentials.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,12 +55,12 @@ 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#") @@ -60,11 +69,11 @@ static ConversionResult TryConvertingCSToVBCode(string inputCode) return CodeConverter.Convert(codeWithOptions); } - public static void PerformVBToCSConversion(IServiceProvider serviceProvider, string inputCode) + public void PerformVBToCSConversion(string inputCode) { string convertedText = null; try { - var result = TryConvertingVBToCSCode(inputCode); + var result = TryConvertingVBToCSCode(inputCode); // Switch to calling VisualBasicConverter.ConvertSingle() directly with the relevant workspace document if (!result.Success) { var newLines = Environment.NewLine + Environment.NewLine; VsShellUtilities.ShowMessageBox( @@ -93,12 +102,12 @@ 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) + ConversionResult TryConvertingVBToCSCode(string inputCode) { var codeWithOptions = new CodeWithOptions(inputCode) .SetFromLanguage("Visual Basic", 14) @@ -107,7 +116,7 @@ static ConversionResult TryConvertingVBToCSCode(string inputCode) return CodeConverter.Convert(codeWithOptions); } - static void WriteStatusBarText(IServiceProvider serviceProvider, string text) + void WriteStatusBarText(string text) { IVsStatusbar statusBar = (IVsStatusbar)serviceProvider.GetService(typeof(SVsStatusbar)); if (statusBar == null) @@ -124,7 +133,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 +151,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) + IWpfTextViewHost GetCurrentVBViewHost() { IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider); if (viewHost == null) @@ -169,9 +178,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..53667719a 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -32,6 +32,8 @@ public static ConvertCSToVBCommand Instance { private set; } + private readonly CodeConversion codeConversion; + /// /// Gets the service provider from the owner package. /// @@ -62,6 +64,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 +93,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; } } @@ -113,8 +116,8 @@ 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) @@ -127,7 +130,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..b35e4a42f 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -24,6 +24,8 @@ internal sealed class ConvertVBToCSCommand /// readonly REConverterPackage package; + private CodeConversion codeConversion; + /// /// Gets the instance of the command. /// @@ -62,6 +64,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) { @@ -89,8 +92,8 @@ 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; } } @@ -113,8 +116,8 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) void CodeEditorMenuItemCallback(object sender, EventArgs e) { - string selectedText = CodeConversion.GetVBSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.GetText(); - CodeConversion.PerformVBToCSConversion(ServiceProvider, selectedText); + string selectedText = codeConversion.GetVBSelectionInCurrentView()?.StreamSelectionSpan.GetText(); + codeConversion.PerformVBToCSConversion(selectedText); } async void ProjectItemMenuItemCallback(object sender, EventArgs e) @@ -127,7 +130,7 @@ async void ProjectItemMenuItemCallback(object sender, EventArgs e) try { using (StreamReader reader = new StreamReader(itemPath)) { string csCode = await reader.ReadToEndAsync(); - CodeConversion.PerformVBToCSConversion(ServiceProvider, csCode); + codeConversion.PerformVBToCSConversion(csCode); } } catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index 3101c3bb6..73c60b251 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -7,6 +7,8 @@ using Microsoft.VisualStudio.TextManager.Interop; using System; using System.Runtime.InteropServices; +using Microsoft.VisualStudio.LanguageServices; + namespace RefactoringEssentials.VsExtension { @@ -84,6 +86,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( From 1deeaef25c7302bdea12e7e0bf7a1a5d6d6fcd4c Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Thu, 11 Jan 2018 23:02:50 +0000 Subject: [PATCH 04/11] Use VisualStudioWorkspace with the user's actual references --- Vsix/CodeConversion.cs | 25 ++++++++++++++++--------- Vsix/ConvertCSToVBCommand.cs | 4 ++-- Vsix/ConvertVBToCSCommand.cs | 27 ++++++++++++++++----------- Vsix/REConverterPackage.cs | 9 ++++++--- Vsix/VisualStudioInteraction.cs | 5 ----- 5 files changed, 40 insertions(+), 30 deletions(-) diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 7d0bd3b82..fcfa15e7d 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -3,9 +3,16 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; using System.Windows; using ICSharpCode.CodeConverter; +using ICSharpCode.CodeConverter.CSharp; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.LanguageServices; +using Task = System.Threading.Tasks.Task; namespace RefactoringEssentials.VsExtension { @@ -69,11 +76,11 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) return CodeConverter.Convert(codeWithOptions); } - public void PerformVBToCSConversion(string inputCode) + public async Task PerformVBToCSConversion(string documentFilePath) { string convertedText = null; try { - var result = TryConvertingVBToCSCode(inputCode); // Switch to calling VisualBasicConverter.ConvertSingle() directly with the relevant workspace document + var result = await TryConvertingVBToCSCode(documentFilePath); if (!result.Success) { var newLines = Environment.NewLine + Environment.NewLine; VsShellUtilities.ShowMessageBox( @@ -107,13 +114,13 @@ public void PerformVBToCSConversion(string inputCode) Clipboard.SetText(convertedText); } - ConversionResult TryConvertingVBToCSCode(string inputCode) + async Task TryConvertingVBToCSCode(string documentPath) { - var codeWithOptions = new CodeWithOptions(inputCode) - .SetFromLanguage("Visual Basic", 14) - .SetToLanguage("C#", 6) - .WithDefaultReferences(); - return CodeConverter.Convert(codeWithOptions); + var documentId = visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(documentPath).Single(); + var document = visualStudioWorkspace.CurrentSolution.GetDocument(documentId); + var syntaxTree = await document.GetSyntaxTreeAsync(); + var compilation = await document.Project.GetCompilationAsync(); + return VisualBasicConverter.ConvertSingle((VisualBasicCompilation)compilation, (VisualBasicSyntaxTree)syntaxTree); } void WriteStatusBarText(string text) @@ -160,7 +167,7 @@ public ITextSelection GetCSSelectionInCurrentView() return viewHost.TextView.Selection; } - IWpfTextViewHost GetCurrentVBViewHost() + public IWpfTextViewHost GetCurrentVBViewHost() { IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider); if (viewHost == null) diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index 53667719a..963849b0e 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -104,7 +104,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; @@ -122,7 +122,7 @@ void CodeEditorMenuItemCallback(object sender, EventArgs e) 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; diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index b35e4a42f..895f2f922 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -2,6 +2,8 @@ using System.ComponentModel.Design; using Microsoft.VisualStudio.Shell; using System.IO; +using System.Linq; +using Task = System.Threading.Tasks.Task; namespace RefactoringEssentials.VsExtension { @@ -104,7 +106,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; @@ -114,25 +116,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()?.StreamSelectionSpan.GetText(); - codeConversion.PerformVBToCSConversion(selectedText); + //string selectedText = codeConversion.GetVBSelectionInCurrentView()?.StreamSelectionSpan.GetText(); //TODO implement for selection only here again by passing span + await ConvertVbDocument(codeConversion.GetCurrentVBViewHost().GetTextDocument().FilePath); } async void ProjectItemMenuItemCallback(object sender, EventArgs e) { - string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath(); - var fileInfo = new FileInfo(itemPath); + string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath; + await ConvertVbDocument(itemPath); + } + + private async Task ConvertVbDocument(string documentPath) + { + 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(csCode); - } - } catch (Exception ex) { + await codeConversion.PerformVBToCSConversion(documentPath);//TODO Figure out when there are multiple document ids for a single file path + } + catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); } } diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index f43964dc5..c504f33a0 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -41,7 +41,12 @@ 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; private set; } + public VisualStudioWorkspace VsWorkspace { + get { + var componentModel = (IComponentModel)GetGlobalService(typeof(SComponentModel)); + return componentModel.GetService(); + } + } /// /// ConvertCSToVBCommandPackage GUID string. @@ -68,8 +73,6 @@ protected override void Initialize() { ConvertCSToVBCommand.Initialize(this); ConvertVBToCSCommand.Initialize(this); - var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel)); - VsWorkspace = componentModel.GetService(); base.Initialize(); } } diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index 73c60b251..74a8ccd9a 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -57,11 +57,6 @@ public static VsDocument GetSingleSelectedItemOrDefault() } } - public static string GetSingleSelectedItemPath() - { - return GetSingleSelectedItemOrDefault()?.ItemPath; - } - public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider) { IVsTextManager txtMgr = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager)); From ce23077a1f5540a1f1307b669a8eafc22e934a92 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Fri, 12 Jan 2018 19:52:07 +0000 Subject: [PATCH 05/11] Deal with selection We'd probably get a better conversion out of converting a whole file then picking a subset, but since I don't actually understand the use case, the effort isn't really worth it here. --- Vsix/CodeConversion.cs | 20 +++++++++++++++----- Vsix/ConvertVBToCSCommand.cs | 9 +++++---- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index fcfa15e7d..1bdaf7644 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -10,6 +10,7 @@ using ICSharpCode.CodeConverter; using ICSharpCode.CodeConverter.CSharp; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.LanguageServices; using Task = System.Threading.Tasks.Task; @@ -76,11 +77,11 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) return CodeConverter.Convert(codeWithOptions); } - public async Task PerformVBToCSConversion(string documentFilePath) + public async Task PerformVBToCSConversion(string documentFilePath, string selectionText) { string convertedText = null; try { - var result = await TryConvertingVBToCSCode(documentFilePath); + var result = await TryConvertingVBToCSCode(documentFilePath, selectionText); if (!result.Success) { var newLines = Environment.NewLine + Environment.NewLine; VsShellUtilities.ShowMessageBox( @@ -114,15 +115,24 @@ public async Task PerformVBToCSConversion(string documentFilePath) Clipboard.SetText(convertedText); } - async Task TryConvertingVBToCSCode(string documentPath) - { + async Task TryConvertingVBToCSCode(string documentPath, string selectionText) + { + //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 syntaxTree = await document.GetSyntaxTreeAsync(); var compilation = await document.Project.GetCompilationAsync(); + var syntaxTree = await GetSyntaxTree(document, selectionText); return VisualBasicConverter.ConvertSingle((VisualBasicCompilation)compilation, (VisualBasicSyntaxTree)syntaxTree); } + private static async Task GetSyntaxTree(Document document, string selectionText) + { + if (string.IsNullOrWhiteSpace(selectionText)) { + return await document.GetSyntaxTreeAsync(); + } + return SyntaxFactory.ParseSyntaxTree(SourceText.From(selectionText)); + } + void WriteStatusBarText(string text) { IVsStatusbar statusBar = (IVsStatusbar)serviceProvider.GetService(typeof(SVsStatusbar)); diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index 895f2f922..7b599070e 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -3,6 +3,7 @@ using Microsoft.VisualStudio.Shell; using System.IO; using System.Linq; +using Microsoft.VisualStudio.Text; using Task = System.Threading.Tasks.Task; namespace RefactoringEssentials.VsExtension @@ -118,8 +119,8 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) async void CodeEditorMenuItemCallback(object sender, EventArgs e) { - //string selectedText = codeConversion.GetVBSelectionInCurrentView()?.StreamSelectionSpan.GetText(); //TODO implement for selection only here again by passing span - await ConvertVbDocument(codeConversion.GetCurrentVBViewHost().GetTextDocument().FilePath); + string selectedText = codeConversion.GetVBSelectionInCurrentView().StreamSelectionSpan.GetText(); + await ConvertVbDocument(codeConversion.GetCurrentVBViewHost().GetTextDocument().FilePath, selectedText); } async void ProjectItemMenuItemCallback(object sender, EventArgs e) @@ -128,14 +129,14 @@ async void ProjectItemMenuItemCallback(object sender, EventArgs e) await ConvertVbDocument(itemPath); } - private async Task ConvertVbDocument(string documentPath) + private async Task ConvertVbDocument(string documentPath, string selectionText = "") { var fileInfo = new FileInfo(documentPath); if (!CodeConversion.IsVBFileName(fileInfo.Name)) return; try { - await codeConversion.PerformVBToCSConversion(documentPath);//TODO Figure out when there are multiple document ids for a single file path + await codeConversion.PerformVBToCSConversion(documentPath, selectionText); } catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); From eed2cb53349b1d313bf7da8ae8299fddb81875ce Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 09:39:40 +0000 Subject: [PATCH 06/11] Fix namespaces --- Vsix/CodeConversion.cs | 15 +++++++-------- Vsix/ConvertCSToVBCommand.cs | 4 ++-- Vsix/ConvertVBToCSCommand.cs | 6 ++---- Vsix/REConverterPackage.cs | 4 +--- Vsix/VisualStudioInteraction.cs | 11 +++++------ Vsix/VsDocument.cs | 2 +- 6 files changed, 18 insertions(+), 24 deletions(-) diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 1bdaf7644..9f9cb0ec5 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -1,9 +1,4 @@ -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using System; -using System.Collections.Immutable; +using System; using System.Linq; using System.Threading.Tasks; using System.Windows; @@ -13,9 +8,13 @@ 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 Task = System.Threading.Tasks.Task; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { class CodeConversion { @@ -74,7 +73,7 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) .SetFromLanguage("C#") .SetToLanguage("Visual Basic") .WithDefaultReferences(); - return CodeConverter.Convert(codeWithOptions); + return ICSharpCode.CodeConverter.CodeConverter.Convert(codeWithOptions); } public async Task PerformVBToCSConversion(string documentFilePath, string selectionText) diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index 963849b0e..b8d90d947 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 diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index 7b599070e..2d8bc9521 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -1,12 +1,10 @@ using System; using System.ComponentModel.Design; -using Microsoft.VisualStudio.Shell; using System.IO; -using System.Linq; -using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { /// /// Command handler diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index c504f33a0..eaa4985b9 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -5,16 +5,14 @@ //------------------------------------------------------------------------------ using System; -using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis; 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. diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index 74a8ccd9a..ba9acef97 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -1,16 +1,15 @@ -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; -using Microsoft.VisualStudio.LanguageServices; - -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { static class VisualStudioInteraction { diff --git a/Vsix/VsDocument.cs b/Vsix/VsDocument.cs index fb53579ad..ca7360da1 100644 --- a/Vsix/VsDocument.cs +++ b/Vsix/VsDocument.cs @@ -1,7 +1,7 @@ using System; using Microsoft.VisualStudio.Shell.Interop; -namespace RefactoringEssentials.VsExtension +namespace CodeConverter.VsExtension { class VsDocument { From 5ff661cc0f700a786dd0bb19632606cbfa6b7e1b Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 10:03:01 +0000 Subject: [PATCH 07/11] Allow our extension to load any version of the assemblies lying around This only kicks in when the runtime is already having difficulty finding the required assembly anyway. This way we be sure of compatibility with the latest version if we compile against the latest assembly shipped with VS, then just hope for compatibility with older versions. The alternative is to compile against the oldest versions of the assemblies for a version of VS we care about, and rely on Visual Studio's own binding redirects (or our advice to it in assemblyinfo) to sort things out. The APIs we're using are quite stable, but I'd rather old versions break than new versions since "please upgrade VS" is a better response to a bug report than "please downgrade VS". If we get lots of MissingMethodException bug reports, we'll have to reconsider this. --- Vsix/REConverterPackage.cs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index eaa4985b9..84b1bd9b6 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -5,7 +5,11 @@ //------------------------------------------------------------------------------ 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; @@ -56,12 +60,39 @@ public VisualStudioWorkspace VsWorkspace { /// 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 From 7f47412fa2dc077315ffea561368423399c00993 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 10:03:14 +0000 Subject: [PATCH 08/11] Remove empty header placeholder, git contains the license details --- Vsix/REConverterPackage.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index 84b1bd9b6..05ff58081 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -1,10 +1,4 @@ -//------------------------------------------------------------------------------ -// -// Copyright (c) Company. All rights reserved. -// -//------------------------------------------------------------------------------ - -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; From b9946ba8a604bbb471f66133bc1b421a184d87a5 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 10:04:49 +0000 Subject: [PATCH 09/11] Join null check with assignment --- Vsix/ConvertCSToVBCommand.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index b8d90d947..021a2d3ba 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -59,11 +59,7 @@ 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; From 8bcba796cc0204d222d1f0101c3cca7b2afa67e1 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 11:15:56 +0000 Subject: [PATCH 10/11] Use annotations to keep track of the node to be converted. The benefit over converting just the selected characters is that we're converting what's hopefully a well formed document, so the rest of the document can be used for context, and returning something that represents a node, rather than trying to convert the text "tring", when someone slightly mis-selects. If two layers of the node hierarachy fail to go through the trivia converter, then the whole document will be converted, which seems like an OK failure case. --- .../CSharp/TriviaConverter.cs | 15 ++++++++++++ .../CSharp/VisualBasicConverter.cs | 23 ++++++++++++++++--- Vsix/CodeConversion.cs | 19 +++++---------- Vsix/ConvertVBToCSCommand.cs | 12 ++++++---- 4 files changed, 48 insertions(+), 21 deletions(-) diff --git a/ICSharpCode.CodeConverter/CSharp/TriviaConverter.cs b/ICSharpCode.CodeConverter/CSharp/TriviaConverter.cs index ef61a202a..ffde10dc0 100644 --- a/ICSharpCode.CodeConverter/CSharp/TriviaConverter.cs +++ b/ICSharpCode.CodeConverter/CSharp/TriviaConverter.cs @@ -10,6 +10,7 @@ namespace ICSharpCode.CodeConverter.CSharp { public class TriviaConverter { + public const string SelectedNodeAnnotationKind = "CodeConverter.SelectedNode"; private static readonly string TrailingTriviaConversionKind = $"{nameof(TriviaConverter)}.TrailingTriviaConversion.Id"; /// @@ -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 8477e8390..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,10 +36,19 @@ enum TokenContext MemberInInterface } - public static ConversionResult ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree) + public static async Task ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree, TextSpan selected) { + 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) { @@ -48,6 +56,15 @@ public static ConversionResult ConvertSingle(VBasic.VisualBasicCompilation compi } } + 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", diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 9f9cb0ec5..bcaca9d7d 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -76,11 +76,11 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) return ICSharpCode.CodeConverter.CodeConverter.Convert(codeWithOptions); } - public async Task PerformVBToCSConversion(string documentFilePath, string selectionText) + public async Task PerformVBToCSConversion(string documentFilePath, Span selected) { string convertedText = null; try { - var result = await TryConvertingVBToCSCode(documentFilePath, selectionText); + var result = await TryConvertingVBToCSCode(documentFilePath, selected); if (!result.Success) { var newLines = Environment.NewLine + Environment.NewLine; VsShellUtilities.ShowMessageBox( @@ -114,24 +114,17 @@ public async Task PerformVBToCSConversion(string documentFilePath, string select Clipboard.SetText(convertedText); } - async Task TryConvertingVBToCSCode(string documentPath, string selectionText) + 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 syntaxTree = await GetSyntaxTree(document, selectionText); - return VisualBasicConverter.ConvertSingle((VisualBasicCompilation)compilation, (VisualBasicSyntaxTree)syntaxTree); - } + var documentSyntaxTree = await document.GetSyntaxTreeAsync(); - private static async Task GetSyntaxTree(Document document, string selectionText) - { - if (string.IsNullOrWhiteSpace(selectionText)) { - return await document.GetSyntaxTreeAsync(); - } - return SyntaxFactory.ParseSyntaxTree(SourceText.From(selectionText)); + 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)); diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index 2d8bc9521..ecbbe0f8b 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -1,7 +1,9 @@ using System; using System.ComponentModel.Design; using System.IO; +using System.Linq; using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Text; using Task = System.Threading.Tasks.Task; namespace CodeConverter.VsExtension @@ -117,24 +119,24 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) async void CodeEditorMenuItemCallback(object sender, EventArgs e) { - string selectedText = codeConversion.GetVBSelectionInCurrentView().StreamSelectionSpan.GetText(); - await ConvertVbDocument(codeConversion.GetCurrentVBViewHost().GetTextDocument().FilePath, 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.GetSingleSelectedItemOrDefault()?.ItemPath; - await ConvertVbDocument(itemPath); + await ConvertVbDocument(itemPath, new Span(0,0)); } - private async Task ConvertVbDocument(string documentPath, string selectionText = "") + private async Task ConvertVbDocument(string documentPath, Span selected) { var fileInfo = new FileInfo(documentPath); if (!CodeConversion.IsVBFileName(fileInfo.Name)) return; try { - await codeConversion.PerformVBToCSConversion(documentPath, selectionText); + await codeConversion.PerformVBToCSConversion(documentPath, selected); } catch (Exception ex) { VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); From 8d70fa4ea9bb045a6192c6944abf89913c4d2dc0 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 11:27:23 +0000 Subject: [PATCH 11/11] Tidy up trailing whitespace --- ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs | 5 ++--- ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs | 2 +- Vsix/ConvertVBToCSCommand.cs | 2 +- Vsix/REConverterPackage.cs | 1 - Vsix/VSPackage.resx | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) 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 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/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index ecbbe0f8b..70ebee5f6 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -95,7 +95,7 @@ void CodeEditorMenuItem_BeforeQueryStatus(object sender, EventArgs e) { var menuItem = sender as OleMenuCommand; if (menuItem != null) { - + menuItem.Visible = !codeConversion.GetVBSelectionInCurrentView()?.StreamSelectionSpan.IsEmpty ?? false; } } diff --git a/Vsix/REConverterPackage.cs b/Vsix/REConverterPackage.cs index 05ff58081..0d4d5db05 100644 --- a/Vsix/REConverterPackage.cs +++ b/Vsix/REConverterPackage.cs @@ -65,7 +65,6 @@ private Assembly LoadWithoutVersionForOurDependencies(object sender, ResolveEven { var requestedAssemblyName = new AssemblyName(args.Name); if (requestedAssemblyName.Version != null && IsThisExtensionRequestingAssembly()) { - return LoadAnyVersionOfAssembly(requestedAssemblyName); } return null; 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.