protected override void CallBack(object sender, EventArgs e)
        {
            var messageBoxResult = MessageBoxDisplay.Show(new MessageBoxDisplay.MessageBoxArgs
            {
                Message = Resources.WarnOnCodeCleanUp,
                Caption = Resources.WarningCaptionCleanup,
                Button  = MessageBoxButtons.OKCancel,
                Icon    = MessageBoxIcon.Warning
            });

            if (messageBoxResult != DialogResult.OK)
            {
                return;
            }

            var dialogResult = CleanupOptionForm.Instance.ShowDialog();

            if (dialogResult == DialogResult.Cancel)
            {
                return;
            }

            ActionsOnCSharp.CSharpActionDelegate.TargetAction desiredAction = ActionsOnCSharp.ActionsCSharpOnFile.DoCleanup;

            if (CleanupOptionForm.Instance.SelectedTypes != null)
            {
                ActionsOnCSharp.ActionCSharpOnAnyWhere.Invoke(desiredAction, CleanupOptionForm.Instance.SelectedTypes);
                GeeksProductivityToolsPackage.Instance.SaveSolutionChanges();
            }
        }
Пример #2
0
        protected override void Callback(object sender, EventArgs e)
        {
            var messageBoxResult = MessageBoxDisplay.Show(new MessageBoxDisplay.MessageBoxArgs
            {
                Message = Resources.WarnOnCodeCleanUp,
                Caption = Resources.WarningCaptionCleanup,
                Button  = MessageBoxButtons.OKCancel,
                Icon    = MessageBoxIcon.Warning
            });

            if (messageBoxResult != DialogResult.OK)
            {
                return;
            }

            CSharpAction.TargetAction desiredAction = ActionsCSharpOnFile.DoCleanup;
            var commandGuid = (sender as OleMenuCommand).CommandID.Guid;

            if (commandGuid == GuidList.GuidCleanupCmdSet)
            {
                ActionCSharpOnAnywhere.Invoke(desiredAction,
                                              new VSIX.TidyCSharp.Cleanup.CommandsHandlers.CleanupOptions
                {
                    //ActionTypes = new[] { CleanerType }
                }
                                              );

                TidyCSharpPackage.Instance.SaveSolutionChanges();
            }
            else
            {
                return;
            }
        }
Пример #3
0
        private void InitializeViewElements()
        {
            // File Menu
            FileMenu            = new PopupMenuElement(fileToolStripMenuItem);
            NewProjectCommand   = new CommandMenuElement(newProjectToolStripMenuItem);
            OpenProjectCommand  = new CommandMenuElement(openProjectToolStripMenuItem);
            CloseCommand        = new CommandMenuElement(closeToolStripMenuItem);
            AddTestFilesCommand = new CommandMenuElement(addTestFilesToolStripMenuItem);
            SaveCommand         = new CommandMenuElement(saveToolStripMenuItem);
            SaveAsCommand       = new CommandMenuElement(saveAsToolStripMenuItem);
            SaveResultsCommand  = new CommandMenuElement(saveResultsToolStripMenuItem);
            ReloadTestsCommand  = new CommandMenuElement(reloadTestsToolStripMenuItem);
            SelectRuntimeMenu   = new PopupMenuElement(selectRuntimeToolStripMenuItem);
            RunAsX86            = new CheckedMenuElement(loadAsX86ToolStripMenuItem);
            RecentProjectsMenu  = new PopupMenuElement(recentProjectsToolStripMenuItem);
            ExitCommand         = new CommandMenuElement(exitToolStripMenuItem);

            // View Menu
            FullGuiCommand      = new CommandMenuElement(fullGuiToolStripMenuItem);
            MiniGuiCommand      = new CommandMenuElement(miniGuiToolStripMenuItem);
            IncreaseFontCommand = new CommandMenuElement(increaseToolStripMenuItem);
            DecreaseFontCommand = new CommandMenuElement(decreaseToolStripMenuItem);
            ChangeFontCommand   = new CommandMenuElement(changeToolStripMenuItem);
            RestoreFontCommand  = new CommandMenuElement(restoreToolStripMenuItem);
            StatusBarCommand    = new CheckedMenuElement(statusBarToolStripMenuItem);

            // Project Menu
            ProjectMenu = new PopupMenuElement(projectToolStripMenuItem);

            // Tools Menu
            SettingsCommand   = new CommandMenuElement(settingsToolStripMenuItem);
            ExtensionsCommand = new CommandMenuElement(extensionsToolStripMenuItem);

            // Help Menu
            NUnitHelpCommand  = new CommandMenuElement(nUnitHelpToolStripMenuItem);
            AboutNUnitCommand = new CommandMenuElement(aboutNUnitToolStripMenuItem);

            TestResult = new ControlElement(testResult);
            TestName   = new ControlElement(testName);

            DialogManager        = new DialogManager();
            MessageDisplay       = new MessageBoxDisplay();
            LongRunningOperation = new LongRunningOperationDisplay(this);
        }
        private void WireUpEvents()
        {
            #region Model Events

            _model.Events.TestsLoading += (TestFilesLoadingEventArgs e) =>
            {
                UpdateViewCommands(testLoading: true);

                var message = e.TestFilesLoading.Count == 1 ?
                              $"Loading Assembly: {e.TestFilesLoading[0]}" :
                              $"Loading {e.TestFilesLoading.Count} Assemblies...";

                BeginLongRunningOperation(message);
            };

            _model.Events.TestLoaded += (TestNodeEventArgs e) =>
            {
                OnLongRunningOperationComplete();

                UpdateViewCommands();
                _view.StopRunButton.Visible   = true;
                _view.ForceStopButton.Visible = false;

                _lastFilesLoaded = _model.TestFiles.ToArray();
                if (_lastFilesLoaded.Length == 1)
                {
                    _view.SetTitleBar(_lastFilesLoaded.First());
                }
            };

            _model.Events.TestsUnloading += (TestEventArgse) =>
            {
                UpdateViewCommands();
                _view.StopRunButton.Visible   = true;
                _view.ForceStopButton.Visible = false;

                BeginLongRunningOperation("Unloading...");
            };

            _model.Events.TestUnloaded += (TestEventArgs e) =>
            {
                OnLongRunningOperationComplete();

                UpdateViewCommands();
                _view.StopRunButton.Visible   = true;
                _view.ForceStopButton.Visible = false;
            };

            _model.Events.TestsReloading += (TestEventArgs e) =>
            {
                UpdateViewCommands();

                BeginLongRunningOperation("Reloading...");
            };

            _model.Events.TestReloaded += (TestNodeEventArgs e) =>
            {
                OnLongRunningOperationComplete();

                UpdateViewCommands();
                _view.StopRunButton.Visible   = true;
                _view.ForceStopButton.Visible = false;
            };

            _model.Events.TestLoadFailure += (TestLoadFailureEventArgs e) =>
            {
                OnLongRunningOperationComplete();

                // HACK: Engine should recognize .NET Standard and give the
                // appropriate error message. For now, we compensate for its
                // failure by issuing the message ourselves and reloading the
                // previously loaded  test.
                var  msg = e.Exception.Message;
                bool isNetStandardError =
                    e.Exception.Message == "Unrecognized Target Framework Identifier: .NETStandard";

                if (!isNetStandardError)
                {
                    _view.MessageDisplay.Error(e.Exception.Message);
                    return;
                }

                _view.MessageDisplay.Error("Test assemblies must target a specific platform, rather than .NETStandard.");
                if (_lastFilesLoaded == null)
                {
                    _view.Close();
                }
                else
                {
                    _model.UnloadTests();
                    _model.LoadTests(_lastFilesLoaded);
                }
            };

            _model.Events.RunStarting += (RunStartingEventArgs e) =>
            {
                UpdateViewCommands();
                _view.StopRunButton.Visible    = true;
                _view.ForceStopButton.Visible  = false;
                _view.RunSummaryButton.Visible = false;
            };

            _model.Events.RunFinished += (TestResultEventArgs e) => OnRunFinished(e.Result);

            // Separate internal method for testing
            void OnRunFinished(ResultNode result)
            {
                OnLongRunningOperationComplete();

                UpdateViewCommands();

                // Reset these in case run was cancelled
                _view.StopRunMenuCommand.Visible   = true;
                _view.ForceStopMenuCommand.Visible = false;
                _view.StopRunButton.Visible        = true;
                _view.ForceStopButton.Visible      = false;
                _view.RunSummaryButton.Visible     = true;

                //string resultPath = Path.Combine(TestProject.BasePath, "TestResult.xml");
                // TODO: Use Work Directory
                string resultPath = "TestResult.xml";

                _model.SaveResults(resultPath);
                //try
                //{
                //    _model.SaveResults(resultPath);
                //    //log.Debug("Saved result to {0}", resultPath);
                //}
                //catch (Exception ex)
                //{
                //    //log.Warning("Unable to save result to {0}\n{1}", resultPath, ex.ToString());
                //}

                //if (e.Result.Outcome.Status == TestStatus.Failed)
                //    _view.Activate();

                // If we were running unattended, it's time to close
                if (_options.Unattended)
                {
                    _view.Close();
                }
                else
                {
                    DisplayTestRunSummary(result, true);
                }
            };

            _settings.Changed += (s, e) =>
            {
                switch (e.SettingName)
                {
                case "TestCentric.Gui.GuiLayout":
                    // Settings have changed (from settings dialog)
                    // so we want to update the GUI to match.
                    var newLayout = _settings.Gui.GuiLayout;
                    var oldLayout = _view.GuiLayout.SelectedItem;
                    // Make sure it hasn't already been changed
                    if (oldLayout != newLayout)
                    {
                        // Save position of form for old layout
                        SaveFormLocationAndSize(oldLayout);
                        // Update the GUI itself
                        SetGuiLayout(newLayout);
                        _view.GuiLayout.SelectedItem = newLayout;
                    }
                    break;

                case "TestCentric.Gui.MainForm.ShowStatusBar":
                    _view.StatusBarView.Visible = _settings.Gui.MainForm.ShowStatusBar;
                    break;
                }
            };

            _model.Events.UnhandledException += (UnhandledExceptionEventArgs e) =>
            {
                MessageBoxDisplay.Error($"{e.Message}\n\n{e.StackTrace}", "TestCentric - Internal Error");
            };

            #endregion

            #region View Events

            _view.Load += (s, e) =>
            {
                var guiLayout = _settings.Gui.GuiLayout;
                _view.GuiLayout.SelectedItem = guiLayout;
                SetGuiLayout(guiLayout);

                var settings = _model.PackageOverrides;
                if (_options.MaxAgents >= 0)
                {
                    _model.Settings.Engine.Agents = _options.MaxAgents;
                }
                _view.RunAsX86.Checked = _options.RunAsX86;
            };

            _view.Shown += (s, e) =>
            {
                Application.DoEvents();

                // Load test specified on command line or
                // the most recent one if options call for it
                if (_options.InputFiles.Count != 0)
                {
                    LoadTests(_options.InputFiles);
                }
                else if (_settings.Gui.LoadLastProject && !_options.NoLoad)
                {
                    foreach (string entry in _recentFiles.Entries)
                    {
                        if (entry != null && File.Exists(entry))
                        {
                            LoadTests(entry);
                            break;
                        }
                    }
                }

                //if ( guiOptions.include != null || guiOptions.exclude != null)
                //{
                //    testTree.ClearSelectedCategories();
                //    bool exclude = guiOptions.include == null;
                //    string[] categories = exclude
                //        ? guiOptions.exclude.Split(',')
                //        : guiOptions.include.Split(',');
                //    if ( categories.Length > 0 )
                //        testTree.SelectCategories( categories, exclude );
                //}

                // Run loaded test automatically if called for
                if (_model.IsPackageLoaded && _options.RunAllTests)
                {
                    RunAllTests();
                }
                // Currently, --unattended without --run does nothing except exit.
                else if (_options.Unattended)
                {
                    _view.Close();
                }
            };

            _view.SplitterPositionChanged += (s, e) =>
            {
                _settings.Gui.MainForm.SplitPosition = _view.SplitterPosition;
            };

            _view.FormClosing += (s, e) =>
            {
                if (_model.IsPackageLoaded)
                {
                    if (_model.IsTestRunning)
                    {
                        if (!_view.MessageDisplay.YesNo("A test is running, do you want to forcibly stop the test and exit?"))
                        {
                            e.Cancel = true;
                            return;
                        }

                        _model.StopTestRun(true);
                    }

                    if (CloseProject() == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                    }
                }

                if (!e.Cancel)
                {
                    SaveFormLocationAndSize(_settings.Gui.GuiLayout);
                }
            };

            _view.FileMenu.Popup += () =>
            {
                bool isPackageLoaded = _model.IsPackageLoaded;
                bool isTestRunning   = _model.IsTestRunning;

                _view.OpenCommand.Enabled  = !isTestRunning;
                _view.CloseCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.ReloadTestsCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.SelectAgentMenu.Enabled = _agentSelectionController.AllowAgentSelection();

                _view.RunAsX86.Enabled = isPackageLoaded && !isTestRunning;

                _view.RecentFilesMenu.Enabled = !isTestRunning;

                //if (!isTestRunning)
                //{
                //    _recentProjectsMenuHandler.Load();
                //}
            };

            _view.OpenCommand.Execute         += () => OpenProject();
            _view.CloseCommand.Execute        += () => CloseProject();
            _view.AddTestFilesCommand.Execute += () => AddTestFiles();
            _view.ReloadTestsCommand.Execute  += () => ReloadTests();

            _view.SelectAgentMenu.Popup += () =>
            {
                _agentSelectionController.PopulateMenu();
            };

            _view.RunAsX86.CheckedChanged += () =>
            {
                var key = EnginePackageSettings.RunAsX86;
                if (_view.RunAsX86.Checked)
                {
                    ChangePackageSettingAndReload(key, true);
                }
                else
                {
                    ChangePackageSettingAndReload(key, null);
                }
            };

            _view.RecentFilesMenu.Popup += () =>
            {
                var menuItems = _view.RecentFilesMenu.MenuItems;
                // Test for null, in case we are running tests with a mock
                if (menuItems == null)
                {
                    return;
                }

                menuItems.Clear();
                int num = 0;
                foreach (string entry in _model.RecentFiles.Entries)
                {
                    var menuText = string.Format("{0} {1}", ++num, entry);
                    var menuItem = new ToolStripMenuItem(menuText);
                    menuItem.Click += (sender, ea) =>
                    {
                        // HACK: We are loading new files, cancel any runtime override
                        _model.PackageOverrides.Remove(EnginePackageSettings.RequestedRuntimeFramework);
                        string path = ((ToolStripMenuItem)sender).Text.Substring(2);
                        _model.LoadTests(new[] { path });
                    };
                    menuItems.Add(menuItem);
                    if (num >= _settings.Gui.RecentProjects.MaxFiles)
                    {
                        break;
                    }
                }
            };

            _view.ExitCommand.Execute += () => _view.Close();

            _view.GuiLayout.SelectionChanged += () =>
            {
                // Selection menu item has changed, so we want
                // to update both the display and the settings
                var oldLayout = _settings.Gui.GuiLayout;
                var newLayout = _view.GuiLayout.SelectedItem;
                if (oldLayout != newLayout)
                {
                    SaveFormLocationAndSize(oldLayout);
                    SetGuiLayout(newLayout);
                }
                _settings.Gui.GuiLayout = _view.GuiLayout.SelectedItem;
            };

            _view.IncreaseFontCommand.Execute += () =>
            {
                applyFont(IncreaseFont(_settings.Gui.Font));
            };

            _view.DecreaseFontCommand.Execute += () =>
            {
                applyFont(DecreaseFont(_settings.Gui.Font));
            };

            _view.ChangeFontCommand.Execute += () =>
            {
                Font currentFont = _settings.Gui.Font;
                Font newFont     = _view.DialogManager.SelectFont(currentFont);
                if (newFont != _settings.Gui.Font)
                {
                    applyFont(newFont);
                }
            };

            _view.DialogManager.ApplyFont += (font) => applyFont(font);

            _view.RestoreFontCommand.Execute += () =>
            {
                applyFont(Form.DefaultFont);
            };

            _view.IncreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = IncreaseFont(_settings.Gui.FixedFont);
            };

            _view.DecreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = DecreaseFont(_settings.Gui.FixedFont);
            };

            _view.RestoreFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = new Font(FontFamily.GenericMonospace, 8.0f);
            };

            _view.RunAllMenuCommand.Execute      += () => RunAllTests();
            _view.RunSelectedMenuCommand.Execute += () => RunSelectedTests();
            _view.RunFailedMenuCommand.Execute   += () => RunFailedTests();

            _view.RunAllToolbarCommand.Execute      += () => RunAllTests();
            _view.RunSelectedToolbarCommand.Execute += () => RunSelectedTests();
            _view.RunButton.Execute += () =>
            {
                // Necessary test because we don't disable the button click
                if (_model.HasTests && !_model.IsTestRunning)
                {
                    RunAllTests();
                }
                // TODO: This should actually run the last Run action selected in the dropdown
            };

            _view.DebugAllToolbarCommand.Execute      += () => _model.DebugAllTests();
            _view.DebugSelectedToolbarCommand.Execute += () => _model.DebugSelectedTests();
            _view.DebugButton.Execute += () =>
            {
                // Necessary test because we don't disable the button click
                if (_model.HasTests && !_model.IsTestRunning)
                {
                    _model.DebugAllTests();
                }
                // TODO: This should actually run the last Run action selected in the dropdown
            };

            _view.DisplayFormat.SelectionChanged += () =>
            {
                SetTreeDisplayFormat(_view.DisplayFormat.SelectedItem);
            };

            _view.GroupBy.SelectionChanged += () =>
            {
                switch (_view.DisplayFormat.SelectedItem)
                {
                case "TEST_LIST":
                    _settings.Gui.TestTree.TestList.GroupBy = _view.GroupBy.SelectedItem;
                    break;

                case "FIXTURE_LIST":
                    _settings.Gui.TestTree.FixtureList.GroupBy = _view.GroupBy.SelectedItem;
                    break;
                }
            };

            _view.StopRunMenuCommand.Execute += ExecuteNormalStop;
            _view.StopRunButton.Execute      += ExecuteNormalStop;

            _view.ForceStopMenuCommand.Execute += ExecuteForcedStop;
            _view.ForceStopButton.Execute      += ExecuteForcedStop;

            _view.TestParametersMenuCommand.Execute    += DisplayTestParametersDialog;
            _view.TestParametersToolbarCommand.Execute += DisplayTestParametersDialog;

            _view.RunSummaryButton.Execute += () =>
            {
                var result = _model.GetResultForTest(_model.Tests.Id);
                DisplayTestRunSummary(result, false);
            };

            //_view.RunSummaryButton.CheckedChanged += () =>
            //{
            //    if (_view.RunSummaryButton.Checked)
            //    {
            //        var resultId = _model.GetResultForTest(_model.Tests.Id);
            //        var summary = ResultSummaryCreator.FromResultNode(resultId);
            //        string report = ResultSummaryReporter.WriteSummaryReport(summary);
            //        _view.DisplayTestRunSummary(report);
            //    }
            //    else
            //        _view.HideTestRunSummary();
            //};

            _view.ToolsMenu.Popup += () =>
            {
                _view.SaveResultsAsMenu.MenuItems.Clear();

                foreach (string format in _resultFormats)
                {
                    var formatItem = new ToolStripMenuItem(format);
                    formatItem.Click += (s, e) => SaveResults(format);
                    _view.SaveResultsAsMenu.MenuItems.Add(formatItem);
                }
            };

            _view.SaveResultsCommand.Execute += () => SaveResults();

            _view.OpenWorkDirectoryCommand.Execute += () => System.Diagnostics.Process.Start(_model.WorkDirectory);

            _view.ExtensionsCommand.Execute += () =>
            {
                using (var extensionsDialog = new ExtensionDialog(_model.Services.ExtensionService))
                {
                    extensionsDialog.Font = _settings.Gui.Font;
                    extensionsDialog.ShowDialog();
                }
            };

            _view.SettingsCommand.Execute += () =>
            {
                SettingsDialog.Display(this, _model);
            };

            _view.TestCentricHelpCommand.Execute += () =>
            {
                System.Diagnostics.Process.Start("https://test-centric.org/testcentric-gui");
            };

            _view.NUnitHelpCommand.Execute += () =>
            {
                System.Diagnostics.Process.Start("https://docs.nunit.org/articles/nunit/intro.html");
            };

            _view.AboutCommand.Execute += () =>
            {
                using (AboutBox aboutBox = new AboutBox())
                {
                    aboutBox.ShowDialog();
                }
            };

            _view.ResultTabs.SelectionChanged += () =>
            {
                _settings.Gui.SelectedTab = _view.ResultTabs.SelectedIndex;
            };

            #endregion
        }
Пример #5
0
        private void WireUpEvents()
        {
            _model.Events.TestsLoading += (e) => _view.RunCommand.Enabled = false;

            _model.Events.TestLoaded += (e) =>
            {
                _view.RunCommand.Enabled = true;
                _view.CheckPropertiesDialog();

                LoadTests(GetTopDisplayNode(e.Test));

                if (_model.Settings.Gui.TestTree.SaveVisualState)
                {
                    string fileName = VisualState.GetVisualStateFileName(_model.TestFiles[0]);
                    if (File.Exists(fileName) && new FileInfo(fileName).Length > 0)
                    {
                        try
                        {
                            var visualState = VisualState.LoadFrom(fileName);
                            visualState.RestoreVisualState(_view, _treeMap);
                            _model.SelectCategories(visualState.SelectedCategories, visualState.ExcludeCategories);
                        }
                        catch (Exception ex)
                        {
                            MessageBoxDisplay.Error(
                                $"Unable to load visual state from {fileName}{Environment.NewLine}{ex.Message}");
                        }
                    }
                }
            };

            VisualState reloadState = null;

            _model.Events.TestsReloading += (e) =>
            {
                reloadState = VisualState.LoadFrom(_view);

                _view.RunCommand.Enabled = false;
            };

            _model.Events.TestReloaded += (e) =>
            {
                ReloadTests(GetTopDisplayNode(e.Test));

                if (reloadState != null)
                {
                    reloadState.RestoreVisualState(_view, _treeMap);
                }

                if (!_settings.Gui.ClearResultsOnReload)
                {
                    RestoreResults(e.Test);
                }

                if (!_treeFilter.IsEmpty)
                {
                    _view.Accept(new TestFilterVisitor(_treeFilter));
                }

                _view.RunCommand.Enabled = true;
            };

            _model.Events.TestChanged += (e) =>
            {
                if (_settings.Engine.ReloadOnChange)
                {
                    _model.ReloadTests();
                }
            };

            _model.Events.TestsUnloading += (e) =>
            {
                _view.RunCommand.Enabled = false;

                _view.ClosePropertiesDialog();

                if (_settings.Gui.TestTree.SaveVisualState)
                {
                    try
                    {
                        var visualState = VisualState.LoadFrom(_view);
                        visualState.SelectedCategories = _model.SelectedCategories;
                        visualState.ExcludeCategories  = _model.ExcludeSelectedCategories;
                        visualState.Save(VisualState.GetVisualStateFileName(_model.TestFiles[0]));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Unable to save visual state.");
                        Debug.WriteLine(ex);
                    }
                }

                _view.Clear();
                _treeMap.Clear();
            };

            _model.Events.TestUnloaded += (e) => _view.RunCommand.Enabled = false;

            _model.Events.RunStarting += (e) =>
            {
                foreach (var node in _view.Tree.Nodes)
                {
                    ((TestSuiteTreeNode)node).ClearResults();
                }
                _view.RunCommand.Enabled = false;
                _view.CheckPropertiesDialog();
            };

            _model.Events.RunFinished += (e) => _view.RunCommand.Enabled = true;

            _model.Events.TestFinished += (e) => SetTestResult(e.Result);

            _model.Events.SuiteFinished += (e) => SetTestResult(e.Result);

            _model.Events.CategorySelectionChanged += (TestEventArgs e) =>
            {
                TestNodeFilter filter = TestNodeFilter.Empty;

                if (_model.SelectedCategories.Count > 0)
                {
                    filter = new CategoryFilter(_model.SelectedCategories);
                    if (_model.ExcludeSelectedCategories)
                    {
                        filter = new NotFilter(filter);
                    }
                }

                _view.Accept(new TestFilterVisitor(_treeFilter = filter));
            };

            _settings.Changed += (s, e) =>
            {
                if (e.SettingName == "Gui.TestTree.AlternateImageSet")
                {
                    _view.AlternateImageSet = _settings.Gui.TestTree.AlternateImageSet;
                }
                else if (e.SettingName == "Gui.TestTree.ShowCheckBoxes")
                {
                    var showCheckBoxes = _settings.Gui.TestTree.ShowCheckBoxes;

                    // When turning off checkboxes with a non-empty tree, the
                    // structure of what is expanded and collapsed is lost.
                    // We save that structure as a VisualState and then restore it.
                    VisualState visualState = !showCheckBoxes && _view.Tree.TopNode != null
                        ? VisualState.LoadFrom(_view)
                        : null;

                    _view.CheckBoxes = showCheckBoxes;

                    if (visualState != null)
                    {
                        visualState.ShowCheckBoxes = showCheckBoxes;
                        visualState.RestoreVisualState(_view, _treeMap);
                    }
                }
            };

            _view.FileDrop += _model.LoadTests;

            _view.RunCommand.Execute += () =>
            {
                if (_settings.Engine.ReloadOnRun)
                {
                    _model.ClearResults();
                    _model.ReloadTests();
                }

                if (_view.ContextNode != null)
                {
                    _model.RunTests(_view.ContextNode.Test);
                }
                else
                {
                    _model.RunTests(new TestSelection(_view.SelectedTests));
                }
            };

            _view.Tree.ContextMenuStrip.Opened += (s, e) => InitializeContextMenu();

            _view.ShowCheckBoxes.CheckedChanged += () => _view.CheckBoxes = _view.ShowCheckBoxes.Checked;

            _view.ClearAllCheckBoxes.Execute += () =>
            {
                foreach (TreeNode node in _view.Tree.Nodes)
                {
                    ClearAllCheckBoxes(node);
                }
            };

            _view.CheckFailedTests.Execute += () =>
            {
                foreach (TreeNode node in _view.Tree.Nodes)
                {
                    CheckFailedTests(node);
                }
            };

            _view.ShowFailedAssumptions.CheckedChanged += () =>
            {
                TestSuiteTreeNode targetNode = _view.ContextNode ?? (TestSuiteTreeNode)_view.Tree.SelectedNode;
                TestSuiteTreeNode theoryNode = targetNode?.GetTheoryNode();
                if (theoryNode != null)
                {
                    theoryNode.ShowFailedAssumptions = _view.ShowFailedAssumptions.Checked;
                }
            };

            _view.EditProject.Execute += () =>
            {
                TestSuiteTreeNode targetNode  = _view.ContextNode ?? (TestSuiteTreeNode)_view.Tree.SelectedNode;
                string            projectPath = targetNode.TestPackage.FullName;
                EditProject(projectPath);
            };

            _view.ExpandAllCommand.Execute += () => _view.Tree.ExpandAll();

            _view.CollapseAllCommand.Execute += () => _view.Tree.CollapseAll();

            _view.HideTestsCommand.Execute += () => HideTestsUnderNode(_model.Tests);

            _view.PropertiesCommand.Execute += () =>
            {
                TestSuiteTreeNode targetNode = _view.ContextNode ?? (TestSuiteTreeNode)_view.Tree.SelectedNode;
                if (targetNode != null)
                {
                    _view.ShowPropertiesDialog(targetNode);
                }
            };
        }
Пример #6
0
        private void WireUpEvents()
        {
            #region Model Events

            _model.Events.TestsLoading += (TestFilesLoadingEventArgs e) =>
            {
                UpdateViewCommands(testLoading: true);

                var message = e.TestFilesLoading.Count == 1 ?
                              $"Loading Assembly: {e.TestFilesLoading[0]}" :
                              $"Loading {e.TestFilesLoading.Count} Assemblies...";

                _view.LongRunningOperation.Display(message);
            };

            _model.Events.TestLoaded += (TestNodeEventArgs e) =>
            {
                _view.LongRunningOperation.Hide();

                UpdateViewCommands();

                var files = _model.TestFiles;
                if (files.Count == 1)
                {
                    _view.SetTitleBar(files.First());
                }
            };

            _model.Events.TestsUnloading += (TestEventArgse) =>
            {
                UpdateViewCommands();
            };

            _model.Events.TestUnloaded += (TestEventArgs e) =>
            {
                _view.RunSummary.Text = null;

                UpdateViewCommands();
            };

            _model.Events.TestsReloading += (TestEventArgs e) =>
            {
                UpdateViewCommands();

                _view.LongRunningOperation.Display("Reloading...");
            };

            _model.Events.TestReloaded += (TestNodeEventArgs e) =>
            {
                _view.LongRunningOperation.Hide();

                if (_settings.Gui.ClearResultsOnReload)
                {
                    _view.RunSummary.Text = null;
                }

                UpdateViewCommands();
            };

            _model.Events.TestLoadFailure += (TestLoadFailureEventArgs e) =>
            {
                _view.LongRunningOperation.Hide();

                _view.MessageDisplay.Error(e.Exception.Message);
            };

            _model.Events.RunStarting += (RunStartingEventArgs e) =>
            {
                UpdateViewCommands();

                _view.RunSummary.Text = null;
            };

            _model.Events.RunFinished += (TestResultEventArgs e) =>
            {
                _view.LongRunningOperation.Hide();

                UpdateViewCommands();

                ResultSummary summary = ResultSummaryCreator.FromResultNode(e.Result);
                _view.RunSummary.Text = string.Format(
                    "Passed: {0}   Failed: {1}   Errors: {2}   Inconclusive: {3}   Invalid: {4}   Ignored: {5}   Skipped: {6}   Time: {7}",
                    summary.PassCount, summary.FailedCount, summary.ErrorCount, summary.InconclusiveCount, summary.InvalidCount, summary.IgnoreCount, summary.SkipCount, summary.Duration);

                if (summary.RunCount == 0)
                {
                }

                //string resultPath = Path.Combine(TestProject.BasePath, "TestResult.xml");
                // TODO: Use Work Directory
                string resultPath = "TestResult.xml";
                _model.SaveResults(resultPath);
                //try
                //{
                //    _model.SaveResults(resultPath);
                //    //log.Debug("Saved result to {0}", resultPath);
                //}
                //catch (Exception ex)
                //{
                //    //log.Warning("Unable to save result to {0}\n{1}", resultPath, ex.ToString());
                //}

                //if (e.Result.Outcome.Status == TestStatus.Failed)
                //    _view.Activate();

                // If we were running unattended, it's time to close
                if (_options.Unattended)
                {
                    _view.Close();
                }
            };

            _settings.Changed += (s, e) =>
            {
                if (e.SettingName == "Gui.Options.DisplayFormat")
                {
                    InitializeDisplay();
                }
            };

            _model.Events.UnhandledException += (UnhandledExceptionEventArgs e) =>
            {
                MessageBoxDisplay.Error($"{e.Message}\n\n{e.StackTrace}", "TestCentric - Internal Error");
            };

            #endregion

            #region View Events

            _view.Load += (s, e) =>
            {
                InitializeDisplay(_settings.Gui.DisplayFormat);

                var settings = _model.PackageOverrides;
                if (_options.MaxAgents >= 0)
                {
                    _model.Settings.Engine.Agents = _options.MaxAgents;
                }
                _view.RunAsX86.Checked = _options.RunAsX86;
            };

            _view.Shown += (s, e) =>
            {
                Application.DoEvents();

                // Load test specified on command line or
                // the most recent one if options call for it
                if (_options.InputFiles.Count != 0)
                {
                    LoadTests(_options.InputFiles);
                }
                else if (_settings.Gui.LoadLastProject && !_options.NoLoad)
                {
                    foreach (string entry in _recentFiles.Entries)
                    {
                        if (entry != null && File.Exists(entry))
                        {
                            LoadTests(entry);
                            break;
                        }
                    }
                }

                //if ( guiOptions.include != null || guiOptions.exclude != null)
                //{
                //    testTree.ClearSelectedCategories();
                //    bool exclude = guiOptions.include == null;
                //    string[] categories = exclude
                //        ? guiOptions.exclude.Split(',')
                //        : guiOptions.include.Split(',');
                //    if ( categories.Length > 0 )
                //        testTree.SelectCategories( categories, exclude );
                //}

                // Run loaded test automatically if called for
                if (_model.IsPackageLoaded && _options.RunAllTests)
                {
                    RunAllTests();
                }
                // Currently, --unattended without --run does nothing except exit.
                else if (_options.Unattended)
                {
                    _view.Close();
                }
            };

            _view.SplitterPositionChanged += (s, e) =>
            {
                _settings.Gui.MainForm.SplitPosition = _view.SplitterPosition;
            };

            _view.FormClosing += (s, e) =>
            {
                if (_model.IsPackageLoaded)
                {
                    if (_model.IsTestRunning)
                    {
                        if (!_view.MessageDisplay.YesNo("A test is running, do you want to forcibly stop the test and exit?"))
                        {
                            e.Cancel = true;
                            return;
                        }

                        _model.StopTestRun(true);
                    }

                    if (CloseProject() == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                    }
                }

                if (!e.Cancel)
                {
                    if (_settings.Gui.DisplayFormat == "Mini")
                    {
                        _settings.Gui.MiniForm.Location = _view.Location;
                        _settings.Gui.MiniForm.Size     = _view.Size;
                    }
                    else
                    {
                        _settings.Gui.MainForm.Location = _view.Location;
                        _settings.Gui.MainForm.Size     = _view.Size;
                    }
                }
            };

            _view.RunButton.Execute       += () => RunSelectedTests();
            _view.StopButton.Execute      += () => StopTests();
            _view.ForceStopButton.Execute += () => ForceStop();

            _view.FileMenu.Popup += () =>
            {
                bool isPackageLoaded = _model.IsPackageLoaded;
                bool isTestRunning   = _model.IsTestRunning;

                _view.OpenCommand.Enabled  = !isTestRunning;
                _view.CloseCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.ReloadTestsCommand.Enabled = isPackageLoaded && !isTestRunning;

                _view.RuntimeMenu.Visible = _model.AvailableRuntimes.Count > 1;

                _view.RecentFilesMenu.Enabled = !isTestRunning;

                //if (!isTestRunning)
                //{
                //    _recentProjectsMenuHandler.Load();
                //}
            };

            _view.RuntimeMenu.Popup += () => _runtimeSelectionController.PopulateMenu();

            _view.OpenCommand.Execute         += () => OpenProject();
            _view.CloseCommand.Execute        += () => CloseProject();
            _view.AddTestFilesCommand.Execute += () => AddTestFiles();
            _view.ReloadTestsCommand.Execute  += () => ReloadTests();

            _view.RunAsX86.CheckedChanged += () =>
            {
                var key = EnginePackageSettings.RunAsX86;
                if (_view.RunAsX86.Checked)
                {
                    ChangePackageSettingAndReload(key, true);
                }
                else
                {
                    ChangePackageSettingAndReload(key, null);
                }
            };

            _view.RecentFilesMenu.Popup += () =>
            {
                var menuItems = _view.RecentFilesMenu.MenuItems;
                // Test for null, in case we are running tests with a mock
                if (menuItems == null)
                {
                    return;
                }

                menuItems.Clear();
                int num = 0;
                foreach (string entry in _model.RecentFiles.Entries)
                {
                    var menuText = string.Format("{0} {1}", ++num, entry);
                    var menuItem = new ToolStripMenuItem(menuText);
                    menuItem.Click += (sender, ea) =>
                    {
                        // HACK: We are loading new files, cancel any runtime override
                        _model.PackageOverrides.Remove(EnginePackageSettings.RequestedRuntimeFramework);
                        string path = ((ToolStripMenuItem)sender).Text.Substring(2);
                        _model.LoadTests(new[] { path });
                    };
                    menuItems.Add(menuItem);
                    if (num >= _settings.Gui.RecentProjects.MaxFiles)
                    {
                        break;
                    }
                }
            };

            _view.ExitCommand.Execute += () => _view.Close();

            _view.DisplayFormat.SelectionChanged += () =>
            {
                _settings.Gui.DisplayFormat = _view.DisplayFormat.SelectedItem;
                InitializeDisplay(_view.DisplayFormat.SelectedItem);
            };

            _view.IncreaseFontCommand.Execute += () =>
            {
                applyFont(IncreaseFont(_settings.Gui.Font));
            };

            _view.DecreaseFontCommand.Execute += () =>
            {
                applyFont(DecreaseFont(_settings.Gui.Font));
            };

            _view.ChangeFontCommand.Execute += () =>
            {
                Font currentFont = _settings.Gui.Font;
                Font newFont     = _view.DialogManager.SelectFont(currentFont);
                if (newFont != _settings.Gui.Font)
                {
                    applyFont(newFont);
                }
            };

            _view.DialogManager.ApplyFont += (font) => applyFont(font);

            _view.RestoreFontCommand.Execute += () =>
            {
                applyFont(Form.DefaultFont);
            };

            _view.IncreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = IncreaseFont(_settings.Gui.FixedFont);
            };

            _view.DecreaseFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = DecreaseFont(_settings.Gui.FixedFont);
            };

            _view.RestoreFixedFontCommand.Execute += () =>
            {
                _settings.Gui.FixedFont = new Font(FontFamily.GenericMonospace, 8.0f);
            };

            _view.StatusBarCommand.CheckedChanged += () =>
            {
                _view.StatusBarView.Visible = _view.StatusBarCommand.Checked;
            };

            _view.RunAllCommand.Execute      += () => RunAllTests();
            _view.RunSelectedCommand.Execute += () => RunSelectedTests();
            _view.RunFailedCommand.Execute   += () => RunFailedTests();

            _view.StopRunCommand.Execute   += () => StopTests();
            _view.ForceStopCommand.Execute += () => ForceStop();

            _view.TestParametersCommand.Execute += () =>
            {
                using (var dlg = new TestParametersDialog())
                {
                    dlg.Font          = _settings.Gui.Font;
                    dlg.StartPosition = FormStartPosition.CenterParent;

                    if (_model.PackageOverrides.ContainsKey("TestParametersDictionary"))
                    {
                        var testParms = _model.PackageOverrides["TestParametersDictionary"] as IDictionary <string, string>;
                        foreach (string key in testParms.Keys)
                        {
                            dlg.Parameters.Add(key, testParms[key]);
                        }
                    }

                    if (dlg.ShowDialog(_view as IWin32Window) == DialogResult.OK)
                    {
                        ChangePackageSettingAndReload("TestParametersDictionary", dlg.Parameters);
                    }
                }
            };

            _view.ToolsMenu.Popup += () =>
            {
                _view.SaveResultsAsMenu.MenuItems.Clear();

                foreach (string format in _resultFormats)
                {
                    var formatItem = new ToolStripMenuItem(format);
                    formatItem.Click += (s, e) => SaveResults(format);
                    _view.SaveResultsAsMenu.MenuItems.Add(formatItem);
                }
            };

            _view.SaveResultsCommand.Execute += () => SaveResults();

            _view.OpenWorkDirectoryCommand.Execute += () => System.Diagnostics.Process.Start(_model.WorkDirectory);

            _view.ExtensionsCommand.Execute += () =>
            {
                using (var extensionsDialog = new ExtensionDialog(_model.Services.ExtensionService))
                {
                    extensionsDialog.Font = _settings.Gui.Font;
                    extensionsDialog.ShowDialog();
                }
            };

            _view.SettingsCommand.Execute += () =>
            {
                SettingsDialog.Display(this, _model);
            };

            _view.TestCentricHelpCommand.Execute += () =>
            {
                System.Diagnostics.Process.Start("https://test-centric.org/testcentric-gui");
            };

            _view.NUnitHelpCommand.Execute += () =>
            {
                System.Diagnostics.Process.Start("https://docs.nunit.org/articles/nunit/intro.html");
            };

            _view.AboutCommand.Execute += () =>
            {
                using (AboutBox aboutBox = new AboutBox())
                {
                    aboutBox.ShowDialog();
                }
            };

            _view.ResultTabs.SelectionChanged += () =>
            {
                _settings.Gui.SelectedTab = _view.ResultTabs.SelectedIndex;
            };

            #endregion
        }