public DiagnosticProgressReporter(
            SVsTaskStatusCenterService taskStatusCenterService,
            IDiagnosticService diagnosticService,
            VisualStudioWorkspace workspace)
        {
            _lastTimeReported = DateTimeOffset.UtcNow;

            _taskCenterService = (IVsTaskStatusCenterService)taskStatusCenterService;
            _diagnosticService = diagnosticService;

            _options = new TaskHandlerOptions()
            {
                Title = ServicesVSResources.Live_code_analysis,
                ActionsAfterCompletion = CompletionActions.None
            };

            var crawlerService = workspace.Services.GetService <ISolutionCrawlerService>();
            var reporter       = crawlerService.GetProgressReporter(workspace);

            Started(reporter.InProgress);

            // no event unsubscription since it will remain alive until VS shutdown
            reporter.ProgressChanged += OnSolutionCrawlerProgressChanged;
            _diagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated;
        }
 public AddVirtualEnvironmentOperation(
     IServiceProvider site,
     PythonProjectNode project,
     string virtualEnvPath,
     string baseInterpreterId,
     bool useVEnv,
     bool installRequirements,
     string requirementsPath,
     bool registerAsCustomEnv,
     string customEnvName,
     bool setAsCurrent,
     bool setAsDefault,
     bool viewInEnvWindow,
     Redirector output = null
     )
 {
     _site                = site ?? throw new ArgumentNullException(nameof(site));
     _project             = project;
     _virtualEnvPath      = virtualEnvPath ?? throw new ArgumentNullException(nameof(virtualEnvPath));
     _baseInterpreter     = baseInterpreterId ?? throw new ArgumentNullException(nameof(baseInterpreterId));
     _useVEnv             = useVEnv;
     _installReqs         = installRequirements;
     _reqsPath            = requirementsPath;
     _registerAsCustomEnv = registerAsCustomEnv;
     _customEnvName       = customEnvName;
     _setAsCurrent        = setAsCurrent;
     _setAsDefault        = setAsDefault;
     _viewInEnvWindow     = viewInEnvWindow;
     _output              = output;
     _statusCenter        = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
     _registry            = _site.GetComponentModel().GetService <IInterpreterRegistryService>();
     _options             = _site.GetComponentModel().GetService <IInterpreterOptionsService>();
     _logger              = _site.GetService(typeof(IPythonToolsLogger)) as IPythonToolsLogger;
 }
Exemple #3
0
        public TaskCenterSolutionAnalysisProgressReporter(
            SVsTaskStatusCenterService taskStatusCenterService,
            IDiagnosticService diagnosticService,
            VisualStudioWorkspace workspace)
        {
            _lastTimeReported = DateTimeOffset.UtcNow;
            _resettableDelay  = null;

            ResetProgressStatus();

            _taskCenterService = (IVsTaskStatusCenterService)taskStatusCenterService;

            _options = new TaskHandlerOptions()
            {
                Title = ServicesVSResources.Running_low_priority_background_processes,
                ActionsAfterCompletion = CompletionActions.None
            };

            var crawlerService = workspace.Services.GetService <ISolutionCrawlerService>();
            var reporter       = crawlerService.GetProgressReporter(workspace);

            StartedOrStopped(reporter.InProgress);

            // no event unsubscription since it will remain alive until VS shutdown
            reporter.ProgressChanged += OnSolutionCrawlerProgressChanged;
        }
Exemple #4
0
 public InstallPackagesOperation(
     IServiceProvider site,
     IPackageManager pm,
     string requirementsPath,
     Redirector output = null
     )
 {
     _site         = site ?? throw new ArgumentNullException(nameof(site));
     _pm           = pm ?? throw new ArgumentNullException(nameof(pm));
     _reqsPath     = requirementsPath ?? throw new ArgumentNullException(nameof(requirementsPath));
     _output       = output;
     _statusCenter = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
 }
        private static async Task <ITaskHandler> SetupTaskStatusCenter()
        {
            IVsTaskStatusCenterService tsc =
                await _package.GetServiceAsync(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;

            TaskHandlerOptions options = default(TaskHandlerOptions);

            options.Title = Vsix.Name;
            options.DisplayTaskDetails     = task => { Logger.ShowOutputWindowPane(); };
            options.ActionsAfterCompletion = CompletionActions.None;
            TaskProgressData data = default(TaskProgressData);

            data.CanBeCanceled = true;
            return(tsc.PreRegister(options, data));
        }
        public async Task <ITaskHandler> CreateTaskHandlerAsync(string title)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsTaskStatusCenterService taskStatusCenter = (IVsTaskStatusCenterService)Package.GetGlobalService(typeof(SVsTaskStatusCenterService));
            TaskHandlerOptions         options          = default(TaskHandlerOptions);

            options.Title = title;
            options.ActionsAfterCompletion = CompletionActions.None;

            TaskProgressData data = default(TaskProgressData);

            data.CanBeCanceled = true;

            ITaskHandler handler = taskStatusCenter.PreRegister(options, data);

            return(handler);
        }
        public AddCondaEnvironmentOperation(
            IServiceProvider site,
            ICondaEnvironmentManager condaMgr,
            PythonProjectNode project,
            IPythonWorkspaceContext workspace,
            string envNameOrPath,
            string envFilePath,
            List <PackageSpec> packages,
            bool setAsCurrent,
            bool setAsDefault,
            bool viewInEnvWindow
            )
        {
            _site            = site ?? throw new ArgumentNullException(nameof(site));
            _condaMgr        = condaMgr ?? throw new ArgumentNullException(nameof(condaMgr));
            _project         = project;
            _workspace       = workspace;
            _envNameOrPath   = envNameOrPath ?? throw new ArgumentNullException(nameof(envNameOrPath));
            _envFilePath     = envFilePath;
            _packages        = packages ?? throw new ArgumentNullException(nameof(packages));
            _setAsCurrent    = setAsCurrent;
            _setAsDefault    = setAsDefault;
            _viewInEnvWindow = viewInEnvWindow;

            // If passed a path, the actual name reported by conda will the last part
            _actualName = PathUtils.GetFileOrDirectoryName(_envNameOrPath);
            if (_actualName.Length == 0)
            {
                _actualName = _envNameOrPath;
            }

            _outputWindow = OutputWindowRedirector.GetGeneral(_site);
            _statusBar    = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
            _showAndActiveOutputWindow = _site.GetPythonToolsService().GeneralOptions.ShowOutputWindowForVirtualEnvCreate;
            _statusCenter    = _site.GetService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
            _registry        = _site.GetComponentModel().GetService <IInterpreterRegistryService>();
            _options         = _site.GetComponentModel().GetService <IInterpreterOptionsService>();
            _logger          = _site.GetService(typeof(IPythonToolsLogger)) as IPythonToolsLogger;
            _factoryProvider = _site.GetComponentModel().GetService <CondaEnvironmentFactoryProvider>();
        }
Exemple #8
0
        public TaskCenterSolutionAnalysisProgressReporter(
            SVsTaskStatusCenterService taskStatusCenterService,
            IDiagnosticService diagnosticService,
            VisualStudioWorkspace workspace)
        {
            _taskCenterService = (IVsTaskStatusCenterService)taskStatusCenterService;
            _options           = new TaskHandlerOptions()
            {
                Title = ServicesVSResources.Running_low_priority_background_processes,
                ActionsAfterCompletion = CompletionActions.None
            };

            var crawlerService = workspace.Services.GetRequiredService <ISolutionCrawlerService>();
            var reporter       = crawlerService.GetProgressReporter(workspace);

            if (reporter.InProgress)
            {
                // The reporter was already sending events before we were able to subscribe, so trigger an update to the task center.
                OnSolutionCrawlerProgressChanged(this, new ProgressData(ProgressStatus.Started, pendingItemCount: null));
            }

            reporter.ProgressChanged += OnSolutionCrawlerProgressChanged;
        }
Exemple #9
0
        public void ApplyChanges()
        {
            IVsTaskStatusCenterService taskCenter = Package.GetGlobalService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
            ITaskHandler taskHandler = taskCenter.PreRegister(
                new TaskHandlerOptions()
            {
                Title = "Updating sdks..."
            },
                new TaskProgressData());

            if (model.SdkChangesCollector.SdksToRemove.Count > 0)
            {
                RemoveSdkViewModel dialogVM = new RemoveSdkViewModel(model.SdkChangesCollector.SdksToRemove);
                RemoveSdkDialog    dialog   = new RemoveSdkDialog(dialogVM);
                bool?result = dialog.ShowModal();
                if (result == null || result == false)
                {
                    return;
                }
                if (dialogVM.RemoveFromDisk)
                {
                    foreach (string path in model.SdkChangesCollector.SdksToRemove)
                    {
                        Directory.Delete(path, true);
                    }
                }
            }


            taskHandler.RegisterTask(Task.Run(async() =>
            {
                foreach (string sdk in model.SdkChangesCollector.SdksToRemove)
                {
                    ITaskHandler subTaskHandler = taskCenter.PreRegister(
                        new TaskHandlerOptions()
                    {
                        Title = $"Removing sdk {sdk}"
                    },
                        new TaskProgressData());

                    Task task = Task.Run(() =>
                    {
                        try
                        {
                            plcncliCommunication.ExecuteCommand("set setting", null, null, "-r", "SdkPaths", $"\"{sdk}\"");
                        }
                        catch (PlcncliException e)
                        {
                            MessageBox.Show(e.Message, "PLCnCLI error");
                        }
                    });
                    subTaskHandler.RegisterTask(task);
                    await task;
                }

                foreach (string sdk in model.SdkChangesCollector.SdksToAdd)
                {
                    ITaskHandler subTaskHandler = taskCenter.PreRegister(
                        new TaskHandlerOptions()
                    {
                        Title = $"Adding sdk {sdk}"
                    },
                        new TaskProgressData());

                    Task task = Task.Run(() =>
                    {
                        try
                        {
                            plcncliCommunication.ExecuteCommand("set setting", null, null, "-a", "SdkPaths", $"\"{sdk}\"");
                        }
                        catch (PlcncliException e)
                        {
                            MessageBox.Show(e.Message, "PLCnCLI error");
                        }
                    });
                    subTaskHandler.RegisterTask(task);
                    await task;
                }
                foreach (InstallSdk sdk in model.SdkChangesCollector.SdksToInstall)
                {
                    ITaskHandler subTaskHandler = taskCenter.PreRegister(
                        new TaskHandlerOptions()
                    {
                        Title = $"Installing sdk {sdk.ArchiveFile} to {sdk.Destination}"
                    },
                        new TaskProgressData());
                    Task task = Task.Run(() =>
                    {
                        try
                        {
                            plcncliCommunication.ExecuteCommand("install sdk", null, null, "--path", $"\"{sdk.ArchiveFile}\"",
                                                                "--destination", $"\"{sdk.Destination}\"", sdk.Force ? "--force" : "");
                        }
                        catch (PlcncliException e)
                        {
                            MessageBox.Show(e.Message, "PLCnCLI error");
                        }
                    });
                    subTaskHandler.RegisterTask(task);
                    await task;
                }
            }));

            if (model.SdkChangesCollector.SdksToInstall.Count > 0)
            {
                MessageBox.Show("Installing sdks in background. This may take a while. New sdks are available after background task has finished." +
                                " Check lower left corner for active background tasks.", "Background installation started", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void SetTargets(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IServiceProvider serviceProvider = package;
            Project          project         = GetProject();

            if (project == null)
            {
                return;
            }
            string projectDirectory = Path.GetDirectoryName(project.FullName);

            //show dialog
            ProjectTargetValueEditorModel     model     = new ProjectTargetValueEditorModel(serviceProvider, projectDirectory);
            ProjectTargetValueEditorViewModel viewModel = new ProjectTargetValueEditorViewModel(model);
            ProjectTargetValueEditorView      view      = new ProjectTargetValueEditorView(viewModel);

            view.ShowModal();

            if (view.DialogResult == true)
            {
                if (!(serviceProvider.GetService(typeof(SPlcncliCommunication)) is IPlcncliCommunication cliCommunication))
                {
                    MessageBox.Show("Could not set project targets because no plcncli communication found.");
                    return;
                }

                VCProject p = project.Object as VCProject;
                bool      needProjectInformation  = false;
                bool      needCompilerInformation = false;

                var(includesSaved, macrosSaved) = ProjectIncludesManager.CheckSavedIncludesAndMacros(p);
                needProjectInformation          = !includesSaved;
                needCompilerInformation         = !macrosSaved;

                IEnumerable <string> includesBefore                        = null;
                IEnumerable <CompilerMacroResult>  macrosBefore            = Enumerable.Empty <CompilerMacroResult>();
                CompilerSpecificationCommandResult compilerSpecsAfter      = null;
                ProjectInformationCommandResult    projectInformationAfter = null;


                IVsTaskStatusCenterService taskCenter = Package.GetGlobalService(typeof(SVsTaskStatusCenterService)) as IVsTaskStatusCenterService;
                ITaskHandler taskHandler = taskCenter.PreRegister(
                    new TaskHandlerOptions()
                {
                    Title = $"Setting project targets"
                },
                    new TaskProgressData());
                Task task = Task.Run(async() =>
                {
                    try
                    {
                        if (needProjectInformation)
                        {
                            ProjectInformationCommandResult projectInformationBefore = null;
                            try
                            {
                                projectInformationBefore = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                           typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                           $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                try
                                {
                                    projectInformationBefore = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                                }
                                catch (PlcncliException) {}
                            }

                            includesBefore = projectInformationBefore?.IncludePaths.Select(x => x.PathValue);
                            if (includesBefore == null)
                            {
                                includesBefore = Enumerable.Empty <string>();
                            }
                        }

                        if (needCompilerInformation)
                        {
                            CompilerSpecificationCommandResult compilerSpecsBefore = null;
                            try
                            {
                                compilerSpecsBefore = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                      typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                      $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                compilerSpecsBefore = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                            }
                            macrosBefore = compilerSpecsBefore?.Specifications.FirstOrDefault()
                                           ?.CompilerMacros.Where(m => !m.Name.StartsWith("__has_include(")) ?? Enumerable.Empty <CompilerMacroResult>();
                        }

                        SetTargets();

                        try
                        {
                            projectInformationAfter = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                      typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                      $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            projectInformationAfter = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                        }
                        try
                        {
                            compilerSpecsAfter = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                 typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                 $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                        }
                        catch (PlcncliException ex)
                        {
                            compilerSpecsAfter = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                        }

                        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                        ProjectConfigurationManager.CreateConfigurationsForAllProjectTargets
                            (projectInformationAfter?.Targets.Select(t => t.GetNameFormattedForCommandLine()), project);


                        ProjectIncludesManager.UpdateIncludesAndMacrosForExistingProject(p, macrosBefore,
                                                                                         compilerSpecsAfter, includesBefore, projectInformationAfter);

                        p.Save();

                        ProjectIncludesManager.AddTargetsFileToOldProjects(p);

                        void SetTargets()
                        {
                            foreach (TargetResult target in model.TargetsToAdd)
                            {
                                cliCommunication.ExecuteCommand(Resources.Command_set_target, null, null,
                                                                Resources.Option_set_target_add, Resources.Option_set_target_project,
                                                                $"\"{projectDirectory}\"",
                                                                Resources.Option_set_target_name, target.Name, Resources.Option_set_target_version,
                                                                $"\"{target.LongVersion}\"");
                            }

                            foreach (TargetResult target in model.TargetsToRemove)
                            {
                                cliCommunication.ExecuteCommand(Resources.Command_set_target, null, null,
                                                                Resources.Option_set_target_remove, Resources.Option_set_target_project,
                                                                $"\"{projectDirectory}\"",
                                                                Resources.Option_set_target_name, target.Name, Resources.Option_set_target_version,
                                                                $"\"{target.LongVersion}\"");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + ex.StackTrace ?? string.Empty, "Exception during setting of targets");
                        throw ex;
                    }
                });
                taskHandler.RegisterTask(task);
            }
        }