Esempio n. 1
0
        public CopyForm(ICopyController copyController, IProgressController progressController)
        {
            this.copyController = copyController;
            this.progressController = progressController;

            InitializeComponent();

            copyController.SourcePluginFolder.PropertyChanged +=
                (s, e) => sourcePluginFolderTextBox.Text = copyController.SourcePluginFolder;
            copyController.TargetPluginFolder.PropertyChanged +=
                (s, e) => targetPluginFolderTextBox.Text = copyController.TargetPluginFolder;

            sourcePluginTreeView.Model = copyController.SourcePlugins;
            targetPluginTreeView.Model = copyController.TargetPlugins;

            progressController.Status.PropertyChanged += (s, e) =>
            {
                taskNameStatusLabel.Text = progressController.Status;
            };
            progressController.TotalWork.PropertyChanged += (s, e) =>
            {
                toolStripProgressBar.TotalWork = progressController.TotalWork;
            };
            progressController.CompletedWork.PropertyChanged += (s, e) =>
            {
                toolStripProgressBar.CompletedWork = progressController.CompletedWork;
            };
            progressController.DisplayProgressDialog += (s, e) => Sync.Invoke(this, () =>
                new ProgressMonitorDialog(e.ProgressMonitor).Show(this));

            copyController.PluginFolderUpdated += (s, e) => Sync.Invoke(this, () => ExpandPluginList(e.Folder));
        }
Esempio n. 2
0
        // TODO: localize filter?
        public void WriteStatsReport(string title, string cap1, string cap2, List <StatsItem> vals)
        {
#if !NETSTANDARD
            if (vals == null)
            {
                return;
            }

            string fileName = AppHost.StdDialogs.GetSaveFile("", "", "Excel files (*.xls)|*.xls", 1, "xls", "");
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            IProgressController progress = AppHost.Progress;
            try
            {
                int rowsCount = vals.Count;
                progress.ProgressInit(LangMan.LS(LSID.LSID_MIExport) + "...", rowsCount);

                try
                {
                    Workbook  workbook  = new Workbook();
                    Worksheet worksheet = new Worksheet(title);

                    worksheet.Cells[0, 1] = new Cell(cap1);
                    worksheet.Cells[0, 2] = new Cell(cap2);

                    int row = 1;
                    for (int i = 0; i < rowsCount; i++)
                    {
                        StatsItem item = vals[i];
                        worksheet.Cells[row, 1] = new Cell(item.Caption);
                        worksheet.Cells[row, 2] = new Cell(item.GetDisplayString());

                        row++;
                        progress.ProgressStep();
                    }

                    workbook.Worksheets.Add(worksheet);
                    workbook.Save(fileName);

                    if (File.Exists(fileName))
                    {
                        Process.Start(fileName);
                    }
                }
                finally
                {
                    progress.ProgressDone();
                }
            }
            catch (Exception ex)
            {
                Logger.LogWrite("TreeStats.WriteStatsReport(): " + ex.Message);
                AppHost.StdDialogs.ShowError(LangMan.LS(LSID.LSID_UploadErrorInExcel));
            }
#endif
        }
Esempio n. 3
0
    public QuestsController(IProgressController progressController)
    {
        _progressController = progressController;

        _progressController.OnTotalScore += OnProgressChanged;
        _progressController.OnCrystals   += OnProgressChanged;
        _progressController.OnLevels     += OnProgressChanged;
    }
        private void AbortWorkflow(IProgressController controller, CancellationToken token)
        {
            bool aborted = controller.TryAbort();

            Debug.Assert(aborted || token.IsCancellationRequested, "Failed to abort the workflow");

            this.host.SonarQubeService.Disconnect();
        }
 public frmUserProgressWindow(IUserController inUserController, IProgressController inProgressController, IRepositoryFactory inRepositoryFactory)
 {
     _userController     = inUserController;
     _progressController = inProgressController;
     _repositoryFactory  = inRepositoryFactory;
     user = _userController.GetUser();
     InitializeComponent();
 }
Esempio n. 6
0
 private ProgressStepDefinition[] CreateWorkflowSteps(IProgressController controller)
 {
     return(new ProgressStepDefinition[]
     {
         new ProgressStepDefinition(Strings.Bind_SavingBindingConfiguration, StepAttributes.Indeterminate,
                                    (token, notifications) => this.SaveBindingInfo(controller, notifications, token)),
     });
 }
        /// <summary>
        /// Will install the NuGet packages for the current managed projects.
        /// The packages that will be installed will be based on the information from <see cref="Analyzer.GetRequiredNuGetPackages"/>
        /// and is specific to the <see cref="RuleSet"/>.
        /// </summary>
        internal /*for testing purposes*/ void InstallPackages(IProgressController controller, CancellationToken token, IProgressStepExecutionEvents notificationEvents)
        {
            if (!this.NuGetPackages.Any())
            {
                return;
            }

            Debug.Assert(this.NuGetPackages.Count == this.NuGetPackages.Distinct().Count(), "Duplicate NuGet packages specified");

            if (!this.BindingProjects.Any())
            {
                Debug.Fail("Not expected to be called when there are no projects");
                return;
            }

            var projectNugets = this.BindingProjects
                                .SelectMany(bindingProject =>
            {
                var projectLanguage = Language.ForProject(bindingProject);

                List <NuGetPackageInfoResponse> nugetPackages;
                if (!this.NuGetPackages.TryGetValue(projectLanguage, out nugetPackages))
                {
                    var message = string.Format(Strings.BindingProjectLanguageNotMatchingAnyQualityProfileLanguage, bindingProject.Name);
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);
                    nugetPackages = new List <NuGetPackageInfoResponse>();
                }

                return(nugetPackages.Select(nugetPackage => new { Project = bindingProject, NugetPackage = nugetPackage }));
            })
                                .ToArray();

            DeterminateStepProgressNotifier progressNotifier = new DeterminateStepProgressNotifier(notificationEvents, projectNugets.Length);

            foreach (var projectNuget in projectNugets)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                string message = string.Format(CultureInfo.CurrentCulture, Strings.EnsuringNugetPackagesProgressMessage, projectNuget.NugetPackage.Id, projectNuget.Project.Name);
                VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);

                var isNugetInstallSuccessful = NuGetHelper.TryInstallPackage(this.host, projectNuget.Project, projectNuget.NugetPackage.Id, projectNuget.NugetPackage.Version);

                if (isNugetInstallSuccessful) // NuGetHelper.TryInstallPackage already displayed the error message so only take care of the success message
                {
                    message = string.Format(CultureInfo.CurrentCulture, Strings.SuccessfullyInstalledNugetPackageForProject, projectNuget.NugetPackage.Id, projectNuget.Project.Name);
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);
                }

                // TODO: SVS-33 (https://jira.sonarsource.com/browse/SVS-33) Trigger a Team Explorer warning notification to investigate the partial binding in the output window.
                this.AllNuGetPackagesInstalled &= isNugetInstallSuccessful;

                progressNotifier.NotifyIncrementedProgress(string.Empty);
            }
        }
Esempio n. 8
0
 public DataRetriever(DataContext dataContext, IProgressController progressController)
 {
     this.dataContext               = dataContext;
     this.processedItemCount        = this.dataContext.ProcessedItemCount;
     this.currentBatch              = new List <ItemId>(ConstantProvider.ExportBatchItemCountLimit);
     this.currentBatchSize          = 0U;
     this.currentBatchForDuplicates = new List <ItemId>(ConstantProvider.ExportBatchItemCountLimit);
     this.progressController        = progressController;
 }
Esempio n. 9
0
        public static ExtList <PatriarchObj> GetPatriarchsList(IBaseContext context,
                                                               int gensMin, bool datesCheck)
        {
            ExtList <PatriarchObj> patList = new ExtList <PatriarchObj>(true);

            IProgressController progress = AppHost.Progress;

            progress.ProgressInit(LangMan.LS(LSID.LSID_PatSearch), context.Tree.RecordsCount);

            GKUtils.InitExtCounts(context.Tree, -1);
            try
            {
                int num = context.Tree.RecordsCount;
                for (int i = 0; i < num; i++)
                {
                    GEDCOMRecord rec = context.Tree[i];

                    if (rec is GEDCOMIndividualRecord)
                    {
                        GEDCOMIndividualRecord iRec = rec as GEDCOMIndividualRecord;

                        var parts = GKUtils.GetNameParts(iRec);

                        int birthDate = context.FindBirthYear(iRec);
                        int descGens  = GKUtils.GetDescGenerations(iRec);

                        bool res = (iRec.ChildToFamilyLinks.Count == 0);
                        res = (res && iRec.Sex == GEDCOMSex.svMale);
                        res = (res && /*nf != "" && nf != "?" &&*/ parts.Name != "" && parts.Name != "?");
                        res = (res && descGens >= gensMin);

                        if (datesCheck)
                        {
                            res = (res && birthDate != 0);
                        }

                        if (res)
                        {
                            PatriarchObj pObj = new PatriarchObj();
                            pObj.IRec             = iRec;
                            pObj.BirthYear        = birthDate;
                            pObj.DescendantsCount = GKUtils.GetDescendantsCount(iRec) - 1;
                            pObj.DescGenerations  = descGens;
                            patList.Add(pObj);
                        }
                    }

                    progress.ProgressStep();
                }
            }
            finally
            {
                progress.ProgressDone();
            }

            return(patList);
        }
        private void FinishSolutionBindingOnUIThread(IProgressController controller, CancellationToken token)
        {
            Debug.Assert(System.Windows.Application.Current?.Dispatcher.CheckAccess() ?? false, "Expected to run on UI thread");

            if (!this.solutionBindingOperation.CommitSolutionBinding())
            {
                AbortWorkflow(controller, token);
            }
        }
        internal /* for testing */ void FinishSolutionBindingOnUIThread(IProgressController controller, CancellationToken token)
        {
            Debug.Assert(host.UIDispatcher.CheckAccess(), "Expected to run on UI thread");

            if (!bindingProcess.FinishSolutionBindingOnUIThread())
            {
                AbortWorkflow(controller, token);
            }
        }
        internal /*for testing purposes*/ void PromptSaveSolutionIfDirty(IProgressController controller, CancellationToken token)
        {
            if (!VsShellUtils.SaveSolution(this.host, silent: false))
            {
                VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SolutionSaveCancelledBindAborted);

                this.AbortWorkflow(controller, token);
            }
        }
Esempio n. 13
0
        public static ExtList <PatriarchObj> GetPatriarchsLinks(IBaseContext context,
                                                                int gensMin, bool datesCheck,
                                                                bool loneSuppress)
        {
            ExtList <PatriarchObj> patList = GetPatriarchsList(context, gensMin, datesCheck);

            IProgressController progress = AppHost.Progress;

            progress.ProgressInit(LangMan.LS(LSID.LSID_LinksSearch), patList.Count);
            try {
                int num2 = patList.Count;
                for (int i = 0; i < num2; i++)
                {
                    PatriarchObj patr = patList[i];

                    for (int j = i + 1; j < num2; j++)
                    {
                        PatriarchObj patr2 = patList[j];

                        GDMIndividualRecord cross = TreeTools.PL_SearchDesc(context.Tree, patr.IRec, patr2.IRec);
                        if (cross != null)
                        {
                            patr.HasLinks  = true;
                            patr2.HasLinks = true;

                            if (cross.Sex == GDMSex.svFemale)
                            {
                                patr.Links.Add(patr2);
                            }
                            else
                            {
                                patr2.Links.Add(patr);
                            }
                        }
                    }

                    progress.ProgressStep();
                }
            } finally {
                progress.ProgressDone();
            }

            if (loneSuppress)
            {
                for (int i = patList.Count - 1; i >= 0; i--)
                {
                    PatriarchObj patr = patList[i];
                    if (!patr.HasLinks)
                    {
                        patList.Delete(i);
                    }
                }
                patList.Pack();
            }

            return(patList);
        }
        private void FinishSolutionBindingOnUIThread(IProgressController controller, CancellationToken token)
        {
            Debug.Assert(host.UIDispatcher.CheckAccess(), "Expected to run on UI thread");

            if (!this.solutionBindingOperation.CommitSolutionBinding())
            {
                AbortWorkflow(controller, token);
            }
        }
        internal /*for testing purposes*/ void DiscoverProjects(IProgressController controller, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(ThreadHelper.CheckAccess(), "Expected step to be run on the UI thread");

            notifications.ProgressChanged(Strings.DiscoveringSolutionProjectsProgressMessage);

            if (!bindingProcess.DiscoverProjects())
            {
                AbortWorkflow(controller, CancellationToken.None);
            }
        }
Esempio n. 16
0
        private void AbortWithMessage(IProgressStepExecutionEvents notifications, IProgressController controller,
                                      CancellationToken cancellationToken)
        {
            notifications.ProgressChanged(cancellationToken.IsCancellationRequested
                ? Strings.ConnectionResultCancellation
                : Strings.ConnectionResultFailure);
            this.host.ActiveSection?.UserNotifications?.ShowNotificationError(Strings.ConnectionFailed,
                                                                              NotificationIds.FailedToConnectId, this.parentCommand);

            AbortWorkflow(controller, cancellationToken);
        }
        private bool VerifyDotNetPlugins(IProgressController controller, CancellationToken cancellationToken, ConnectionInformation connection, IProgressStepExecutionEvents notifications)
        {
            notifications.ProgressChanged(Strings.DetectingServerPlugins);

            ServerPlugin[] plugins;
            if (!this.host.SonarQubeService.TryGetPlugins(connection, cancellationToken, out plugins))
            {
                notifications.ProgressChanged(cancellationToken.IsCancellationRequested ? Strings.ConnectionResultCancellation : Strings.ConnectionResultFailure);
                this.host.ActiveSection?.UserNotifications?.ShowNotificationError(Strings.ConnectionFailed, NotificationIds.FailedToConnectId, this.parentCommand);

                AbortWorkflow(controller, cancellationToken);
                return(false);
            }

            IsCSharpPluginSupported = VerifyPluginSupport(plugins, MinimumSupportedServerPlugin.CSharp);
            IsVBNetPluginSupported  = VerifyPluginSupport(plugins, MinimumSupportedServerPlugin.VbNet);

            var projects         = this.projectSystem.GetSolutionProjects().ToList();
            var anyCSharpProject = projects.Any(p => MinimumSupportedServerPlugin.CSharp.ISupported(p));
            var anyVbNetProject  = projects.Any(p => MinimumSupportedServerPlugin.VbNet.ISupported(p));

            string errorMessage;

            if ((IsCSharpPluginSupported && anyCSharpProject) ||
                (IsVBNetPluginSupported && anyVbNetProject))
            {
                return(true);
            }
            else if (!IsCSharpPluginSupported && !IsVBNetPluginSupported)
            {
                errorMessage = Strings.ServerHasNoSupportedPluginVersion;
            }
            else if (projects.Count == 0)
            {
                errorMessage = Strings.SolutionContainsNoSupportedProject;
            }
            else if (IsCSharpPluginSupported && !anyCSharpProject)
            {
                errorMessage = string.Format(Strings.OnlySupportedPluginHasNoProjectInSolution, Language.CSharp.Name);
            }
            else
            {
                errorMessage = string.Format(Strings.OnlySupportedPluginHasNoProjectInSolution, Language.VBNET.Name);
            }

            this.host.ActiveSection?.UserNotifications?.ShowNotificationError(errorMessage, NotificationIds.BadServerPluginId, null);
            VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, errorMessage);
            notifications.ProgressChanged(Strings.ConnectionResultFailure);

            AbortWorkflow(controller, cancellationToken);
            return(false);
        }
Esempio n. 18
0
 public PstWriter(PstTarget target, IProgressController progressController)
 {
     this.progressController = progressController;
     this.target             = target;
     this.timer = new Stopwatch();
     this.targetFolderProvider    = new PstTargetFolderProvider();
     this.pstMBFileCount          = 1;
     this.unsearchableMBTotalSize = 0L;
     this.searchableMBTotalSize   = 0L;
     this.pstPFFileCount          = 1;
     this.unsearchablePFTotalSize = 0L;
     this.searchablePFTotalSize   = 0L;
 }
        private ProgressStepDefinition[] CreateConnectionSteps(IProgressController controller, ConnectionInformation connection)
        {
            string connectStepDisplayText = string.Format(CultureInfo.CurrentCulture, Resources.Strings.ConnectingToSever, connection.ServerUri);
            return new[]
            {
                    new ProgressStepDefinition(connectStepDisplayText, StepAttributes.Indeterminate | StepAttributes.BackgroundThread,
                        (cancellationToken, notifications) => this.ConnectionStep(controller, cancellationToken, connection, notifications)),

                    new ProgressStepDefinition(connectStepDisplayText, StepAttributes.BackgroundThread,
                        (token, notifications) => this.DownloadServiceParameters(controller, token, notifications)),

                };
        }
        private ProgressStepDefinition[] CreateConnectionSteps(IProgressController controller, ConnectionInformation connection)
        {
            string connectStepDisplayText = string.Format(CultureInfo.CurrentCulture, Resources.Strings.ConnectingToSever, connection.ServerUri);

            return(new[]
            {
                new ProgressStepDefinition(connectStepDisplayText, StepAttributes.Indeterminate | StepAttributes.BackgroundThread,
                                           (cancellationToken, notifications) => this.ConnectionStep(controller, cancellationToken, connection, notifications)),

                new ProgressStepDefinition(connectStepDisplayText, StepAttributes.BackgroundThread,
                                           (token, notifications) => this.DownloadServiceParameters(controller, token, notifications)),
            });
        }
        internal /*for testing purposes*/ async System.Threading.Tasks.Task DownloadQualityProfileAsync(
            IProgressController controller, IProgressStepExecutionEvents notificationEvents,
            CancellationToken cancellationToken)
        {
            Debug.Assert(controller != null);
            Debug.Assert(notificationEvents != null);

            var progressAdapter = new FixedStepsProgressAdapter(notificationEvents);

            if (!await bindingProcess.DownloadQualityProfileAsync(progressAdapter, cancellationToken).ConfigureAwait(false))
            {
                this.AbortWorkflow(controller, cancellationToken);
            }
        }
 protected void ExecuteOperation(OperatingContext Context, IProgressController pc, string Command, CancellationToken CancellationToken)
 {
     pc.SetProgress(0);
     Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                   new CommandExpectation(@"SMDKC100 #", Context.Terminal, Command));
     Context.Surfer.SeekForMatches(Context.Terminal, CancellationToken,
                                   new DelegateExpectation(@"Writing data at 0x([0-9a-fA-F]+) --\s+(?<progress>\d+)% complete\.", false,
                                                           match => pc.SetProgress(0.01 * int.Parse(match.Groups["progress"].Value))),
                                   new DelegateExpectation(@"(?<length>\d+) bytes written\: (?<result>.+)\n", true,
                                                           match =>
                                                           {
                                                               if (match.Groups["result"].Value != "OK")
                                                                   throw new NandWriteErrorDnwBurningException(match.Groups["result"].Value);
                                                           }));
 }
Esempio n. 23
0
        internal /*for testing purposes*/ void DiscoverProjects(IProgressController controller, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(ThreadHelper.CheckAccess(), "Expected step to be run on the UI thread");

            notifications.ProgressChanged(Strings.DiscoveringSolutionProjectsProgressMessage);

            this.BindingProjects.UnionWith(this.projectSystem.GetFilteredSolutionProjects());

            this.InformAboutFilteredOutProjects();

            if (!this.BindingProjects.Any())
            {
                AbortWorkflow(controller, CancellationToken.None);
            }
        }
Esempio n. 24
0
        public static bool CheckGEDCOMFormat(IBaseContext baseContext, IProgressController pc)
        {
            if (baseContext == null)
            {
                throw new ArgumentNullException("baseContext");
            }

            if (pc == null)
            {
                throw new ArgumentNullException("pc");
            }

            var instance = new GEDCOMChecker(baseContext, pc);

            return(instance.CheckFormat());
        }
        /// <summary>
        /// Creates a step from definition
        /// </summary>
        /// <param name="controller">The hosting <see cref="IProgressController"/> for this step</param>
        /// <param name="definition">The <see cref="ProgressStepDefinition"/> for which to create the step</param>
        public ProgressControllerStep(IProgressController controller, ProgressStepDefinition definition)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (definition == null)
            {
                throw new ArgumentNullException(nameof(definition));
            }

            this.controller = controller;
            this.definition = definition;
            this.Initialize();
        }
        public IProgressStepOperation CreateStepOperation(IProgressController controller, IProgressStepDefinition definition)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            ProgressStepDefinition supportedDefinition = definition as ProgressStepDefinition;
            if (supportedDefinition == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ProgressResources.UnsupportedTypeException, definition.GetType().FullName, typeof(ProgressStepDefinition).FullName));
            }

            ProgressControllerStep step = new ProgressControllerStep(controller, supportedDefinition);
            return step;
        }
        /// <summary>
        /// Creates a step from definition
        /// </summary>
        /// <param name="controller">The hosting <see cref="IProgressController"/> for this step</param>
        /// <param name="definition">The <see cref="ProgressStepDefinition"/> for which to create the step</param>
        public ProgressControllerStep(IProgressController controller, ProgressStepDefinition definition)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (definition == null)
            {
                throw new ArgumentNullException(nameof(definition));
            }

            this.controller = controller;
            this.definition = definition;
            this.Initialize();
        }
Esempio n. 28
0
        internal /*for testing purposes*/ async Task DownloadServiceParametersAsync(IProgressController controller,
                                                                                    IProgressStepExecutionEvents notifications, CancellationToken token)
        {
            Debug.Assert(this.ConnectedServer != null);

            const string TestProjectRegexKey          = "sonar.cs.msbuild.testProjectPattern";
            const string TestProjectRegexDefaultValue = @"[^\\]*test[^\\]*$";

            // Should never realistically take more than 1 second to match against a project name
            var timeout      = TimeSpan.FromSeconds(1);
            var defaultRegex = new Regex(TestProjectRegexDefaultValue, RegexOptions.IgnoreCase, timeout);

            notifications.ProgressChanged(Strings.DownloadingServerSettingsProgessMessage);

            var properties = await this.host.SonarQubeService.GetAllPropertiesAsync(token);

            if (token.IsCancellationRequested)
            {
                AbortWorkflow(controller, token);
                return;
            }

            var testProjRegexPattern = properties.First(x => StringComparer.Ordinal.Equals(x.Key, TestProjectRegexKey)).Value;

            Regex regex = null;

            if (testProjRegexPattern != null)
            {
                // Try and create regex from provided server pattern.
                // No way to determine a valid pattern other than attempting to construct
                // the Regex object.
                try
                {
                    regex = new Regex(testProjRegexPattern, RegexOptions.IgnoreCase, timeout);
                }
                catch (ArgumentException)
                {
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.InvalidTestProjectRegexPattern,
                                                            testProjRegexPattern);
                }
            }

            var projectFilter = this.host.GetService <IProjectSystemFilter>();

            projectFilter.AssertLocalServiceIsNotNull();
            projectFilter.SetTestRegex(regex ?? defaultRegex);
        }
        internal /*for testing purposes*/ void DownloadServiceParameters(IProgressController controller, CancellationToken token, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(this.ConnectedServer != null);

            // Should never realistically take more than 1 second to match against a project name
            var timeout      = TimeSpan.FromSeconds(1);
            var defaultRegex = new Regex(ServerProperty.TestProjectRegexDefaultValue, RegexOptions.IgnoreCase, timeout);

            notifications.ProgressChanged(Strings.DownloadingServerSettingsProgessMessage);

            ServerProperty[] properties;
            if (!this.host.SonarQubeService.TryGetProperties(this.ConnectedServer, token, out properties) || token.IsCancellationRequested)
            {
                AbortWorkflow(controller, token);
                return;
            }

            var testProjRegexProperty = properties.FirstOrDefault(x => StringComparer.Ordinal.Equals(x.Key, ServerProperty.TestProjectRegexKey));

            // Using this older API, if the property hasn't been explicitly set no default value is returned.
            // http://jira.sonarsource.com/browse/SONAR-5891
            var testProjRegexPattern = testProjRegexProperty?.Value ?? ServerProperty.TestProjectRegexDefaultValue;

            Regex regex = null;

            if (testProjRegexPattern != null)
            {
                // Try and create regex from provided server pattern.
                // No way to determine a valid pattern other than attempting to construct
                // the Regex object.
                try
                {
                    regex = new Regex(testProjRegexPattern, RegexOptions.IgnoreCase, timeout);
                }
                catch (ArgumentException)
                {
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.InvalidTestProjectRegexPattern, testProjRegexPattern);
                }
            }

            var projectFilter = this.host.GetService <IProjectSystemFilter>();

            projectFilter.AssertLocalServiceIsNotNull();
            projectFilter.SetTestRegex(regex ?? defaultRegex);
        }
        public IProgressStepOperation CreateStepOperation(IProgressController controller, IProgressStepDefinition definition)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            ProgressStepDefinition supportedDefinition = definition as ProgressStepDefinition;

            if (supportedDefinition == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ProgressResources.UnsupportedTypeException, definition.GetType().FullName, typeof(ProgressStepDefinition).FullName));
            }

            ProgressControllerStep step = new ProgressControllerStep(controller, supportedDefinition);

            return(step);
        }
        internal /*for testing purposes*/ void DiscoverProjects(IProgressController controller, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(ThreadHelper.CheckAccess(), "Expected step to be run on the UI thread");

            notifications.ProgressChanged(Strings.DiscoveringSolutionProjectsProgressMessage);

            var patternFilteredProjects          = this.projectSystem.GetFilteredSolutionProjects();
            var pluginAndPatternFilteredProjects =
                patternFilteredProjects.Where(p => this.host.SupportedPluginLanguages.Contains(Language.ForProject(p)));

            this.BindingProjects.UnionWith(pluginAndPatternFilteredProjects);
            this.InformAboutFilteredOutProjects();

            if (!this.BindingProjects.Any())
            {
                AbortWorkflow(controller, CancellationToken.None);
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Will use the specified <paramref name="host"/> to visualize the progress of <paramref name="controller"/>
        /// </summary>
        public static ProgressObserver Observe(IProgressController controller, IProgressControlHost host)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            Debug.Assert(ThreadHelper.CheckAccess(), "Expected to be called on the UI thread");

            ProgressControl visualizer = VisualizeInHost(host);

            return(Observe(controller, visualizer));
        }
Esempio n. 33
0
        public static ProgressObserver StartObserving(IProgressController controller, IProgressVisualizer visualizer, ProgressControllerViewModel state)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (visualizer == null)
            {
                throw new ArgumentNullException(nameof(visualizer));
            }

            CheckSupportedController(controller);
            ProgressObserver observer = CreateAndConfigureInstance((IServiceProvider)controller, visualizer, controller.Events, new RelayCommand((s) => controller.TryAbort()), state);

            Debug.Assert(observer != null, "Failed to create observer on the UI thread");

            return(observer);
        }
        internal /*for testing purposes*/ async Task DownloadServiceParametersAsync(IProgressController controller,
                                                                                    IProgressStepExecutionEvents notifications, CancellationToken token)
        {
            Debug.Assert(this.ConnectedServer != null);

            notifications.ProgressChanged(Strings.DownloadingServerSettingsProgessMessage);

            var properties = await this.host.SonarQubeService.GetAllPropertiesAsync(this.host.VisualStateManager.BoundProjectKey, token);

            if (token.IsCancellationRequested)
            {
                AbortWorkflow(controller, token);
                return;
            }

            var testProjRegexPattern = properties.FirstOrDefault(IsTestProjectPatternProperty)?.Value;

            testProjectRegexSetter.SetTestRegex(testProjRegexPattern);
        }
Esempio n. 35
0
        private bool LoadRawText()
        {
            SourceType = SourceType.stText;

            try
            {
                using (StreamReader strd = new StreamReader(fFileName, Encoding.GetEncoding(1251)))
                {
                    IProgressController progress = AppHost.Progress;
                    try
                    {
                        progress.ProgressInit(fLangMan.LS(ILS.LSID_Loading), (int)strd.BaseStream.Length);

                        int lineNum = 0;
                        while (strd.Peek() != -1)
                        {
                            string txt = strd.ReadLine().Trim();

                            if (!string.IsNullOrEmpty(txt))
                            {
                                fRawContents.AddObject(txt, new RawLine(lineNum));
                            }

                            progress.ProgressStep((int)strd.BaseStream.Position);
                            lineNum++;
                        }
                        fRawContents.AddObject("", new RawLine(lineNum));
                    }
                    finally
                    {
                        progress.ProgressDone();
                    }
                }

                return(AnalyseRaw());
            }
            catch (Exception ex)
            {
                fLog.Add(">>>> " + fLangMan.LS(ILS.LSID_DataLoadError));
                Logger.LogWrite("Importer.LoadRawText(): " + ex.Message);
                return(false);
            }
        }
        internal /*for testing purposes*/ void PromptSaveSolutionIfDirty(IProgressController controller, CancellationToken token)
        {
            if (!VsShellUtils.SaveSolution(this.host, silent: false))
            {
                VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SolutionSaveCancelledBindAborted);

                this.AbortWorkflow(controller, token);
            }
        }
        private ProgressStepDefinition[] CreateWorkflowSteps(IProgressController controller)
        {
            StepAttributes IndeterminateNonCancellableUIStep = StepAttributes.Indeterminate | StepAttributes.NonCancellable;
            StepAttributes HiddenIndeterminateNonImpactingNonCancellableUIStep = IndeterminateNonCancellableUIStep | StepAttributes.Hidden | StepAttributes.NoProgressImpact;
            StepAttributes HiddenNonImpactingBackgroundStep = StepAttributes.BackgroundThread | StepAttributes.Hidden | StepAttributes.NoProgressImpact;

            return new ProgressStepDefinition[]
            {
                new ProgressStepDefinition(null, HiddenNonImpactingBackgroundStep,
                        (token, notifications) => notifications.ProgressChanged(Strings.StartedSolutionBindingWorkflow)),

                new ProgressStepDefinition(null, StepAttributes.Indeterminate | StepAttributes.Hidden,
                        (token, notifications) => this.PromptSaveSolutionIfDirty(controller, token)),

                new ProgressStepDefinition(Strings.BindingProjectsDisplayMessage, StepAttributes.Indeterminate,
                        (token, notifications) => this.DiscoverProjects(controller, notifications)),

                new ProgressStepDefinition(Strings.BindingProjectsDisplayMessage, StepAttributes.BackgroundThread,
                        (token, notifications) => this.DownloadQualityProfile(controller, token, notifications, this.GetBindingLanguages())),

                new ProgressStepDefinition(null, HiddenIndeterminateNonImpactingNonCancellableUIStep,
                        (token, notifications) => { NuGetHelper.LoadService(this.host); /*The service needs to be loaded on UI thread*/ }),

                new ProgressStepDefinition(Strings.BindingProjectsDisplayMessage, StepAttributes.BackgroundThread,
                        (token, notifications) => this.InstallPackages(controller, token, notifications)),

                new ProgressStepDefinition(Strings.BindingProjectsDisplayMessage, IndeterminateNonCancellableUIStep,
                        (token, notifications) => this.InitializeSolutionBindingOnUIThread(notifications)),

                new ProgressStepDefinition(Strings.BindingProjectsDisplayMessage, StepAttributes.BackgroundThread | StepAttributes.Indeterminate,
                        (token, notifications) => this.PrepareSolutionBinding(token)),

                new ProgressStepDefinition(null, StepAttributes.Hidden | StepAttributes.Indeterminate,
                        (token, notifications) => this.FinishSolutionBindingOnUIThread(controller, token)),

                new ProgressStepDefinition(null, HiddenIndeterminateNonImpactingNonCancellableUIStep,
                        (token, notifications) => this.SilentSaveSolutionIfDirty()),

                new ProgressStepDefinition(null, HiddenNonImpactingBackgroundStep,
                        (token, notifications) => this.EmitBindingCompleteMessage(notifications))
            };
        }
        internal /*for testing purposes*/ void DownloadQualityProfile(IProgressController controller, CancellationToken cancellationToken, IProgressStepExecutionEvents notificationEvents, IEnumerable<Language> languages)
        {
            Debug.Assert(controller != null);
            Debug.Assert(notificationEvents != null);

            bool failed = false;
            var rulesets = new Dictionary<Language, RuleSet>();
            var languageList = languages as IList<Language> ?? languages.ToList();
            DeterminateStepProgressNotifier notifier = new DeterminateStepProgressNotifier(notificationEvents, languageList.Count);

            notifier.NotifyCurrentProgress(Strings.DownloadingQualityProfileProgressMessage);
            foreach (var language in languageList)
            {
                QualityProfile qualityProfileInfo;
                if (!host.SonarQubeService.TryGetQualityProfile(this.connectionInformation, this.project, language, cancellationToken, out qualityProfileInfo))
                {
                    failed = true;
                    InformAboutQualityProfileToDownload(qualityProfileInfo.Name, qualityProfileInfo.Key, language.Name, true);
                    break;
                }
                this.QualityProfiles[language] = qualityProfileInfo;

                RoslynExportProfile export;
                if (!this.host.SonarQubeService.TryGetExportProfile(this.connectionInformation, qualityProfileInfo, language, cancellationToken, out export))
                {
                    failed = true;
                    InformAboutQualityProfileToDownload(qualityProfileInfo.Name, qualityProfileInfo.Key, language.Name, true);
                    break;
                }
                this.NuGetPackages.Add(language, export.Deployment.NuGetPackages);

                var tempRuleSetFilePath = Path.GetTempFileName();
                File.WriteAllText(tempRuleSetFilePath, export.Configuration.RuleSet.OuterXml);
                RuleSet ruleSet = RuleSet.LoadFromFile(tempRuleSetFilePath);

                // Remove/Move/Refactor code when XML ruleset file is no longer downloaded but the proper API is used to retrieve rules
                UpdateDownloadedSonarQubeQualityProfile(ruleSet, qualityProfileInfo);

                rulesets[language] = ruleSet;
                notifier.NotifyIncrementedProgress(string.Empty);
                if (rulesets[language] == null)
                {
                    failed = true;
                    InformAboutQualityProfileToDownload(qualityProfileInfo.Name, qualityProfileInfo.Key, language.Name, true);
                    break;
                }

                InformAboutQualityProfileToDownload(qualityProfileInfo.Name, qualityProfileInfo.Key, language.Name, false);
            }

            if (failed)
            {
                this.AbortWorkflow(controller, cancellationToken);
            }
            else
            {
                // Set the rule set which should be available for the following steps
                foreach (var keyValue in rulesets)
                {
                    this.Rulesets[keyValue.Key] = keyValue.Value;
                }
            }
        }
 private static void AbortWorkflow(IProgressController controller, CancellationToken token)
 {
     bool aborted = controller.TryAbort();
     Debug.Assert(aborted || token.IsCancellationRequested, "Failed to abort the workflow");
 }
        public static ProgressObserver StartObserving(IProgressController controller, IProgressVisualizer visualizer, ProgressControllerViewModel state)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (visualizer == null)
            {
                throw new ArgumentNullException(nameof(visualizer));
            }

            CheckSupportedController(controller);
            ProgressObserver observer = CreateAndConfigureInstance((IServiceProvider)controller, visualizer, controller.Events, new RelayCommand((s) => controller.TryAbort()), state);

            Debug.Assert(observer != null, "Failed to create observer on the UI thread");

            return observer;
        }
 IProgressStepOperation IProgressStepFactory.CreateStepOperation(IProgressController controller, IProgressStepDefinition definition)
 {
     return this.CreatedOperations[definition] = this.CreateOpeartion(definition);
 }
        internal /*for testing purposes*/ void DiscoverProjects(IProgressController controller, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(ThreadHelper.CheckAccess(), "Expected step to be run on the UI thread");

            notifications.ProgressChanged(Strings.DiscoveringSolutionProjectsProgressMessage, double.NaN);

            this.BindingProjects.UnionWith(this.projectSystem.GetFilteredSolutionProjects());

            this.InformAboutFilteredOutProjects(this.projectSystem.GetSolutionProjects().Except(this.BindingProjects));

            if (!this.BindingProjects.Any())
            {
                VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.NoProjectsApplicableForBinding);
                AbortWorkflow(controller, CancellationToken.None);
            }
        }
        internal /*for testing purposes*/ void DiscoverProjects(IProgressController controller, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(ThreadHelper.CheckAccess(), "Expected step to be run on the UI thread");

            notifications.ProgressChanged(Strings.DiscoveringSolutionProjectsProgressMessage);

            this.BindingProjects.UnionWith(this.projectSystem.GetFilteredSolutionProjects());

            this.InformAboutFilteredOutProjects();

            if (!this.BindingProjects.Any())
            {
                AbortWorkflow(controller, CancellationToken.None);
            }
        }
Esempio n. 44
0
        internal Main(IApplicationController applicationController)
        {
            this.applicationController = applicationController;

            applicationController.RunStarted += (s, e) => SyncContext.Post(cb => 
            {
                // enable/disable buttons
                startButton.Enabled = startTestsToolStripMenuItem.Enabled = false;
                startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = false;
                stopButton.Enabled = stopTestsToolStripMenuItem.Enabled = true;
            }, null);

            applicationController.RunFinished += (s, e) => SyncContext.Post(cb => 
            {
                // enable/disable buttons & menu items appropriately
                stopButton.Enabled = stopTestsToolStripMenuItem.Enabled = false;
                startButton.Enabled = startTestsToolStripMenuItem.Enabled = true;
                startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = true;
            }, null);

            applicationController.ExploreFinished += (sender, e) => SyncContext.Post(cb => 
            {
                startButton.Enabled = startTestsToolStripMenuItem.Enabled = true;
                startTestsWithDebuggerButton.Enabled = startWithDebuggerToolStripMenuItem.Enabled = true;
            }, null);

            applicationController.TestsFailed += (s, e) => SyncContext.Post(cb => Activate(), null);

            taskManager = RuntimeAccessor.ServiceLocator.Resolve<ITaskManager>();
            optionsController = RuntimeAccessor.ServiceLocator.Resolve<IOptionsController>();
            reportController = RuntimeAccessor.ServiceLocator.Resolve<IReportController>();

            testTreeModel = RuntimeAccessor.ServiceLocator.Resolve<ITestTreeModel>();
            testStatistics = RuntimeAccessor.ServiceLocator.Resolve<ITestStatistics>();

            commandFactory = RuntimeAccessor.ServiceLocator.Resolve<ICommandFactory>();
            testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve<ITestFrameworkManager>();
            windowManager = RuntimeAccessor.ServiceLocator.Resolve<IWindowManager>();    

            // moved this below the service locator calls as the optionsController was being used _before_ it was initialised :(
            // TODO: remove as many dependencies from the shell as possible
            InitializeComponent();

            SetupReportMenus();

            SetupRecentProjects();

            applicationController.PropertyChanged += (sender, e) => 
            {
                switch (e.PropertyName)
                {
                    case "ProjectFileName":
                        Text = applicationController.Title;
                        break;

                    case "RecentProjects":
                        SetupRecentProjects();
                        break;
                }
            };

            progressController = RuntimeAccessor.ServiceLocator.Resolve<IProgressController>();
            progressController.Status.PropertyChanged += (s, e) =>
            {
                toolStripStatusLabel.Text = progressController.Status;
            };
            progressController.TotalWork.PropertyChanged += (s, e) =>
            {
                toolStripProgressBar.TotalWork = progressController.TotalWork;
            };
            progressController.CompletedWork.PropertyChanged += (s, e) =>
            {
                toolStripProgressBar.CompletedWork = progressController.CompletedWork;
            };
            progressController.DisplayProgressDialog += (s, e) => SyncContext.Post(cb => 
                new ProgressMonitorDialog(e.ProgressMonitor).Show(this), null);
        }
 private static ProgressObserver CreateObserver(IProgressController controller, IProgressVisualizer visualizer, ProgressControllerViewModel state)
 {
     return ProgressObserver.StartObserving(controller, visualizer, state);
 }
        private void FinishSolutionBindingOnUIThread(IProgressController controller, CancellationToken token)
        {
            Debug.Assert(System.Windows.Application.Current?.Dispatcher.CheckAccess() ?? false, "Expected to run on UI thread");

            if (!this.solutionBindingOperation.CommitSolutionBinding())
            {
                AbortWorkflow(controller, token);
            }
        }
 private static ProgressObserver Observe(IProgressController controller, IProgressVisualizer visualizer)
 {
     ProgressObserver observer = CreateObserver(controller, visualizer, null);
     observedControllersMap.Add(controller, observer);
     return observer;
 }
        internal /*for testing purposes*/ void DownloadQualityProfile(IProgressController controller, CancellationToken cancellationToken, IProgressStepExecutionEvents notificationEvents, IEnumerable<Language> languages)
        {
            Debug.Assert(controller != null);
            Debug.Assert(notificationEvents != null);

            bool failed = false;
            var rulesets = new Dictionary<Language, RuleSet>();
            DeterminateStepProgressNotifier notifier = new DeterminateStepProgressNotifier(notificationEvents, languages.Count());

            foreach (var language in languages)
            {
                notifier.NotifyCurrentProgress(string.Format(CultureInfo.CurrentCulture, Strings.DownloadingQualityProfileProgressMessage, language.Name));

                QualityProfile qualityProfileInfo;
                if (!host.SonarQubeService.TryGetQualityProfile(this.connectionInformation, this.project, language, cancellationToken, out qualityProfileInfo))
                {
                    failed = true;
                    break;
                }
                this.QualityProfiles[language] = qualityProfileInfo;

                RoslynExportProfile export;
                if (!this.host.SonarQubeService.TryGetExportProfile(this.connectionInformation, qualityProfileInfo, language, cancellationToken, out export))
                {
                    failed = true;
                    break;
                }

                this.NuGetPackages.AddRange(export.Deployment.NuGetPackages);

                var tempRuleSetFilePath = Path.GetTempFileName();
                File.WriteAllText(tempRuleSetFilePath, export.Configuration.RuleSet.OuterXml);
                RuleSet ruleSet = RuleSet.LoadFromFile(tempRuleSetFilePath);

                rulesets[language] = ruleSet;
                notifier.NotifyIncrementedProgress(string.Empty);
                if (rulesets[language] == null)
                {
                    failed = true;
                    break;
                }
            }

            if (failed)
            {
                VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.QualityProfileDownloadFailedMessage);
                this.AbortWorkflow(controller, cancellationToken);
            }
            else
            {
                // Set the rule set which should be available for the following steps
                foreach (var keyValue in rulesets)
                {
                    this.Rulesets[keyValue.Key] = keyValue.Value;
                }

                notifier.NotifyCurrentProgress(Strings.QualityProfileDownloadedSuccessfulMessage);
            }
        }
 public static ProgressObserver StartObserving(IProgressController controller)
 {
     return StartObserving(controller, new WpfWindowProgressVisualizer());
 }
        /// <summary>
        /// Will install the NuGet packages for the current managed projects.
        /// The packages that will be installed will be based on the information from <see cref="Analyzer.GetRequiredNuGetPackages"/>
        /// and is specific to the <see cref="RuleSet"/>.
        /// </summary>
        internal /*for testing purposes*/ void InstallPackages(IProgressController controller, CancellationToken token, IProgressStepExecutionEvents notificationEvents)
        {
            if (!this.NuGetPackages.Any())
            {
                return;
            }

            Debug.Assert(this.NuGetPackages.Count == this.NuGetPackages.Distinct().Count(), "Duplicate NuGet packages specified");

            if (!this.BindingProjects.Any())
            {
                Debug.Fail("Not expected to be called when there are no projects");
                return;
            }

            DeterminateStepProgressNotifier progressNotifier = new DeterminateStepProgressNotifier(notificationEvents, this.BindingProjects.Count * this.NuGetPackages.Count);
            foreach (var bindingProject in this.BindingProjects)
            {
                List<NuGetPackageInfo> nugetPackages;
                if (!this.NuGetPackages.TryGetValue(Language.ForProject(bindingProject), out nugetPackages))
                {
                    var message = string.Format(Strings.BindingProjectLanguageNotMatchingAnyQualityProfileLanguage, bindingProject.Name);
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);
                    continue;
                }

                foreach (var packageInfo in nugetPackages)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    string message = string.Format(CultureInfo.CurrentCulture, Strings.EnsuringNugetPackagesProgressMessage, packageInfo.Id, bindingProject.Name);
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);

                    var isNugetInstallSuccessful = NuGetHelper.TryInstallPackage(this.host, bindingProject, packageInfo.Id, packageInfo.Version);

                    if (isNugetInstallSuccessful) // NuGetHelper.TryInstallPackage already displayed the error message so only take care of the success message
                    {
                        message = string.Format(CultureInfo.CurrentCulture, Strings.SuccessfullyInstalledNugetPackageForProject, packageInfo.Id, bindingProject.Name);
                        VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, message);
                    }

                    // TODO: SVS-33 (https://jira.sonarsource.com/browse/SVS-33) Trigger a Team Explorer warning notification to investigate the partial binding in the output window.
                    this.AllNuGetPackagesInstalled &= isNugetInstallSuccessful;

                    progressNotifier.NotifyIncrementedProgress(string.Empty);
                }
            }
        }
 public static ProgressObserver StartObserving(IProgressController controller, IProgressVisualizer visualizer)
 {
     return StartObserving(controller, visualizer, null);
 }
        internal /*for testing purposes*/ void DownloadServiceParameters(IProgressController controller, CancellationToken token, IProgressStepExecutionEvents notifications)
        {
            Debug.Assert(this.ConnectedServer != null);

            // Should never realistically take more than 1 second to match against a project name
            var timeout = TimeSpan.FromSeconds(1);
            var defaultRegex = new Regex(ServerProperty.TestProjectRegexDefaultValue, RegexOptions.IgnoreCase, timeout);

            notifications.ProgressChanged(Strings.DownloadingServerSettingsProgessMessage);

            ServerProperty[] properties;
            if (!this.host.SonarQubeService.TryGetProperties(this.ConnectedServer, token, out properties) || token.IsCancellationRequested)
            {
                AbortWorkflow(controller, token);
                return;
            }

            var testProjRegexProperty = properties.FirstOrDefault(x => StringComparer.Ordinal.Equals(x.Key, ServerProperty.TestProjectRegexKey));

            // Using this older API, if the property hasn't been explicitly set no default value is returned.
            // http://jira.sonarsource.com/browse/SONAR-5891
            var testProjRegexPattern = testProjRegexProperty?.Value ?? ServerProperty.TestProjectRegexDefaultValue;

            Regex regex = null;
            if (testProjRegexPattern != null)
            {
                // Try and create regex from provided server pattern.
                // No way to determine a valid pattern other than attempting to construct
                // the Regex object.
                try
                {
                    regex = new Regex(testProjRegexPattern, RegexOptions.IgnoreCase, timeout);
                }
                catch (ArgumentException)
                {
                    VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.InvalidTestProjectRegexPattern, testProjRegexPattern);
                }
            }

            var projectFilter = this.host.GetService<IProjectSystemFilter>();
            projectFilter.AssertLocalServiceIsNotNull();
            projectFilter.SetTestRegex(regex ?? defaultRegex);
        }
 /// <summary>
 /// Checks if the <see cref="IProgressController"/> meets the requirements to be observable by this class
 /// </summary>
 /// <param name="progressController">An instance of <see cref="IProgressController"/> to check</param>
 private static void CheckSupportedController(IProgressController progressController)
 {
     if (progressController.Events == null || progressController.Events.Steps == null)
     {
         throw new InvalidOperationException(ProgressObserverResources.UnsupportedProgressControllerException);
     }
 }
        private bool VerifyDotNetPlugins(IProgressController controller, CancellationToken cancellationToken, ConnectionInformation connection, IProgressStepExecutionEvents notifications)
        {
            notifications.ProgressChanged(Strings.DetectingServerPlugins);

            ServerPlugin[] plugins;
            if (!this.host.SonarQubeService.TryGetPlugins(connection, cancellationToken, out plugins))
            {
                notifications.ProgressChanged(cancellationToken.IsCancellationRequested ? Strings.ConnectionResultCancellation : Strings.ConnectionResultFailure);
                this.host.ActiveSection?.UserNotifications?.ShowNotificationError(Strings.ConnectionFailed, NotificationIds.FailedToConnectId, this.parentCommand);

                AbortWorkflow(controller, cancellationToken);
                return false;
            }

            IsCSharpPluginSupported = VerifyPluginSupport(plugins, MinimumSupportedServerPlugin.CSharp);
            IsVBNetPluginSupported = VerifyPluginSupport(plugins, MinimumSupportedServerPlugin.VbNet);

            var projects = this.projectSystem.GetSolutionProjects().ToList();
            var anyCSharpProject = projects.Any(p => MinimumSupportedServerPlugin.CSharp.ISupported(p));
            var anyVbNetProject = projects.Any(p => MinimumSupportedServerPlugin.VbNet.ISupported(p));

            string errorMessage;
            if ((IsCSharpPluginSupported && anyCSharpProject) ||
                (IsVBNetPluginSupported && anyVbNetProject))
            {
                return true;
            }
            else if (!IsCSharpPluginSupported && !IsVBNetPluginSupported)
            {
                errorMessage = Strings.ServerHasNoSupportedPluginVersion;
            }
            else if (projects.Count == 0)
            {
                errorMessage = Strings.SolutionContainsNoSupportedProject;
            }
            else if (IsCSharpPluginSupported && !anyCSharpProject)
            {
                errorMessage = string.Format(Strings.OnlySupportedPluginHasNoProjectInSolution, Language.CSharp.Name);
            }
            else
            {
                errorMessage = string.Format(Strings.OnlySupportedPluginHasNoProjectInSolution, Language.VBNET.Name);
            }

            this.host.ActiveSection?.UserNotifications?.ShowNotificationError(errorMessage, NotificationIds.BadServerPluginId, null);
            VsShellUtils.WriteToSonarLintOutputPane(this.host, Strings.SubTextPaddingFormat, errorMessage);
            notifications.ProgressChanged(Strings.ConnectionResultFailure);

            AbortWorkflow(controller, cancellationToken);
            return false;
        }
        internal /* for testing purposes */ void ConnectionStep(IProgressController controller, CancellationToken cancellationToken, ConnectionInformation connection, IProgressStepExecutionEvents notifications)
        {
            this.host.ActiveSection?.UserNotifications?.HideNotification(NotificationIds.FailedToConnectId);
            this.host.ActiveSection?.UserNotifications?.HideNotification(NotificationIds.BadServerPluginId);

            notifications.ProgressChanged(connection.ServerUri.ToString());

            if (!this.VerifyDotNetPlugins(controller, cancellationToken, connection, notifications))
            {
                return;
            }

            this.ConnectedServer = connection;

            ProjectInformation[] projects;
            if (!this.host.SonarQubeService.TryGetProjects(connection, cancellationToken, out projects))
            {
                notifications.ProgressChanged(cancellationToken.IsCancellationRequested ? Strings.ConnectionResultCancellation : Strings.ConnectionResultFailure);
                this.host.ActiveSection?.UserNotifications?.ShowNotificationError(Strings.ConnectionFailed, NotificationIds.FailedToConnectId, this.parentCommand);

                AbortWorkflow(controller, cancellationToken);
                return;
            }

            this.OnProjectsChanged(connection, projects);
            notifications.ProgressChanged(Strings.ConnectionResultSuccess);
        }
        private bool VerifyCSharpPlugin(IProgressController controller, CancellationToken cancellationToken, ConnectionInformation connection, IProgressStepExecutionEvents notifications)
        {
            ServerPlugin[] plugins;
            if (!this.host.SonarQubeService.TryGetPlugins(connection, cancellationToken, out plugins))
            {
                notifications.ProgressChanged(cancellationToken.IsCancellationRequested ? Strings.ConnectionResultCancellation : Strings.ConnectionResultFailure, double.NaN);
                this.host.ActiveSection?.UserNotifications?.ShowNotificationError(Strings.ConnectionFailed, NotificationIds.FailedToConnectId, this.parentCommand);

                AbortWorkflow(controller, cancellationToken);
                return false;
            }

            var csPlugin = plugins.FirstOrDefault(x => StringComparer.Ordinal.Equals(x.Key, ServerPlugin.CSharpPluginKey));
            if (string.IsNullOrWhiteSpace(csPlugin?.Version) || VersionHelper.Compare(csPlugin.Version, ServerPlugin.CSharpPluginMinimumVersion) < 0)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, Strings.ServerDoesNotHaveCorrectVersionOfCSharpPlugin, ServerPlugin.CSharpPluginMinimumVersion);

                this.host.ActiveSection?.UserNotifications?.ShowNotificationError(errorMessage, NotificationIds.BadServerPluginId, null);
                notifications.ProgressChanged(errorMessage, double.NaN);
                notifications.ProgressChanged(Strings.ConnectionResultFailure, double.NaN);

                AbortWorkflow(controller, cancellationToken);
                return false;
            }

            return true;
        }
        /// <summary>
        /// Will use the specified <paramref name="host"/> to visualize the progress of <paramref name="controller"/>
        /// </summary>
        public static ProgressObserver Observe(IProgressController controller, IProgressControlHost host)
        {
            if (controller == null)
            {
                throw new ArgumentNullException(nameof(controller));
            }

            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            Debug.Assert(ThreadHelper.CheckAccess(), "Expected to be called on the UI thread");

            ProgressControl visualizer = VisualizeInHost(host);
            return Observe(controller, visualizer);
        }
        /// <summary>
        /// Will install the NuGet packages for the current managed projects.
        /// The packages that will be installed will be based on the information from <see cref="Analyzer.GetRequiredNuGetPackages"/> 
        /// and is specific to the <see cref="RuleSet"/>.
        /// </summary>
        internal /*for testing purposes*/ void InstallPackages(IProgressController controller, CancellationToken token, IProgressStepExecutionEvents notificationEvents)
        {
            if (!this.NuGetPackages.Any())
            {
                return;
            }

            Debug.Assert(this.NuGetPackages.Count == this.NuGetPackages.Distinct().Count(), "Duplicate NuGet packages specified");

            if (!this.BindingProjects.Any())
            {
                Debug.Fail("Not expected to be called when there are no projects");
                return;
            }

            DeterminateStepProgressNotifier progressNotifier = new DeterminateStepProgressNotifier(notificationEvents, this.BindingProjects.Count * this.NuGetPackages.Count);
            foreach (var project in this.BindingProjects)
            {
                foreach (var packageInfo in this.NuGetPackages)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    string message = string.Format(CultureInfo.CurrentCulture, Strings.EnsuringNugetPackagesProgressMessage, packageInfo.Id, project.Name);
                    progressNotifier.NotifyCurrentProgress(message);

                    // TODO: SVS-33 (https://jira.sonarsource.com/browse/SVS-33) Trigger a Team Explorer warning notification to investigate the partial binding in the output window.
                    this.AllNuGetPackagesInstalled &= NuGetHelper.TryInstallPackage(this.host, project, packageInfo.Id, packageInfo.Version);

                    progressNotifier.NotifyIncrementedProgress(string.Empty);
                }
            }
        }