Example #1
0
        private async Task <string> GetConversionSummaryAsync(IReadOnlyCollection <string> files, IReadOnlyCollection <string> errors)
        {
            var oneLine        = "Code conversion failed";
            var successSummary = "";

            if (files.Any())
            {
                oneLine        = "Code conversion completed";
                successSummary = $"{files.Count} files have been written to disk.";
            }

            if (errors.Any())
            {
                oneLine += $" with {errors.Count} error" + (errors.Count == 1 ? "" : "s");
            }

            if (files.Count > errors.Count * 2)
            {
                successSummary += Environment.NewLine + "Please report issues at https://github.com/icsharpcode/CodeConverter/issues and consider rating at https://marketplace.visualstudio.com/items?itemName=SharpDevelopTeam.CodeConverter#review-details";
            }
            else
            {
                successSummary += Environment.NewLine + "Please report issues at https://github.com/icsharpcode/CodeConverter/issues";
            }

            await VisualStudioInteraction.WriteStatusBarTextAsync(_serviceProvider, oneLine + " - see output window");

            return(Environment.NewLine + Environment.NewLine
                   + oneLine
                   + Environment.NewLine + successSummary
                   + Environment.NewLine);
        }
        private async Task ProjectItemMenuItemCallbackAsync(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            string itemPath = (await VisualStudioInteraction.GetSingleSelectedItemOrDefaultAsync())?.ItemPath;

            await ConvertDocumentAsync(itemPath, new Span(0, 0));
        }
        private async Task CodeEditorMenuItemCallbackAsync(CancellationToken cancellationToken)
        {
            var(filePath, selection) = await VisualStudioInteraction.GetCurrentFilenameAndSelectionAsync(ServiceProvider, CodeConversion.IsVBFileName, false);

            if (filePath != null && selection != null)
            {
                await ConvertDocumentAsync(filePath, selection.Value, cancellationToken);
            }
        }
        private async Task CodeEditorMenuItem_BeforeQueryStatusAsync(object sender, EventArgs e)
        {
            if (sender is OleMenuCommand menuItem)
            {
                var selectionInCurrentViewAsync = await VisualStudioInteraction.GetFirstSelectedSpanInCurrentViewAsync(ServiceProvider, CodeConversion.IsCSFileName, true);

                menuItem.Visible = selectionInCurrentViewAsync != null;
            }
        }
        private async Task CodeEditorMenuItemCallbackAsync(object sender, EventArgs e)
        {
            var(filePath, selection) = await VisualStudioInteraction.GetCurrentFilenameAndSelectionAsync(ServiceProvider, CodeConversion.IsCSFileName, false);

            if (filePath != null && selection != null)
            {
                await ConvertDocumentAsync(filePath, selection.Value);
            }
        }
Example #6
0
        private void SolutionOrProjectMenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var menuItem = sender as OleMenuCommand;

            if (menuItem != null)
            {
                menuItem.Visible = menuItem.Enabled = VisualStudioInteraction.GetSelectedProjects(ProjectExtension).Any();
            }
        }
Example #7
0
 private async void SolutionOrProjectMenuItemCallback(object sender, EventArgs e)
 {
     try {
         var projects = VisualStudioInteraction.GetSelectedProjects(ProjectExtension);
         await _codeConversion.PerformProjectConversion <VBToCSConversion>(projects);
     } catch (Exception ex) {
         VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.ConverterTitle, ex);
     }
 }
        private async Task SolutionOrProjectMenuItem_BeforeQueryStatusAsync(object sender, EventArgs e)
        {
            if (sender is OleMenuCommand menuItem)
            {
                var selectedProjectsAsync = await VisualStudioInteraction.GetSelectedProjectsAsync(ProjectExtension);

                menuItem.Visible = menuItem.Enabled = selectedProjectsAsync.Any();
            }
        }
 private async Task SolutionOrProjectMenuItemCallbackAsync(CancellationToken cancellationToken)
 {
     try {
         var projects = VisualStudioInteraction.GetSelectedProjectsAsync(ProjectExtension);
         await _codeConversion.ConvertProjectsAsync <VBToCSConversion>(await projects, cancellationToken);
     } catch (Exception ex) {
         await VisualStudioInteraction.ShowExceptionAsync(ServiceProvider, CodeConversion.ConverterTitle, ex);
     }
 }
 private async Task SolutionOrProjectMenuItemCallbackAsync(object sender, EventArgs e)
 {
     try {
         var projects = VisualStudioInteraction.GetSelectedProjectsAsync(ProjectExtension);
         await _codeConversion.PerformProjectConversionAsync <CSToVBConversion>(await projects);
     } catch (Exception ex) {
         await VisualStudioInteraction.ShowExceptionAsync(ServiceProvider, CodeConversion.ConverterTitle, ex);
     }
 }
Example #11
0
        private bool UserHasConfirmedOverwrite(List <string> files, List <string> errors, string pathsToOverwrite)
        {
            return(VisualStudioInteraction.ShowMessageBox(_serviceProvider,
                                                          "Overwrite solution and referencing projects?",
                                                          $@"The current solution file and any referencing projects will be overwritten to reference the new project(s):
* {pathsToOverwrite}

The old contents will be copied to 'currentFilename.bak'.
Please 'Reload All' when Visual Studio prompts you.", true, files.Count > errors.Count));
        }
Example #12
0
        private Task <bool> UserHasConfirmedOverwriteAsync(List <string> files, List <string> errors, IReadOnlyCollection <string> pathsToOverwrite)
        {
            var maxExamples = 30; // Avoid a huge unreadable dialog going off the screen
            var exampleText = pathsToOverwrite.Count > maxExamples ? $". First {maxExamples} examples" : "";

            return(VisualStudioInteraction.ShowMessageBoxAsync(_serviceProvider,
                                                               "Overwrite solution and referencing projects?",
                                                               $@"The current solution file and any referencing projects will be overwritten to reference the new project(s){exampleText}:
* {string.Join(Environment.NewLine + "* ", pathsToOverwrite.Take(maxExamples))}

The old contents will be copied to 'currentFilename.bak'.
Please 'Reload All' when Visual Studio prompts you.", true, files.Count > errors.Count));
        }
        private async Task ConvertDocumentAsync(string documentPath, Span selected, CancellationToken cancellationToken)
        {
            if (documentPath == null || !CodeConversion.IsVBFileName(documentPath))
            {
                return;
            }

            try {
                await _codeConversion.ConvertDocumentAsync <VBToCSConversion>(documentPath, selected, cancellationToken);
            } catch (Exception ex) {
                await VisualStudioInteraction.ShowExceptionAsync(ServiceProvider, CodeConversion.ConverterTitle, ex);
            }
        }
        private async Task ConvertDocumentAsync(string documentPath, Span selected)
        {
            if (documentPath == null || !CodeConversion.IsCSFileName(documentPath))
            {
                return;
            }

            try {
                await _codeConversion.PerformDocumentConversionAsync <CSToVBConversion>(documentPath, selected);
            } catch (Exception ex) {
                await VisualStudioInteraction.ShowExceptionAsync(ServiceProvider, CodeConversion.ConverterTitle, ex);
            }
        }
Example #15
0
        public async Task PerformDocumentConversion <TLanguageConversion>(string documentFilePath, Span selected) where TLanguageConversion : ILanguageConversion, new()
        {
            var conversionResult = await Task.Run(async() => {
                var result = await ConvertDocumentUnhandled <TLanguageConversion>(documentFilePath, selected);
                WriteConvertedFilesAndShowSummary(new[] { result });
                return(result);
            });

            if (GetOptions().CopyResultToClipboardForSingleDocument)
            {
                Clipboard.SetText(conversionResult.ConvertedCode ?? conversionResult.GetExceptionsAsString());
                _outputWindow.WriteToOutputWindow("Conversion result copied to clipboard.");
                VisualStudioInteraction.ShowMessageBox(_serviceProvider, "Conversion result copied to clipboard.", conversionResult.GetExceptionsAsString(), false);
            }
        }
Example #16
0
        public async Task PerformDocumentConversionAsync <TLanguageConversion>(string documentFilePath, Span selected) where TLanguageConversion : ILanguageConversion, new()
        {
            var conversionResult = await _joinableTaskFactory.RunAsync(async() => {
                var result = await ConvertDocumentUnhandledAsync <TLanguageConversion>(documentFilePath, selected);
                await WriteConvertedFilesAndShowSummaryAsync(new[] { result });
                return(result);
            });

            if ((await GetOptions()).CopyResultToClipboardForSingleDocument)
            {
                Clipboard.SetText(conversionResult.ConvertedCode ?? conversionResult.GetExceptionsAsString());
                await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + "Conversion result copied to clipboard.");

                await VisualStudioInteraction.ShowMessageBoxAsync(_serviceProvider, "Conversion result copied to clipboard.", conversionResult.GetExceptionsAsString(), false);
            }
        }
Example #17
0
        private async Task ProjectItemMenuItem_BeforeQueryStatusAsync(object sender, EventArgs e)
        {
            if (sender is OleMenuCommand menuItem)
            {
                menuItem.Visible = false;
                menuItem.Enabled = false;

                string itemPath = (await VisualStudioInteraction.GetSingleSelectedItemOrDefaultAsync())?.ItemPath;
                if (itemPath == null || !CodeConversion.IsCSFileName(itemPath))
                {
                    return;
                }

                menuItem.Visible = true;
                menuItem.Enabled = true;
            }
        }
        /// <summary>
        /// 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.
        /// </summary>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            var oleMenuCommandService = await this.GetServiceAsync <IMenuCommandService, OleMenuCommandService>();

            var componentModel = await this.GetServiceAsync <SComponentModel, IComponentModel>();

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var visualStudioWorkspace = componentModel.GetService <VisualStudioWorkspace>();
            var codeConversion        = await CodeConversion.CreateAsync(this, visualStudioWorkspace, this.GetDialogPageAsync <ConverterOptionsPage>);

            ConvertCSToVBCommand.Initialize(this, oleMenuCommandService, codeConversion);
            ConvertVBToCSCommand.Initialize(this, oleMenuCommandService, codeConversion);
            VisualStudioInteraction.Initialize(PackageCancellation);
            await TaskScheduler.Default;
            await base.InitializeAsync(cancellationToken, progress);
        }
Example #19
0
        public IWpfTextViewHost GetCurrentViewHost(Func <string, bool> predicate)
        {
            IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(_serviceProvider);

            if (viewHost == null)
            {
                return(null);
            }

            ITextDocument textDocument = viewHost.GetTextDocument();

            if (textDocument == null || !predicate(textDocument.FilePath))
            {
                return(null);
            }

            return(viewHost);
        }
Example #20
0
        private void WriteConvertedFilesAndShowSummary(IEnumerable <ConversionResult> convertedFiles)
        {
            var    files             = new List <string>();
            var    errors            = new List <string>();
            string longestFilePath   = null;
            var    longestFileLength = -1;

            var solutionDir = Path.GetDirectoryName(_visualStudioWorkspace.CurrentSolution.FilePath);

            VisualStudioInteraction.OutputWindow.WriteToOutputWindow(Intro);
            VisualStudioInteraction.OutputWindow.ForceShowOutputPane();

            foreach (var convertedFile in convertedFiles)
            {
                var sourcePath = convertedFile.SourcePathOrNull ?? "";
                var sourcePathRelativeToSolutionDir = PathRelativeToSolutionDir(solutionDir, sourcePath);
                if (sourcePath != "")
                {
                    if (!string.IsNullOrWhiteSpace(convertedFile.ConvertedCode))
                    {
                        var path = ToggleExtension(sourcePath);
                        if (convertedFile.ConvertedCode.Length > longestFileLength)
                        {
                            longestFileLength = convertedFile.ConvertedCode.Length;
                            longestFilePath   = path;
                        }

                        files.Add(path);
                        File.WriteAllText(path, convertedFile.ConvertedCode);
                    }

                    LogProgress(convertedFile, errors, sourcePathRelativeToSolutionDir);
                }
            }

            VisualStudioInteraction.OutputWindow.WriteToOutputWindow(GetConversionSummary(files, errors));
            VisualStudioInteraction.OutputWindow.ForceShowOutputPane();

            if (longestFilePath != null)
            {
                VisualStudioInteraction.OpenFile(new FileInfo(longestFilePath)).SelectAll();
            }
        }
Example #21
0
        void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var menuItem = sender as OleMenuCommand;

            if (menuItem != null)
            {
                menuItem.Visible = false;
                menuItem.Enabled = false;

                string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath;
                if (itemPath == null || !CodeConversion.IsVBFileName(itemPath))
                {
                    return;
                }

                menuItem.Visible = true;
                menuItem.Enabled = true;
            }
        }
Example #22
0
        private void WriteConvertedFilesAndShowSummary(IEnumerable <ConversionResult> convertedFiles)
        {
            var    files             = new List <string>();
            var    errors            = new List <string>();
            string longestFilePath   = null;
            var    longestFileLength = -1;

            var solutionDir = Path.GetDirectoryName(_visualStudioWorkspace.CurrentSolution.FilePath);

            VisualStudioInteraction.OutputWindow.WriteToOutputWindow(Intro);
            VisualStudioInteraction.OutputWindow.ForceShowOutputPane();

            foreach (var convertedFile in convertedFiles)
            {
                var sourcePath = convertedFile.SourcePathOrNull;
                if (convertedFile.Success && sourcePath != null)
                {
                    var path = ToggleExtension(sourcePath);
                    if (convertedFile.ConvertedCode.Length > longestFileLength)
                    {
                        longestFileLength = convertedFile.ConvertedCode.Length;
                        longestFilePath   = path;
                    }

                    files.Add(path);
                    File.WriteAllText(path, convertedFile.ConvertedCode);
                    LogCompleted(solutionDir, path);
                }
                else
                {
                    errors.Add(convertedFile.GetExceptionsAsString());
                    LogError(solutionDir, convertedFile);
                }
            }

            VisualStudioInteraction.OutputWindow.WriteToOutputWindow(GetConversionSummary(files, errors));
            VisualStudioInteraction.OutputWindow.ForceShowOutputPane();

            if (longestFilePath != null)
            {
                VisualStudioInteraction.OpenFile(new FileInfo(longestFilePath)).SelectAll();
            }
        }
        private async Task FinalizeConversionAsync(List <string> files, List <string> errors, string longestFilePath, List <ConversionResult> filesToOverwrite)
        {
            var options = await GetOptions();

            var pathsToOverwrite = filesToOverwrite.Select(f => PathRelativeToSolutionDir(f.SourcePathOrNull));
            var shouldOverwriteSolutionAndProjectFiles =
                filesToOverwrite.Any() &&
                (options.AlwaysOverwriteFiles || await UserHasConfirmedOverwriteAsync(files, errors, pathsToOverwrite.ToList()));

            if (shouldOverwriteSolutionAndProjectFiles)
            {
                var titleMessage = options.CreateBackups ? "Creating backups and overwriting files:" : "Overwriting files:" + "";
                await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + titleMessage);

                foreach (var fileToOverwrite in filesToOverwrite)
                {
                    if (options.CreateBackups)
                    {
                        File.Copy(fileToOverwrite.SourcePathOrNull, fileToOverwrite.SourcePathOrNull + ".bak", true);
                    }
                    fileToOverwrite.WriteToFile();

                    var targetPathRelativeToSolutionDir = PathRelativeToSolutionDir(fileToOverwrite.TargetPathOrNull);
                    await _outputWindow.WriteToOutputWindowAsync($"* {targetPathRelativeToSolutionDir}");
                }
                files = files.Concat(filesToOverwrite.Select(f => f.SourcePathOrNull)).ToList();
            }
            else if (longestFilePath != null)
            {
                await(await VisualStudioInteraction.OpenFileAsync(new FileInfo(longestFilePath))).SelectAllAsync();
            }

            var conversionSummary = await GetConversionSummaryAsync(files, errors);

            await _outputWindow.WriteToOutputWindowAsync(conversionSummary);

            await _outputWindow.ForceShowOutputPaneAsync();
        }
Example #24
0
        public async Task ConvertDocumentAsync <TLanguageConversion>(string documentFilePath, Span selected, CancellationToken cancellationToken) where TLanguageConversion : ILanguageConversion, new()
        {
            try {
                var conversionResult = await _joinableTaskFactory.RunAsync(async() => {
                    var result = await ConvertDocumentUnhandledAsync <TLanguageConversion>(documentFilePath, selected, cancellationToken);
                    await WriteConvertedFilesAndShowSummaryAsync(new[] { result }.ToAsyncEnumerable());
                    return(result);
                });

                if ((await GetOptions()).CopyResultToClipboardForSingleDocument)
                {
                    await SetClipboardTextOnUiThreadAsync(conversionResult.ConvertedCode ?? conversionResult.GetExceptionsAsString());

                    await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + "Conversion result copied to clipboard.");

                    await VisualStudioInteraction.ShowMessageBoxAsync(_serviceProvider, "Conversion result copied to clipboard.", $"Conversion result copied to clipboard. {conversionResult.GetExceptionsAsString()}", false);
                }
            } catch (OperationCanceledException) {
                if (!_packageCancellation.CancelAll.IsCancellationRequested)
                {
                    await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + "Previous conversion cancelled", forceShow : true);
                }
            }
        }
Example #25
0
        private void FinalizeConversion(List <string> files, List <string> errors, string longestFilePath, List <ConversionResult> filesToOverwrite)
        {
            var options           = GetOptions();
            var conversionSummary = GetConversionSummary(files, errors);

            _outputWindow.WriteToOutputWindow(conversionSummary);
            _outputWindow.ForceShowOutputPane();

            if (longestFilePath != null)
            {
                VisualStudioInteraction.OpenFile(new FileInfo(longestFilePath)).SelectAll();
            }

            var pathsToOverwrite = string.Join(Environment.NewLine + "* ",
                                               filesToOverwrite.Select(f => PathRelativeToSolutionDir(f.SourcePathOrNull)));
            var shouldOverwriteSolutionAndProjectFiles =
                filesToOverwrite.Any() &&
                (options.AlwaysOverwriteFiles || UserHasConfirmedOverwrite(files, errors, pathsToOverwrite));

            if (shouldOverwriteSolutionAndProjectFiles)
            {
                var titleMessage = options.CreateBackups ? "Creating backups and overwriting files:" : "Overwriting files:" + "";
                _outputWindow.WriteToOutputWindow(titleMessage);
                foreach (var fileToOverwrite in filesToOverwrite)
                {
                    if (options.CreateBackups)
                    {
                        File.Copy(fileToOverwrite.SourcePathOrNull, fileToOverwrite.SourcePathOrNull + ".bak", true);
                    }
                    File.WriteAllText(fileToOverwrite.TargetPathOrNull, fileToOverwrite.ConvertedCode);

                    var targetPathRelativeToSolutionDir = PathRelativeToSolutionDir(fileToOverwrite.TargetPathOrNull);
                    _outputWindow.WriteToOutputWindow(Environment.NewLine + $"* {targetPathRelativeToSolutionDir}");
                }
            }
        }
        private async Task ProjectItemMenuItemCallbackAsync(CancellationToken cancellationToken)
        {
            string itemPath = await VisualStudioInteraction.GetSingleSelectedItemPathOrDefaultAsync();

            await ConvertDocumentAsync(itemPath, new Span(0, 0), cancellationToken);
        }
Example #27
0
        async void ProjectItemMenuItemCallback(object sender, EventArgs e)
        {
            string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath;

            await ConvertDocument(itemPath, new Span(0, 0));
        }
        private async Task ProjectItemMenuItemCallbackAsync(object sender, EventArgs e)
        {
            string itemPath = await VisualStudioInteraction.GetSingleSelectedItemPathOrDefaultAsync();

            await ConvertDocumentAsync(itemPath, new Span(0, 0));
        }