Esempio n. 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);
        }
        public async Task ConvertDocumentAsync <TLanguageConversion>(string documentFilePath, Span selected, CancellationToken cancellationToken) where TLanguageConversion : ILanguageConversion, new()
        {
            try {
                await EnsureBuiltAsync();

                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);
                }
            }
        }
Esempio n. 3
0
 private async Task CodeEditorMenuItemCallbackAsync(CancellationToken cancellationToken)
 {
     try {
         await _codeConversion.PasteAsAsync <VBToCSConversion>(cancellationToken);
     } catch (Exception ex) {
         await VisualStudioInteraction.ShowExceptionAsync(ex);
     }
 }
        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 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 CodeEditorMenuItemCallbackAsync(CancellationToken cancellationToken)
        {
            var(filePath, selection) = await VisualStudioInteraction.GetCurrentFilenameAndSelectionAsync(ServiceProvider, CodeConversion.IsCSFileName, false);

            if (filePath != null && selection != null)
            {
                await ConvertDocumentAsync(filePath, selection.Value, cancellationToken);
            }
        }
Esempio n. 7
0
        private async Task ProjectItemMenuItem_BeforeQueryStatusAsync(object sender, EventArgs e)
        {
            if (sender is OleMenuCommand menuItem)
            {
                var itemsPath = await VisualStudioInteraction.GetSelectedItemsPathAsync(CodeConversion.IsVBFileName);

                menuItem.Visible = menuItem.Enabled = itemsPath.Count != 0;
            }
        }
 private async Task SolutionOrProjectMenuItemCallbackAsync(CancellationToken cancellationToken)
 {
     try {
         var projects = VisualStudioInteraction.GetSelectedProjectsAsync(ProjectExtension);
         await _codeConversion.ConvertProjectsAsync <CSToVBConversion>(await projects, cancellationToken);
     } catch (Exception ex) {
         await VisualStudioInteraction.ShowExceptionAsync(ex);
     }
 }
Esempio n. 9
0
        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, CancellationToken cancellationToken)
        {
            if (documentPath == null || !CodeConversion.IsCSFileName(documentPath))
            {
                return;
            }

            try {
                await _codeConversion.ConvertDocumentAsync <CSToVBConversion>(documentPath, selected, cancellationToken);
            } catch (Exception ex) {
                await VisualStudioInteraction.ShowExceptionAsync(ex);
            }
        }
Esempio n. 11
0
        private async Task ConvertDocumentsAsync(IReadOnlyCollection <string> documentsPath, CancellationToken cancellationToken)
        {
            if (documentsPath.Count == 0)
            {
                await VisualStudioInteraction.ShowMessageBoxAsync("Unable to find any files valid for conversion.");

                return;
            }

            try {
                await _codeConversion.ConvertDocumentsAsync <VBToCSConversion>(documentsPath, cancellationToken);
            } catch (Exception ex) {
                await _package.ShowExceptionAsync(ex);
            }
        }
        public async Task PasteAsAsync <TLanguageConversion>(CancellationToken cancellationToken) where TLanguageConversion : ILanguageConversion, new()
        {
            var caretPosition = await VisualStudioInteraction.GetCaretPositionAsync(_serviceProvider);

            _outputWindow.WriteToOutputWindowAsync("Converting clipboard text...", true, true).Forget();

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            string text = Clipboard.GetText();

            var convertTextOnly = await _joinableTaskFactory.RunAsync(async() =>
                                                                      await ConvertTextAsync <TLanguageConversion>(text, cancellationToken)
                                                                      );

            await caretPosition.InsertAsync(convertTextOnly.ConvertedCode);
        }
Esempio n. 13
0
        public async Task ConvertDocumentsAsync <TLanguageConversion>(IReadOnlyCollection <string> documentsFilePath, CancellationToken cancellationToken) where TLanguageConversion : ILanguageConversion, new()
        {
            try {
                var containingProject = await VisualStudioInteraction.GetFirstProjectContainingAsync(documentsFilePath.First());
                await EnsureBuiltAsync(containingProject is null?Array.Empty <Project>() : new[] { containingProject });

                await _joinableTaskFactory.RunAsync(async() => {
                    var result = ConvertDocumentsUnhandled <TLanguageConversion>(documentsFilePath, cancellationToken);
                    await WriteConvertedFilesAndShowSummaryAsync(result);
                });
            } catch (OperationCanceledException) {
                if (!_packageCancellation.CancelAll.IsCancellationRequested)
                {
                    await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + "Previous conversion cancelled", forceShow : true);
                }
            }
        }
Esempio n. 14
0
        /// <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);
        }
Esempio n. 15
0
        private async 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" : "";
            await _outputWindow.WriteToOutputWindowAsync(Environment.NewLine + "Awaiting user confirmation for overwrite....", forceShow : true);

            bool shouldOverwrite = await VisualStudioInteraction.ShowMessageBoxAsync("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);

            await _outputWindow.WriteToOutputWindowAsync(shouldOverwrite? "confirmed" : "declined");

            return(shouldOverwrite);
        }
        private async Task ProjectItemMenuItem_BeforeQueryStatusAsync(object sender, EventArgs e)
        {
            if (sender is OleMenuCommand menuItem)
            {
                menuItem.Visible = false;
                menuItem.Enabled = false;

                string itemPath = await VisualStudioInteraction.GetSingleSelectedItemPathOrDefaultAsync();

                if (itemPath == null || !CodeConversion.IsCSFileName(itemPath))
                {
                    return;
                }

                menuItem.Visible = true;
                menuItem.Enabled = true;
            }
        }
Esempio n. 17
0
        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(Environment.NewLine + $"* {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, false, true);
        }
Esempio n. 18
0
 /// <remarks>
 /// https://github.com/icsharpcode/CodeConverter/issues/592
 /// https://github.com/dotnet/roslyn/issues/6615
 /// </remarks>
 private async Task EnsureBuiltAsync(IReadOnlyCollection <Project> readOnlyCollection)
 {
     await VisualStudioInteraction.EnsureBuiltAsync(readOnlyCollection, m => _outputWindow.WriteToOutputWindowAsync(m));
 }
        private async Task ProjectItemMenuItemCallbackAsync(CancellationToken cancellationToken)
        {
            string itemPath = await VisualStudioInteraction.GetSingleSelectedItemPathOrDefaultAsync();

            await ConvertDocumentAsync(itemPath, new Span(0, 0), cancellationToken);
        }
Esempio n. 20
0
        private async Task ProjectItemMenuItemCallbackAsync(CancellationToken cancellationToken)
        {
            var itemsPath = await VisualStudioInteraction.GetSelectedItemsPathAsync(CodeConversion.IsVBFileName);

            await ConvertDocumentsAsync(itemsPath, cancellationToken);
        }
 /// <remarks>
 /// https://github.com/icsharpcode/CodeConverter/issues/592
 /// https://github.com/dotnet/roslyn/issues/6615
 /// </remarks>
 private async Task EnsureBuiltAsync()
 {
     await VisualStudioInteraction.EnsureBuiltAsync(m => _outputWindow.WriteToOutputWindowAsync(m));
 }