From dd457799c2a33e16721e79add90a698b78cafde2 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 11:48:03 +0000 Subject: [PATCH 01/29] Use spaces for consistency with rest of project --- Vsix/REConverterPackage.vsct | 166 +++++++++++++++++------------------ 1 file changed, 83 insertions(+), 83 deletions(-) diff --git a/Vsix/REConverterPackage.vsct b/Vsix/REConverterPackage.vsct index c4a3cef4e..f54400c9f 100644 --- a/Vsix/REConverterPackage.vsct +++ b/Vsix/REConverterPackage.vsct @@ -1,92 +1,92 @@  - - + + - - - - - - - - - - - - + + + + + + + + + + + + - - - - - + + + + + - - - - - - + + + + + + - - - + + + - - - - - - - - - - - - - + + + + + + + + + + + + + From ff41161d38671f63e6915477eb2150a34777eda8 Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 12:29:50 +0000 Subject: [PATCH 02/29] WIP define project and solution commands --- Vsix/CodeConversion.cs | 60 ++++++++++++++++++++++++++++----- Vsix/ConvertCSToVBCommand.cs | 14 ++++++++ Vsix/ConvertVBToCSCommand.cs | 32 +++++++++++++++++- Vsix/REConverterPackage.vsct | 42 +++++++++++++++++++++++ Vsix/VisualStudioInteraction.cs | 18 ++++++++++ 5 files changed, 157 insertions(+), 9 deletions(-) diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index bcaca9d7d..27f991a19 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -1,7 +1,10 @@ using System; +using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; +using EnvDTE; using ICSharpCode.CodeConverter; using ICSharpCode.CodeConverter.CSharp; using Microsoft.CodeAnalysis; @@ -12,6 +15,7 @@ using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; +using Project = EnvDTE.Project; using Task = System.Threading.Tasks.Task; namespace CodeConverter.VsExtension @@ -76,20 +80,48 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) return ICSharpCode.CodeConverter.CodeConverter.Convert(codeWithOptions); } + public async Task ConvertVBProjects(IReadOnlyCollection selectedProjects) + { + var errors = new Dictionary(); + var selectedDocuments = selectedProjects.SelectMany(GetVBFilePaths).ToList(); + foreach (var selectedDocument in selectedDocuments) { + try { + var result = await TryConvertingVBToCSCode(selectedDocument, new Span(0,0)); + if (!result.Success) { + errors.Add(selectedDocument, result.GetExceptionsAsString()); + } + + File.WriteAllText(Path.ChangeExtension(selectedDocument, ".cs"), result.ConvertedCode); + } catch (Exception ex) { + errors.Add(selectedDocument, ex.ToString()); + return; + } + } + + if (errors.Any()) { + var successes = errors.Count - selectedDocuments.Count; + var intro = successes > 0 + ? $"{successes}/{errors.Count} files converted" + : "Conversion failed"; + ShowNonFatalError(intro + string.Join(Environment.NewLine + Environment.NewLine, + errors.Select(fileAndError => + $"In {fileAndError.Key}:{Environment.NewLine}{fileAndError.Value}"))); + } + } + + private static IEnumerable GetVBFilePaths(Project selectedProject) + { + return selectedProject.ProjectItems.OfType().Select(f => f.Document.FullName) + .Where(fn => fn.ToLowerInvariant().EndsWith(".vb")); + } + public async Task PerformVBToCSConversion(string documentFilePath, Span selected) { string convertedText = null; try { var result = await TryConvertingVBToCSCode(documentFilePath, selected); if (!result.Success) { - var newLines = Environment.NewLine + Environment.NewLine; - VsShellUtilities.ShowMessageBox( - serviceProvider, - $"Selected VB code seems to have errors or to be incomplete:{newLines}{result.GetExceptionsAsString()}", - VBToCSConversionTitle, - OLEMSGICON.OLEMSGICON_WARNING, - OLEMSGBUTTON.OLEMSGBUTTON_OK, - OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); + ShowNonFatalError(result.GetExceptionsAsString()); return; } @@ -114,6 +146,18 @@ public async Task PerformVBToCSConversion(string documentFilePath, Span selected Clipboard.SetText(convertedText); } + private void ShowNonFatalError(string error) + { + var newLines = Environment.NewLine + Environment.NewLine; + VsShellUtilities.ShowMessageBox( + serviceProvider, + $"Selected VB code seems to have errors or to be incomplete:{newLines}{error}", + VBToCSConversionTitle, + OLEMSGICON.OLEMSGICON_WARNING, + OLEMSGBUTTON.OLEMSGBUTTON_OK, + OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); + } + async Task TryConvertingVBToCSCode(string documentPath, Span selected) { //TODO Figure out when there are multiple document ids for a single file path diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index 021a2d3ba..80b2e7165 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -13,6 +13,8 @@ internal sealed class ConvertCSToVBCommand public const int MainMenuCommandId = 0x0100; public const int CtxMenuCommandId = 0x0101; public const int ProjectItemCtxMenuCommandId = 0x0102; + public const int ProjectCtxMenuCommandId = 0x0103; + public const int SolutionCtxMenuCommandId = 0x0104; /// /// Command menu group (command set GUID). @@ -81,6 +83,18 @@ public static void Initialize(REConverterPackage package) var projectItemCtxMenuItem = new OleMenuCommand(ProjectItemMenuItemCallback, projectItemCtxMenuCommandID); projectItemCtxMenuItem.BeforeQueryStatus += ProjectItemMenuItem_BeforeQueryStatus; commandService.AddCommand(projectItemCtxMenuItem); + + // Command in project context menu + var projectCtxMenuCommandID = new CommandID(CommandSet, ProjectCtxMenuCommandId); + var projectCtxMenuItem = new OleMenuCommand(ProjectMenuItemCallback, projectCtxMenuCommandID); + projectCtxMenuItem.BeforeQueryStatus += ProjectMenuItem_BeforeQueryStatus; + commandService.AddCommand(projectCtxMenuItem); + + // Command in solution context menu + var solutionCtxMenuCommandID = new CommandID(CommandSet, SolutionCtxMenuCommandId); + var solutionCtxMenuItem = new OleMenuCommand(SolutionMenuItemCallback, solutionCtxMenuCommandID); + solutionCtxMenuItem.BeforeQueryStatus += SolutionMenuItem_BeforeQueryStatus; + commandService.AddCommand(solutionCtxMenuItem); } } diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index 70ebee5f6..e75036dbf 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -16,6 +16,8 @@ internal sealed class ConvertVBToCSCommand public const int MainMenuCommandId = 0x0200; public const int CtxMenuCommandId = 0x0201; public const int ProjectItemCtxMenuCommandId = 0x0202; + public const int ProjectCtxMenuCommandId = 0x0203; + public const int SolutionCtxMenuCommandId = 0x0204; /// /// Command menu group (command set GUID). @@ -88,6 +90,18 @@ public static void Initialize(REConverterPackage package) var projectItemCtxMenuItem = new OleMenuCommand(ProjectItemMenuItemCallback, projectItemCtxMenuCommandID); projectItemCtxMenuItem.BeforeQueryStatus += ProjectItemMenuItem_BeforeQueryStatus; commandService.AddCommand(projectItemCtxMenuItem); + + // Command in project context menu + var projectCtxMenuCommandID = new CommandID(CommandSet, ProjectCtxMenuCommandId); + var projectCtxMenuItem = new OleMenuCommand(SolutionOrProjectMenuItemCallback, projectCtxMenuCommandID); + projectCtxMenuItem.BeforeQueryStatus += SolutionOrProjectMenuItem_BeforeQueryStatus; + commandService.AddCommand(projectCtxMenuItem); + + // Command in solution context menu + var solutionCtxMenuCommandID = new CommandID(CommandSet, SolutionCtxMenuCommandId); + var solutionCtxMenuItem = new OleMenuCommand(SolutionOrProjectMenuItemCallback, solutionCtxMenuCommandID); + solutionCtxMenuItem.BeforeQueryStatus += SolutionOrProjectMenuItem_BeforeQueryStatus; + commandService.AddCommand(solutionCtxMenuItem); } } @@ -116,19 +130,35 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) menuItem.Enabled = true; } } + private void SolutionOrProjectMenuItem_BeforeQueryStatus(object sender, EventArgs e) + { + var menuItem = sender as OleMenuCommand; + if (menuItem != null) { + menuItem.Visible = menuItem.Enabled = VisualStudioInteraction.GetSelectedProjects(".vbproj").Any(); + } + } async void CodeEditorMenuItemCallback(object sender, EventArgs e) { 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, new Span(0,0)); } + private async void SolutionOrProjectMenuItemCallback(object sender, EventArgs e) + { + try { + await codeConversion.ConvertVBProjects(VisualStudioInteraction.GetSelectedProjects(".vbproj")); + } catch (Exception ex) { + VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); + } + } + private async Task ConvertVbDocument(string documentPath, Span selected) { var fileInfo = new FileInfo(documentPath); diff --git a/Vsix/REConverterPackage.vsct b/Vsix/REConverterPackage.vsct index f54400c9f..e531abbb9 100644 --- a/Vsix/REConverterPackage.vsct +++ b/Vsix/REConverterPackage.vsct @@ -15,6 +15,12 @@ + + + + + + @@ -43,6 +49,22 @@ Convert to VB and copy to clipboard + + + + @@ -84,9 +122,13 @@ + + + + diff --git a/Vsix/VisualStudioInteraction.cs b/Vsix/VisualStudioInteraction.cs index ba9acef97..e78c214ec 100644 --- a/Vsix/VisualStudioInteraction.cs +++ b/Vsix/VisualStudioInteraction.cs @@ -1,5 +1,9 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Runtime.InteropServices; +using EnvDTE; +using EnvDTE80; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices; @@ -55,6 +59,20 @@ public static VsDocument GetSingleSelectedItemOrDefault() } } } + private static IEnumerable GetSelectedSolutionExplorerItems() where T: class + { + var selectedItems = (IEnumerable) Dte.ToolWindows.SolutionExplorer.SelectedItems; + return selectedItems.OfType().Select(i => i.Object).OfType(); + } + + private static DTE2 Dte => Package.GetGlobalService(typeof(DTE2)) as DTE2; + + + public static List GetSelectedProjects(string projectExtension) + { + var items = GetSelectedSolutionExplorerItems().Where(project => project.FullName.EndsWith(projectExtension, StringComparison.InvariantCultureIgnoreCase)).ToList(); + return items; + } public static IWpfTextViewHost GetCurrentViewHost(IServiceProvider serviceProvider) { From b831dffe19c15daff33e9602f0414ce89d43477d Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 19:41:54 +0000 Subject: [PATCH 03/29] Use specific method for this --- ICSharpCode.CodeConverter/CSharp/CompilationErrorFixer.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ICSharpCode.CodeConverter/CSharp/CompilationErrorFixer.cs b/ICSharpCode.CodeConverter/CSharp/CompilationErrorFixer.cs index ba8c72158..363a75af5 100644 --- a/ICSharpCode.CodeConverter/CSharp/CompilationErrorFixer.cs +++ b/ICSharpCode.CodeConverter/CSharp/CompilationErrorFixer.cs @@ -39,10 +39,7 @@ private SyntaxNode ComputeReplacementNode(SyntaxNode originalNode, SyntaxNode po var refOrOutKeyword = GetRefKeyword(methodSymbol.Parameters[index]); var currentSyntaxKind = nodeToReturn.Arguments[index].Kind(); if (!refOrOutKeyword.IsKind(currentSyntaxKind)) { - nodeToReturn = nodeToReturn.ReplaceNode(argument, - SyntaxFactory.Argument(argument.NameColon, refOrOutKeyword, argument.Expression) - .WithLeadingTrivia(argument.GetLeadingTrivia()) - .WithTrailingTrivia(argument.GetTrailingTrivia())); + nodeToReturn = nodeToReturn.ReplaceNode(argument, argument.WithRefOrOutKeyword(refOrOutKeyword)); } } } From aee94ba1367134bca7257cfdf4fa61fff0e77d2a Mon Sep 17 00:00:00 2001 From: GrahamTheCoder Date: Sun, 18 Feb 2018 19:54:08 +0000 Subject: [PATCH 04/29] WIP VB -> C# Solution command works --- .../CSharp/VisualBasicConverter.cs | 16 ++++ Vsix/CodeConversion.cs | 61 ++++++++-------- Vsix/ConvertCSToVBCommand.cs | 26 ++++++- Vsix/ConvertVBToCSCommand.cs | 1 + Vsix/REConverterPackage.vsct | 6 +- Vsix/VisualStudioInteraction.cs | 73 +++++++++++++++++-- 6 files changed, 141 insertions(+), 42 deletions(-) diff --git a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs index 06b964a5b..863bd5ea8 100644 --- a/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs +++ b/ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading.Tasks; using ICSharpCode.CodeConverter.Util; @@ -64,6 +65,21 @@ private static SyntaxTree GetSyntaxTreeWithAnnotatedSelection(TextSpan selected, return syntaxTree; } + public static async Task ConvertProjects(IEnumerable projects) + { + foreach (var project in projects) { + var compilation = await project.GetCompilationAsync(); + var syntaxTrees = project.Documents + .Where(d => Path.GetExtension(d.FilePath).Equals(".vb", StringComparison.OrdinalIgnoreCase)) + .Select(d => d.GetSyntaxTreeAsync().GetAwaiter().GetResult()) + .OfType(); + foreach (var pathNodePair in ConvertMultiple((VBasic.VisualBasicCompilation)compilation, syntaxTrees)) { + var formattedNode = Formatter.Format(pathNodePair.Value, new AdhocWorkspace()); + var path = Path.ChangeExtension(pathNodePair.Key, ".cs"); + File.WriteAllText(path, formattedNode.ToFullString()); + } + } + } public static Dictionary ConvertMultiple(VBasic.VisualBasicCompilation compilation, IEnumerable syntaxTrees) { diff --git a/Vsix/CodeConversion.cs b/Vsix/CodeConversion.cs index 27f991a19..1fd907fd4 100644 --- a/Vsix/CodeConversion.cs +++ b/Vsix/CodeConversion.cs @@ -82,37 +82,36 @@ ConversionResult TryConvertingCSToVBCode(string inputCode) public async Task ConvertVBProjects(IReadOnlyCollection selectedProjects) { - var errors = new Dictionary(); - var selectedDocuments = selectedProjects.SelectMany(GetVBFilePaths).ToList(); - foreach (var selectedDocument in selectedDocuments) { - try { - var result = await TryConvertingVBToCSCode(selectedDocument, new Span(0,0)); - if (!result.Success) { - errors.Add(selectedDocument, result.GetExceptionsAsString()); - } - - File.WriteAllText(Path.ChangeExtension(selectedDocument, ".cs"), result.ConvertedCode); - } catch (Exception ex) { - errors.Add(selectedDocument, ex.ToString()); - return; - } - } - - if (errors.Any()) { - var successes = errors.Count - selectedDocuments.Count; - var intro = successes > 0 - ? $"{successes}/{errors.Count} files converted" - : "Conversion failed"; - ShowNonFatalError(intro + string.Join(Environment.NewLine + Environment.NewLine, - errors.Select(fileAndError => - $"In {fileAndError.Key}:{Environment.NewLine}{fileAndError.Value}"))); - } - } - - private static IEnumerable GetVBFilePaths(Project selectedProject) - { - return selectedProject.ProjectItems.OfType().Select(f => f.Document.FullName) - .Where(fn => fn.ToLowerInvariant().EndsWith(".vb")); + var projectsByPath = visualStudioWorkspace.CurrentSolution.Projects.ToDictionary(p => p.FilePath, p => p); + var projects = selectedProjects.Select(p => projectsByPath[p.FullName]); + await VisualBasicConverter.ConvertProjects(projects); + + + //var errors = new Dictionary(); + //var selectedDocuments = selectedProjects.SelectMany(GetVBFilePaths).ToList(); + //foreach (var selectedDocument in selectedDocuments) { + // try { + // var result = await TryConvertingVBToCSCode(selectedDocument, new TextSpan(0,0)); + // if (!result.Success) { + // errors.Add(selectedDocument, result.GetExceptionsAsString()); + // } + + // File.WriteAllText(Path.ChangeExtension(selectedDocument, ".cs"), result.ConvertedCode); + // } catch (Exception ex) { + // errors.Add(selectedDocument, ex.ToString()); + // return; + // } + //} + + //if (errors.Any()) { + // var successes = errors.Count - selectedDocuments.Count; + // var intro = successes > 0 + // ? $"{successes}/{errors.Count} files converted" + // : "Conversion failed"; + // ShowNonFatalError(intro + string.Join(Environment.NewLine + Environment.NewLine, + // errors.Select(fileAndError => + // $"In {fileAndError.Key}:{Environment.NewLine}{fileAndError.Value}"))); + //} } public async Task PerformVBToCSConversion(string documentFilePath, Span selected) diff --git a/Vsix/ConvertCSToVBCommand.cs b/Vsix/ConvertCSToVBCommand.cs index 80b2e7165..c2557e8bf 100644 --- a/Vsix/ConvertCSToVBCommand.cs +++ b/Vsix/ConvertCSToVBCommand.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel.Design; using System.IO; +using System.Linq; using Microsoft.VisualStudio.Shell; namespace CodeConverter.VsExtension @@ -86,14 +87,14 @@ public static void Initialize(REConverterPackage package) // Command in project context menu var projectCtxMenuCommandID = new CommandID(CommandSet, ProjectCtxMenuCommandId); - var projectCtxMenuItem = new OleMenuCommand(ProjectMenuItemCallback, projectCtxMenuCommandID); - projectCtxMenuItem.BeforeQueryStatus += ProjectMenuItem_BeforeQueryStatus; + var projectCtxMenuItem = new OleMenuCommand(SolutionOrProjectMenuItemCallback, projectCtxMenuCommandID); + projectCtxMenuItem.BeforeQueryStatus += SolutionOrProjectMenuItem_BeforeQueryStatus; commandService.AddCommand(projectCtxMenuItem); // Command in solution context menu var solutionCtxMenuCommandID = new CommandID(CommandSet, SolutionCtxMenuCommandId); - var solutionCtxMenuItem = new OleMenuCommand(SolutionMenuItemCallback, solutionCtxMenuCommandID); - solutionCtxMenuItem.BeforeQueryStatus += SolutionMenuItem_BeforeQueryStatus; + var solutionCtxMenuItem = new OleMenuCommand(SolutionOrProjectMenuItemCallback, solutionCtxMenuCommandID); + solutionCtxMenuItem.BeforeQueryStatus += SolutionOrProjectMenuItem_BeforeQueryStatus; commandService.AddCommand(solutionCtxMenuItem); } } @@ -124,6 +125,14 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) } } + private void SolutionOrProjectMenuItem_BeforeQueryStatus(object sender, EventArgs e) + { + var menuItem = sender as OleMenuCommand; + if (menuItem != null) { + menuItem.Visible = menuItem.Enabled = VisualStudioInteraction.GetSelectedProjects(".csproj").Any(); + } + } + void CodeEditorMenuItemCallback(object sender, EventArgs e) { string selectedText = codeConversion.GetCSSelectionInCurrentView()?.StreamSelectionSpan.GetText(); @@ -146,5 +155,14 @@ async void ProjectItemMenuItemCallback(object sender, EventArgs e) VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.CSToVBConversionTitle, ex); } } + + private async void SolutionOrProjectMenuItemCallback(object sender, EventArgs e) + { + try { + await codeConversion.ConvertVBProjects(VisualStudioInteraction.GetSelectedProjects(".csproj")); + } catch (Exception ex) { + VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.VBToCSConversionTitle, ex); + } + } } } diff --git a/Vsix/ConvertVBToCSCommand.cs b/Vsix/ConvertVBToCSCommand.cs index e75036dbf..4167c6c63 100644 --- a/Vsix/ConvertVBToCSCommand.cs +++ b/Vsix/ConvertVBToCSCommand.cs @@ -130,6 +130,7 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e) menuItem.Enabled = true; } } + private void SolutionOrProjectMenuItem_BeforeQueryStatus(object sender, EventArgs e) { var menuItem = sender as OleMenuCommand; diff --git a/Vsix/REConverterPackage.vsct b/Vsix/REConverterPackage.vsct index e531abbb9..3623c20d8 100644 --- a/Vsix/REConverterPackage.vsct +++ b/Vsix/REConverterPackage.vsct @@ -99,8 +99,8 @@ Convert to C# and write to adjacent files -