Пример #1
0
        private void LaunchWorkflow(RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name)
        {
            var workflowType = Web.Cache.WorkflowTypeCache.Read(connectionWorkflow.WorkflowTypeId.Value);

            if (workflowType != null && (workflowType.IsActive ?? true))
            {
                ConnectionRequestActivity connectionRequestActivity = null;
                if (ConnectionRequestActivityGuid.HasValue)
                {
                    connectionRequestActivity = new ConnectionRequestActivityService(rockContext).Get(ConnectionRequestActivityGuid.Value);
                    var workflow = Rock.Model.Workflow.Activate(workflowType, name);

                    List <string> workflowErrors;
                    new WorkflowService(rockContext).Process(workflow, connectionRequestActivity, out workflowErrors);
                    if (workflow.Id != 0)
                    {
                        ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                        connectionRequestWorkflow.ConnectionRequestId  = connectionRequestActivity.ConnectionRequestId;
                        connectionRequestWorkflow.WorkflowId           = workflow.Id;
                        connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                        connectionRequestWorkflow.TriggerType          = connectionWorkflow.TriggerType;
                        connectionRequestWorkflow.TriggerQualifier     = connectionWorkflow.QualifierValue;
                        new ConnectionRequestWorkflowService(rockContext).Add(connectionRequestWorkflow);
                        rockContext.SaveChanges();
                    }
                }
            }
        }
        public void ConnectionWorkflow_ConnectionStep_WhenMissingCSharpPluginAndVBNetPlugin_AbortsWorkflowAndDisconnects()
        {
            // Setup
            var connectionInfo             = new ConnectionInformation(new Uri("http://server"));
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, new RelayCommand(() => { }));
            var controller = new ConfigurableProgressController();

            this.sonarQubeService.AllowConnections         = true;
            this.sonarQubeService.ReturnProjectInformation = new ProjectInformation[0];
            this.sonarQubeService.ClearServerPlugins();
            this.host.SetActiveSection(ConfigurableSectionController.CreateDefault());
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)this.host.ActiveSection.UserNotifications;
            var executionEvents = new ConfigurableProgressStepExecutionEvents();

            // Act
            testSubject.ConnectionStep(controller, CancellationToken.None, connectionInfo, executionEvents);

            // Verify
            controller.AssertNumberOfAbortRequests(1);
            executionEvents.AssertProgressMessages(
                connectionInfo.ServerUri.ToString(),
                Strings.DetectingServerPlugins,
                Strings.ConnectionResultFailure);
            notifications.AssertNotification(NotificationIds.BadServerPluginId, Strings.ServerHasNoSupportedPluginVersion);
        }
Пример #3
0
        private void LaunchWorkflow(RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name, Message message)
        {
            var workflowType = WorkflowTypeCache.Get(connectionWorkflow.WorkflowTypeId.Value);

            if (workflowType != null && (workflowType.IsActive ?? true))
            {
                ConnectionRequest connectionRequest = null;
                if (message.ConnectionRequestGuid.HasValue)
                {
                    connectionRequest = new ConnectionRequestService(rockContext).Get(message.ConnectionRequestGuid.Value);

                    var workflow = Rock.Model.Workflow.Activate(workflowType, name);

                    workflow.InitiatorPersonAliasId = message.InitiatorPersonAliasId;

                    List <string> workflowErrors;
                    new WorkflowService(rockContext).Process(workflow, connectionRequest, out workflowErrors);
                    if (workflow.Id != 0)
                    {
                        ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                        connectionRequestWorkflow.ConnectionRequestId  = connectionRequest.Id;
                        connectionRequestWorkflow.WorkflowId           = workflow.Id;
                        connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                        connectionRequestWorkflow.TriggerType          = connectionWorkflow.TriggerType;
                        connectionRequestWorkflow.TriggerQualifier     = connectionWorkflow.QualifierValue;
                        new ConnectionRequestWorkflowService(rockContext).Add(connectionRequestWorkflow);
                        rockContext.SaveChanges();
                    }
                }
            }
        }
Пример #4
0
        public async Task ConnectionWorkflow_ConnectionStep_10KProjectsAndKeyIsNotPartOfIt()
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"), "user", "pass".ToSecureString());
            var projects       = Enumerable.Range(1, 10000)
                                 .Select(i => new SonarQubeProject($"project-{i}", $"Project {i}"))
                                 .ToList();

            this.sonarQubeServiceMock.Setup(x => x.ConnectAsync(connectionInfo, It.IsAny <CancellationToken>()))
            .Returns(Task.Delay(0));
            this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(projects);
            this.projectSystemHelper.Projects = new[] { new ProjectMock("tttt.csproj")
                                                        {
                                                            ProjectKind = ProjectSystemHelper.CSharpProjectKind
                                                        } };
            bool projectChangedCallbackCalled = false;

            const string boundProjectKey  = "whatever-key";
            const string boundProjectName = "whatever-name";

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                var expectedList = new List <SonarQubeProject>(projects);
                expectedList.Insert(0, new SonarQubeProject(boundProjectKey, boundProjectName));
                p.Should().BeEquivalentTo(expectedList);
            };
            this.host.VisualStateManager.BoundProjectKey  = boundProjectKey;
            this.host.VisualStateManager.BoundProjectName = boundProjectName;

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(0);
            AssertServiceDisconnectNotCalled();
            executionEvents.AssertProgressMessages(
                connectionMessage,
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingSonarQubePlugins,
                Strings.ConnectionStepRetrievingProjects,
                Strings.ConnectionResultSuccess);
            projectChangedCallbackCalled.Should().BeTrue("ConnectedProjectsCallaback was not called");
            this.sonarQubeServiceMock.Verify(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(),
                                                                 It.IsAny <CancellationToken>()), Times.Once());
            testSubject.ConnectedServer.Should().Be(connectionInfo);
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoShowErrorMessages();
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoNotification(NotificationIds.FailedToConnectId);

            AssertCredentialsStored(connectionInfo);

            this.outputWindowPane.AssertOutputStrings(4);
        }
Пример #5
0
        private void LaunchWorkflow(RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name)
        {
            var workflowTypeService = new WorkflowTypeService(rockContext);
            var workflowType        = workflowTypeService.Get(connectionWorkflow.WorkflowTypeId.Value);

            if (workflowType != null)
            {
                ConnectionRequest connectionRequest = null;
                if (ConnectionRequestGuid.HasValue)
                {
                    connectionRequest = new ConnectionRequestService(rockContext).Get(ConnectionRequestGuid.Value);

                    var workflow = Rock.Model.Workflow.Activate(workflowType, name);

                    List <string> workflowErrors;
                    new WorkflowService(rockContext).Process(workflow, connectionRequest, out workflowErrors);
                    if (workflow.Id != 0)
                    {
                        ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                        connectionRequestWorkflow.ConnectionRequestId  = connectionRequest.Id;
                        connectionRequestWorkflow.WorkflowId           = workflow.Id;
                        connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                        connectionRequestWorkflow.TriggerType          = connectionWorkflow.TriggerType;
                        connectionRequestWorkflow.TriggerQualifier     = connectionWorkflow.QualifierValue;
                        new ConnectionRequestWorkflowService(rockContext).Add(connectionRequestWorkflow);
                        rockContext.SaveChanges();
                    }
                }
            }
        }
Пример #6
0
        private bool QualifiersMatch(RockContext rockContext, ConnectionWorkflow workflowTrigger, int prevStatusId, int statusId)
        {
            var qualifierParts = (workflowTrigger.QualifierValue ?? "").Split(new char[] { '|' });

            bool matches = true;

            if (matches && qualifierParts.Length > 1 && !string.IsNullOrWhiteSpace(qualifierParts[1]))
            {
                var qualifierRoleId = qualifierParts[1].AsIntegerOrNull();
                if (qualifierRoleId.HasValue)
                {
                    matches = qualifierRoleId != 0 && qualifierRoleId == statusId;
                }
                else
                {
                    matches = false;
                }
            }

            if (matches && qualifierParts.Length > 3 && !string.IsNullOrWhiteSpace(qualifierParts[3]))
            {
                var qualifierRoleId = qualifierParts[3].AsIntegerOrNull();
                if (qualifierRoleId.HasValue)
                {
                    matches = qualifierRoleId != 0 && qualifierRoleId == prevStatusId;
                }
                else
                {
                    matches = false;
                }
            }

            return(matches);
        }
        public void ConnectionWorkflow_DownloadServiceParameters_InvalidRegex_UsesDefault()
        {
            // Setup
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            var badExpression      = "*-gf/d*-b/try\\*-/r-*yeb/\\";
            var expectedExpression = ServerProperty.TestProjectRegexDefaultValue;

            this.sonarQubeService.RegisterServerProperty(new ServerProperty
            {
                Key   = ServerProperty.TestProjectRegexKey,
                Value = badExpression
            });

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            // Act
            testSubject.DownloadServiceParameters(controller, CancellationToken.None, progressEvents);

            // Verify
            filter.AssertTestRegex(expectedExpression, RegexOptions.IgnoreCase);
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
            this.outputWindowPane.AssertOutputStrings(string.Format(CultureInfo.CurrentCulture, Strings.InvalidTestProjectRegexPattern, badExpression));
        }
        public async Task ConnectionWorkflow_ConnectionStep_Credentials_Invalid()
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"), "user", "pass".ToSecureString());

            this.sonarQubeServiceMock.Setup(x => x.ConnectAsync(connectionInfo, It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(1);
            AssertServiceDisconnectCalled();
            executionEvents.AssertProgressMessages(
                connectionMessage,
                Strings.ConnectionStepValidatinCredentials,
                Strings.ConnectionResultFailure);

            this.sonarQubeServiceMock.Verify(
                x => x.ConnectAsync(It.IsAny <ConnectionInformation>(), It.IsAny <CancellationToken>()),
                Times.Once());

            testSubject.ConnectedServer.Should().Be(null);

            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoShowErrorMessages();
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNotification(NotificationIds.FailedToConnectId);

            AssertCredentialsNotStored(); // Connection was rejected by SonarQube
        }
        public async Task ConnectionWorkflow_ConnectionStep_WhenMissingCSharpPluginAndVBNetPlugin_AbortsWorkflowAndDisconnects()
        {
            // Arrange
            var connectionInfo             = new ConnectionInformation(new Uri("http://server"));
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, new RelayCommand(() => { }));
            var controller = new ConfigurableProgressController();

            this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <SonarQubeProject>());
            this.sonarQubeServiceMock.Setup(x => x.GetAllPluginsAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <SonarQubePlugin>());
            this.host.SetActiveSection(ConfigurableSectionController.CreateDefault());
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)this.host.ActiveSection.UserNotifications;
            var executionEvents = new ConfigurableProgressStepExecutionEvents();

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(1);
            AssertServiceDisconnectCalled();
            executionEvents.AssertProgressMessages(
                connectionInfo.ServerUri.ToString(),
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingSonarQubePlugins,
                Strings.ConnectionResultFailure);
            notifications.AssertNotification(NotificationIds.BadSonarQubePluginId, Strings.ServerHasNoSupportedPluginVersion);

            AssertCredentialsNotStored(); // Username and password are null
        }
        public void ConnectionWorkflow_ConnectionStep_WhenGivenANullParentCommand_ThrowsArgumentNullException()
        {
            // Arrange & Act
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, null);

            // Assert
            FluentAssertions.Execution.Execute.Assertion.FailWith("Expected exception of type ArgumentNullException but no exception was thrown.");
        }
        private ConnectionWorkflow SetTestSubjectWithConnectedServer()
        {
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            var connectionInfo             = new ConnectionInformation(new Uri("http://server"));

            testSubject.ConnectedServer = connectionInfo;
            return(testSubject);
        }
        public void ConnectionWorkflow_ConnectionStep_WhenGivenANullHost_ThrowsArgumentNullException()
        {
            // Arrange & Act
            ConnectionWorkflow testSubject = new ConnectionWorkflow(null, new RelayCommand(() => { }));

            // Assert
            FluentAssertions.Execution.Execute.Assertion.FailWith("Expected exception of type ArgumentNullException but no exception was thrown.");
        }
        public void ConnectionWorkflow_ConnectionStep_ConnectedServerCanBeGetAndSet()
        {
            // Arrange
            var connectionInfo             = new ConnectionInformation(new Uri("http://server"));
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, new RelayCommand(() => { }));

            // Act
            testSubject.ConnectedServer = connectionInfo;

            // Assert
            connectionInfo.Should().Be(testSubject.ConnectedServer);
        }
        private async Task ConnectionWorkflow_ConnectionStep_WhenXPluginAndAnyXProject_SuccessfulConnection(string projectName, string projectKind)
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"), "user", "pass".ToSecureString());
            var projects       = new List <SonarQubeProject> {
                new SonarQubeProject("project1", "")
            };

            this.sonarQubeServiceMock.Setup(x => x.ConnectAsync(connectionInfo, It.IsAny <CancellationToken>()))
            .Returns(Task.Delay(0));
            this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(projects);
            this.projectSystemHelper.Projects = new[] { new ProjectMock(projectName)
                                                        {
                                                            ProjectKind = projectKind
                                                        } };
            bool projectChangedCallbackCalled = false;

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                CollectionAssert.AreEqual(projects, p.ToArray(), "Unexpected projects");
            };

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(0);
            AssertServiceDisconnectNotCalled();
            executionEvents.AssertProgressMessages(
                connectionMessage,
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingSonarQubePlugins,
                Strings.ConnectionStepRetrievingProjects,
                Strings.ConnectionResultSuccess);
            projectChangedCallbackCalled.Should().BeTrue("ConnectedProjectsCallaback was not called");
            this.sonarQubeServiceMock.Verify(x => x.ConnectAsync(It.IsAny <ConnectionInformation>(),
                                                                 It.IsAny <CancellationToken>()), Times.Once());
            testSubject.ConnectedServer.Should().Be(connectionInfo);
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoShowErrorMessages();
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoNotification(NotificationIds.FailedToConnectId);

            AssertCredentialsStored(connectionInfo);
        }
Пример #15
0
        private async Task ConnectionWorkflow_ConnectionStep_WhenXPluginAndNoXProject_AbortsWorkflowAndDisconnects(string projectName, string projectKind,
                                                                                                                   params MinimumSupportedSonarQubePlugin[] minimumSupportedSonarQubePlugins)
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"));
            var projects       = new List <SonarQubeProject> {
                new SonarQubeProject("project1", "")
            };

            this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(projects);
            this.sonarQubeServiceMock.Setup(x => x.GetAllPluginsAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(minimumSupportedSonarQubePlugins.Select(p => new SonarQubePlugin(p.Key, p.MinimumVersion)).ToList());
            this.projectSystemHelper.Projects = new[] { new ProjectMock(projectName)
                                                        {
                                                            ProjectKind = projectKind
                                                        } };
            bool projectChangedCallbackCalled = false;

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                CollectionAssert.AreEqual(projects, p.ToArray(), "Unexpected projects");
            };

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)this.host.ActiveSection.UserNotifications;

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(1);
            AssertServiceDisconnectCalled();
            executionEvents.AssertProgressMessages(
                connectionInfo.ServerUri.ToString(),
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingSonarQubePlugins,
                Strings.ConnectionResultFailure);
            projectChangedCallbackCalled.Should().BeFalse("ConnectedProjectsCallaback was called");

            var languageList = string.Join(", ", minimumSupportedSonarQubePlugins.SelectMany(x => x.Languages.Select(l => l.Name)));

            notifications.AssertNotification(NotificationIds.BadSonarQubePluginId, string.Format(Strings.OnlySupportedPluginsHaveNoProjectInSolution, languageList));

            AssertCredentialsNotStored(); // Username and password are null
        }
        public void IsSonarQubePluginSupported_WhenUnsupportedVersionOfVSAndCSharpPluginEquals60_ReturnsTrue()
        {
            // Arrange
            VisualStudioHelpers.VisualStudioVersion = "14.0";
            var testSubject     = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            var sonarqubePlugin = new SonarQubePlugin("csharp", "6.0");

            // Act
            var result = testSubject.IsSonarQubePluginSupported(new[] { sonarqubePlugin }, MinimumSupportedSonarQubePlugin.CSharp);

            // Assert
            result.Should().BeTrue();
            this.outputWindowPane.AssertOutputStrings("   Discovered a supported plugin: Language: 'C#', Minimum version: '5.0', Maximum version: '7.0'");
        }
        public void IsSonarQubePluginSupported_WhenSupportedVersionOfVSAndVBNetPluginEquals50_ReturnsTrueAndWriteExpectedText()
        {
            // Arrange
            VisualStudioHelpers.VisualStudioVersion = "14.0.25420.00";
            var testSubject     = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            var sonarqubePlugin = new SonarQubePlugin("vbnet", "5.0");

            // Act
            var result = testSubject.IsSonarQubePluginSupported(new[] { sonarqubePlugin }, MinimumSupportedSonarQubePlugin.VbNet);

            // Assert
            result.Should().BeTrue();
            this.outputWindowPane.AssertOutputStrings("   Discovered a supported plugin: Language: 'VB.NET', Minimum version: '3.0'");
        }
Пример #18
0
        public void ConnectionWorkflow_ConnectionStep_ConnectedServerCanBeGetAndSet()
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"));

#pragma warning disable IDE0017 // Simplify object initialization
            ConnectionWorkflow testSubject = new ConnectionWorkflow(this.host, new RelayCommand(() => { }));
#pragma warning restore IDE0017 // Simplify object initialization

            // Act
            testSubject.ConnectedServer = connectionInfo;

            // Assert
            connectionInfo.Should().Be(testSubject.ConnectedServer);
        }
Пример #19
0
        private static void TestPluginSupport(bool expectedResult, string vsVersion, SonarQubePlugin installedPlugin,
                                              MinimumSupportedSonarQubePlugin minimumSupportedPlugin,
                                              string expectedMessage)
        {
            // Arrange
            VisualStudioHelpers.VisualStudioVersion = vsVersion;
            var logger = new TestLogger();

            // Act
            var result = ConnectionWorkflow.IsSonarQubePluginSupported(new[] { installedPlugin }, minimumSupportedPlugin, logger);

            // Assert
            result.Should().Be(expectedResult);
            logger.AssertOutputStrings(expectedMessage);
        }
        private void ConnectionWorkflow_ConnectionStep_WhenXPluginAndNoXProject_AbortsWorkflowAndDisconnects(string projectName, string projectKind, MinimumSupportedServerPlugin minimumSupportedServerPlugin)
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"));
            var projects       = new ProjectInformation[] { new ProjectInformation {
                                                                Key = "project1"
                                                            } };

            this.sonarQubeService.ReturnProjectInformation = projects;
            this.sonarQubeService.ClearServerPlugins();
            this.sonarQubeService.RegisterServerPlugin(new ServerPlugin {
                Key = minimumSupportedServerPlugin.Key, Version = minimumSupportedServerPlugin.MinimumVersion
            });
            this.projectSystemHelper.Projects = new[] { new ProjectMock(projectName)
                                                        {
                                                            ProjectKind = projectKind
                                                        } };
            bool projectChangedCallbackCalled = false;

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                CollectionAssert.AreEqual(projects, p.ToArray(), "Unexpected projects");
            };

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)this.host.ActiveSection.UserNotifications;

            // Act
            testSubject.ConnectionStep(controller, CancellationToken.None, connectionInfo, executionEvents);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(1);
            executionEvents.AssertProgressMessages(
                connectionInfo.ServerUri.ToString(),
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingServerPlugins,
                Strings.ConnectionResultFailure);
            projectChangedCallbackCalled.Should().BeFalse("ConnectedProjectsCallaback was called");
            notifications.AssertNotification(NotificationIds.BadServerPluginId, string.Format(Strings.OnlySupportedPluginHasNoProjectInSolution, minimumSupportedServerPlugin.Language.Name));
        }
Пример #21
0
        private bool QualifiersMatch(RockContext rockContext, ConnectionWorkflow workflowTrigger, ConnectionState prevState, ConnectionState state)
        {
            var qualifierParts = (workflowTrigger.QualifierValue ?? "").Split(new char[] { '|' });

            bool matches = true;

            if (matches && qualifierParts.Length > 0 && !string.IsNullOrWhiteSpace(qualifierParts[0]))
            {
                matches = qualifierParts[0].AsInteger() == state.ConvertToInt();
            }

            if (matches && qualifierParts.Length > 2 && !string.IsNullOrWhiteSpace(qualifierParts[2]))
            {
                matches = qualifierParts[2].AsInteger() == prevState.ConvertToInt();
            }

            return(matches);
        }
        public void ConnectionWorkflow_DownloadServiceParameters_RegexPropertyNotSet_SetsFilterWithDefaultExpression()
        {
            // Setup
            var controller                 = new ConfigurableProgressController();
            var progressEvents             = new ConfigurableProgressStepExecutionEvents();
            var expectedExpression         = ServerProperty.TestProjectRegexDefaultValue;
            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            // Sanity
            Assert.IsFalse(this.sonarQubeService.ServerProperties.Any(x => x.Key != ServerProperty.TestProjectRegexKey), "Test project regex property should not be set");

            // Act
            testSubject.DownloadServiceParameters(controller, CancellationToken.None, progressEvents);

            // Verify
            filter.AssertTestRegex(expectedExpression, RegexOptions.IgnoreCase);
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
        }
        private void ConnectionWorkflow_ConnectionStep_WhenXPluginAndAnyXProject_SuccessfulConnection(string projectName, string projectKind)
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"));
            var projects       = new ProjectInformation[] { new ProjectInformation {
                                                                Key = "project1"
                                                            } };

            this.sonarQubeService.ReturnProjectInformation = projects;
            this.projectSystemHelper.Projects = new[] { new ProjectMock(projectName)
                                                        {
                                                            ProjectKind = projectKind
                                                        } };
            bool projectChangedCallbackCalled = false;

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                CollectionAssert.AreEqual(projects, p.ToArray(), "Unexpected projects");
            };

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));

            // Act
            testSubject.ConnectionStep(controller, CancellationToken.None, connectionInfo, executionEvents);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(0);
            executionEvents.AssertProgressMessages(
                connectionMessage,
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingServerPlugins,
                Strings.ConnectionStepRetrievingProjects,
                Strings.ConnectionResultSuccess);
            projectChangedCallbackCalled.Should().BeTrue("ConnectedProjectsCallaback was not called");
            sonarQubeService.ConnectionRequestsCount.Should().Be(1);
            testSubject.ConnectedServer.Should().Be(connectionInfo);
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoShowErrorMessages();
            ((ConfigurableUserNotification)this.host.ActiveSection.UserNotifications).AssertNoNotification(NotificationIds.FailedToConnectId);
        }
        public void ConnectionWorkflow_DownloadServiceParameters_Cancelled_AbortsWorkflow()
        {
            // Setup
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            var cts = new CancellationTokenSource();

            cts.Cancel();

            // Act
            testSubject.DownloadServiceParameters(controller, cts.Token, progressEvents);

            // Verify
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
            controller.AssertNumberOfAbortRequests(1);
        }
        public async Task ConnectionWorkflow_DownloadServiceParameters_NoTestProjectRegexProperty()
        {
            // Arrange
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            this.sonarQubeServiceMock.Setup(x => x.GetAllPropertiesAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <SonarQubeProperty> {
            });

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            // Act
            await testSubject.DownloadServiceParametersAsync(controller, progressEvents, CancellationToken.None);

            // Assert
            filter.AssertTestRegex(SonarQubeProperty.TestProjectRegexDefaultValue, RegexOptions.IgnoreCase);
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
        }
Пример #26
0
        public async Task ConnectionWorkflow_DownloadServiceParameters_Cancelled_AbortsWorkflow()
        {
            // Arrange
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            var cts = new CancellationTokenSource();

            cts.Cancel();

            // Act
            await testSubject.DownloadServiceParametersAsync(controller, progressEvents, cts.Token);

            // Assert
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
            controller.NumberOfAbortRequests.Should().Be(1);
        }
        public async Task ConnectionWorkflow_ConnectionStep_WhenPluginOkAndNoProjects_AbortsWorkflowAndDisconnects()
        {
            // Arrange
            var connectionInfo = new ConnectionInformation(new Uri("http://server"));
            var projects       = new List <SonarQubeProject> {
                new SonarQubeProject("project1", "")
            };

            this.sonarQubeServiceMock.Setup(x => x.GetAllProjectsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(projects);
            bool projectChangedCallbackCalled = false;

            this.host.TestStateManager.SetProjectsAction = (c, p) =>
            {
                projectChangedCallbackCalled = true;
                c.Should().Be(connectionInfo, "Unexpected connection");
                CollectionAssert.AreEqual(projects, p.ToArray(), "Unexpected projects");
            };

            var    controller        = new ConfigurableProgressController();
            var    executionEvents   = new ConfigurableProgressStepExecutionEvents();
            string connectionMessage = connectionInfo.ServerUri.ToString();
            var    testSubject       = new ConnectionWorkflow(this.host, new RelayCommand(AssertIfCalled));
            ConfigurableUserNotification notifications = (ConfigurableUserNotification)this.host.ActiveSection.UserNotifications;

            // Act
            await testSubject.ConnectionStepAsync(connectionInfo, controller, executionEvents, CancellationToken.None);

            // Assert
            controller.NumberOfAbortRequests.Should().Be(1);
            AssertServiceDisconnectCalled();
            executionEvents.AssertProgressMessages(
                connectionInfo.ServerUri.ToString(),
                Strings.ConnectionStepValidatinCredentials,
                Strings.DetectingSonarQubePlugins,
                Strings.ConnectionResultFailure);
            projectChangedCallbackCalled.Should().BeFalse("ConnectedProjectsCallaback was called");
            notifications.AssertNotification(NotificationIds.BadSonarQubePluginId, Strings.SolutionContainsNoSupportedProject);

            AssertCredentialsNotStored(); // Username and password are null
        }
Пример #28
0
        public async Task ConnectionWorkflow_DownloadServiceParameters_CustomRegexProperty_SetsFilterWithCorrectExpression()
        {
            // Arrange
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            var expectedExpression = ".*spoon.*";

            this.sonarQubeServiceMock.Setup(x => x.GetAllPropertiesAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <SonarQubeProperty> {
                new SonarQubeProperty(SonarQubeProperty.TestProjectRegexKey, expectedExpression)
            });

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            // Act
            await testSubject.DownloadServiceParametersAsync(controller, progressEvents, CancellationToken.None);

            // Assert
            testProjectRegexSetter.Verify(x => x.SetTestRegex(expectedExpression), Times.Once);
        }
        private bool QualifiersMatch(RockContext rockContext, ConnectionWorkflow workflowTrigger, int connectionActivityTypeId)
        {
            var qualifierParts = (workflowTrigger.QualifierValue ?? string.Empty).Split(new char[] { '|' });

            bool matches = true;

            if (matches && qualifierParts.Length > 1 && !string.IsNullOrWhiteSpace(qualifierParts[1]))
            {
                var qualifierGroupId = qualifierParts[1].AsIntegerOrNull();
                if (qualifierGroupId.HasValue)
                {
                    matches = qualifierGroupId != 0 && qualifierGroupId == connectionActivityTypeId;
                }
                else
                {
                    matches = false;
                }
            }

            return(matches);
        }
        public void ConnectionWorkflow_DownloadServiceParameters_CustomRegexProperty_SetsFilterWithCorrectExpression()
        {
            // Setup
            var controller     = new ConfigurableProgressController();
            var progressEvents = new ConfigurableProgressStepExecutionEvents();

            var expectedExpression = ".*spoon.*";

            this.sonarQubeService.RegisterServerProperty(new ServerProperty
            {
                Key   = ServerProperty.TestProjectRegexKey,
                Value = expectedExpression
            });

            ConnectionWorkflow testSubject = SetTestSubjectWithConnectedServer();

            // Act
            testSubject.DownloadServiceParameters(controller, CancellationToken.None, progressEvents);

            // Verify
            filter.AssertTestRegex(expectedExpression, RegexOptions.IgnoreCase);
            progressEvents.AssertProgressMessages(Strings.DownloadingServerSettingsProgessMessage);
        }
Пример #31
0
        /// <summary>
        /// Launches the workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="connectionWorkflow">The connection workflow.</param>
        /// <param name="name">The name.</param>
        private void LaunchWorkflow( RockContext rockContext, ConnectionRequest connectionRequest, ConnectionWorkflow connectionWorkflow )
        {
            if ( connectionRequest != null && connectionWorkflow != null && connectionWorkflow.WorkflowType != null )
            {
                var workflow = Rock.Model.Workflow.Activate( connectionWorkflow.WorkflowType, connectionWorkflow.WorkflowType.WorkTerm, rockContext );
                if ( workflow != null )
                {
                    var workflowService = new Rock.Model.WorkflowService( rockContext );

                    List<string> workflowErrors;
                    if ( workflowService.Process( workflow, connectionRequest, out workflowErrors ) )
                    {
                        if ( workflow.Id != 0 )
                        {
                            ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                            connectionRequestWorkflow.ConnectionRequestId = connectionRequest.Id;
                            connectionRequestWorkflow.WorkflowId = workflow.Id;
                            connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                            connectionRequestWorkflow.TriggerType = connectionWorkflow.TriggerType;
                            connectionRequestWorkflow.TriggerQualifier = connectionWorkflow.QualifierValue;
                            new ConnectionRequestWorkflowService( rockContext ).Add( connectionRequestWorkflow );

                            rockContext.SaveChanges();

                            if ( workflow.HasActiveEntryForm( CurrentPerson ) )
                            {
                                var qryParam = new Dictionary<string, string>();
                                qryParam.Add( "WorkflowTypeId", connectionWorkflow.WorkflowType.Id.ToString() );
                                qryParam.Add( "WorkflowId", workflow.Id.ToString() );
                                NavigateToLinkedPage( "WorkflowEntryPage", qryParam );
                            }
                            else
                            {
                                mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow has been started.",
                                    connectionWorkflow.WorkflowType.Name ), ModalAlertType.Information );
                            }

                            ShowDetail( PageParameter( "ConnectionRequestId" ).AsInteger(), PageParameter( "ConnectionOpportunityId" ).AsIntegerOrNull() );
                        }
                        else
                        {
                            mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow was processed (but not persisted).",
                                connectionWorkflow.WorkflowType.Name ), ModalAlertType.Information );
                        }
                    }
                    else
                    {
                        mdWorkflowLaunched.Show( "Workflow Processing Error(s):<ul><li>" + workflowErrors.AsDelimited( "</li><li>" ) + "</li></ul>", ModalAlertType.Information );
                    }
                }
            }
        }
        private bool QualifiersMatch( RockContext rockContext, ConnectionWorkflow workflowTrigger, int prevStatusId, int statusId )
        {
            if ( prevStatusId == statusId )
            {
                return false;
            }

            var qualifierParts = ( workflowTrigger.QualifierValue ?? "" ).Split( new char[] { '|' } );

            bool matches = true;

            if ( matches && qualifierParts.Length > 1 && !string.IsNullOrWhiteSpace( qualifierParts[1] ) )
            {
                var qualifierStatusId = qualifierParts[1].AsIntegerOrNull();
                if ( qualifierStatusId.HasValue )
                {
                    matches = qualifierStatusId != 0 && qualifierStatusId == prevStatusId;
                }
                else
                {
                    matches = false;
                }
            }

            if ( matches && qualifierParts.Length > 2 && !string.IsNullOrWhiteSpace( qualifierParts[2] ) )
            {
                var qualifierStatusId = qualifierParts[2].AsIntegerOrNull();
                if ( qualifierStatusId.HasValue )
                {
                    matches = qualifierStatusId != 0 && qualifierStatusId == statusId;
                }
                else
                {
                    matches = false;
                }
            }

            return matches;
        }
Пример #33
0
        private void LaunchWorkflow( RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name )
        {
            ConnectionRequest connectionRequest = null;
            if ( ConnectionRequestGuid.HasValue )
            {
                connectionRequest = new ConnectionRequestService( rockContext ).Get( ConnectionRequestGuid.Value );
            }

            var workflowTypeService = new WorkflowTypeService( rockContext );
            var workflowType = workflowTypeService.Get( connectionWorkflow.WorkflowTypeId.Value );
            if ( workflowType != null )
            {
                var workflow = Rock.Model.Workflow.Activate( workflowType, name );

                if ( workflow.AttributeValues != null )
                {
                    if ( workflow.AttributeValues.ContainsKey( "ConnectionOpportunity" ) )
                    {
                        var connectionOpportunity = new ConnectionOpportunityService( rockContext ).Get( ConnectionOpportunityId.Value );
                        if ( connectionOpportunity != null )
                        {
                            workflow.AttributeValues["ConnectionOpportunity"].Value = connectionOpportunity.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "ConnectionType" ) )
                    {
                        var connectionType = new ConnectionTypeService( rockContext ).Get( ConnectionTypeId.Value );
                        if ( connectionType != null )
                        {
                            workflow.AttributeValues["ConnectionType"].Value = connectionType.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "ConnectionRequest" ) )
                    {
                        if ( connectionRequest != null )
                        {
                            workflow.AttributeValues["ConnectionRequest"].Value = connectionRequest.Guid.ToString();
                        }
                    }

                    if ( workflow.AttributeValues.ContainsKey( "Person" ) )
                    {
                        var person = new PersonService( rockContext ).Get( PersonId.Value );
                        if ( person != null )
                        {
                            workflow.AttributeValues["Person"].Value = person.PrimaryAlias.Guid.ToString();
                        }
                    }
                }

                List<string> workflowErrors;
                new WorkflowService( rockContext ).Process( workflow, connectionRequest, out workflowErrors );
                if ( workflow.Id != 0 )
                {
                    ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                    connectionRequestWorkflow.ConnectionRequestId = connectionRequest.Id;
                    connectionRequestWorkflow.WorkflowId = workflow.Id;
                    connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                    connectionRequestWorkflow.TriggerType = connectionWorkflow.TriggerType;
                    connectionRequestWorkflow.TriggerQualifier = connectionWorkflow.QualifierValue;
                    new ConnectionRequestWorkflowService( rockContext ).Add( connectionRequestWorkflow );
                    rockContext.SaveChanges();
                }
            }
        }
Пример #34
0
 private bool QualifiersMatch( RockContext rockContext, ConnectionWorkflow workflowTrigger, ConnectionState prevState, ConnectionState state, int prevStatusId, int statusId, int? groupId )
 {
     return QualifiersMatch( rockContext, workflowTrigger, prevState, state ) && QualifiersMatch( rockContext, workflowTrigger, prevStatusId, statusId ) && QualifiersMatch( rockContext, workflowTrigger, groupId );
 }
Пример #35
0
        private bool QualifiersMatch( RockContext rockContext, ConnectionWorkflow workflowTrigger, ConnectionState prevState, ConnectionState state )
        {
            var qualifierParts = ( workflowTrigger.QualifierValue ?? "" ).Split( new char[] { '|' } );

            bool matches = true;

            if ( matches && qualifierParts.Length > 0 && !string.IsNullOrWhiteSpace( qualifierParts[0] ) )
            {
                matches = qualifierParts[0].AsInteger() == state.ConvertToInt();
            }

            if ( matches && qualifierParts.Length > 2 && !string.IsNullOrWhiteSpace( qualifierParts[2] ) )
            {
                matches = qualifierParts[2].AsInteger() == prevState.ConvertToInt();
            }

            return matches;
        }
Пример #36
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            ConnectionOpportunity connectionOpportunity = null;

            using ( RockContext rockContext = new RockContext() )
            {
                int? groupTypeId = ddlGroupType.SelectedValueAsInt();
                if ( groupTypeId.HasValue && GroupsState.Any( g => g.Group.GroupTypeId != groupTypeId.Value ) )
                {
                    var groupType = new GroupTypeService( rockContext ).Get( groupTypeId.Value );
                    if ( groupType != null )
                    {
                        nbInvalidGroupTypes.Text = string.Format( "<p>One or more of the selected groups is not a <strong>{0}</strong> type. Please select groups that have a group type of <strong>{0}</strong>.", groupType.Name );
                        nbInvalidGroupTypes.Visible = true;
                        return;
                    }
                }

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext );
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext );
                ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext );
                ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext );

                int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt();
                if ( connectionOpportunityId != 0 )
                {
                    connectionOpportunity = connectionOpportunityService
                        .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" )
                        .Where( ei => ei.Id == connectionOpportunityId )
                        .FirstOrDefault();
                }

                if ( connectionOpportunity == null )
                {
                    connectionOpportunity = new ConnectionOpportunity();
                    connectionOpportunity.Name = string.Empty;
                    connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger();
                    connectionOpportunityService.Add( connectionOpportunity );

                }

                connectionOpportunity.Name = tbName.Text;
                connectionOpportunity.Description = tbDescription.Text;
                connectionOpportunity.IsActive = cbIsActive.Checked;
                connectionOpportunity.PublicName = tbPublicName.Text;
                connectionOpportunity.IconCssClass = tbIconCssClass.Text;
                connectionOpportunity.GroupTypeId = ddlGroupType.SelectedValue.AsInteger();
                connectionOpportunity.GroupMemberRoleId = ddlGroupRole.SelectedValue.AsInteger();
                connectionOpportunity.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                int? orphanedPhotoId = null;
                if ( imgupPhoto.BinaryFileId != null )
                {
                    if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = connectionOpportunity.PhotoId;
                    }
                    connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value;
                }

                // remove any workflows that removed in the UI
                var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid );
                foreach ( var connectionOpportunityWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionWorkflows.Remove( connectionOpportunityWorkflow );
                    connectionWorkflowService.Delete( connectionOpportunityWorkflow );
                }

                // Add or Update workflows from the UI
                foreach ( ConnectionWorkflow connectionOpportunityWorkflowState in WorkflowsState.Where( w => w.ConnectionTypeId == null ) )
                {
                    ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == connectionOpportunityWorkflowState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityWorkflow == null )
                    {
                        connectionOpportunityWorkflow = new ConnectionWorkflow();
                        connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow );
                    }
                    connectionOpportunityWorkflow.CopyPropertiesFrom( connectionOpportunityWorkflowState );
                    connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any group campuses that removed in the UI
                var uiGroupCampuses = GroupCampusesState.Select( l => l.Guid );
                foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiGroupCampuses.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups );
                    connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups );
                }

                // Add or Update group campuses from the UI
                foreach ( var connectionOpportunityConnectorGroupsState in GroupCampusesState )
                {
                    ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroups = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == connectionOpportunityConnectorGroupsState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityConnectorGroups == null )
                    {
                        connectionOpportunityConnectorGroups = new ConnectionOpportunityConnectorGroup();
                        connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroups );
                    }

                    connectionOpportunityConnectorGroups.CopyPropertiesFrom( connectionOpportunityConnectorGroupsState );
                }

                // remove any campuses that removed in the UI
                var uiCampuses = cblCampus.SelectedValuesAsInt;
                foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus );
                    connectionOpportunityCampusService.Delete( connectionOpportunityCampus );
                }

                // Add or Update campuses from the UI
                foreach ( var campusId in uiCampuses )
                {
                    ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault();
                    if ( connectionOpportunityCampus == null )
                    {
                        connectionOpportunityCampus = new ConnectionOpportunityCampus();
                        connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus );
                    }

                    connectionOpportunityCampus.CampusId = campusId;
                }

                // Remove any groups that were removed in the UI
                var uiGroups = GroupsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup );
                    connectionOpportunityGroupService.Delete( connectionOpportunityGroup );
                }

                // Add or Update groups from the UI
                foreach ( var connectionOpportunityGroupState in GroupsState )
                {
                    ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == connectionOpportunityGroupState.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroup == null )
                    {
                        connectionOpportunityGroup = new ConnectionOpportunityGroup();
                        connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup );
                    }

                    connectionOpportunityGroup.CopyPropertiesFrom( connectionOpportunityGroupState );
                }

                connectionOpportunity.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity );

                if ( !Page.IsValid )
                {
                    return;
                }

                if ( !connectionOpportunity.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    connectionOpportunity.SaveAttributeValues( rockContext );

                    if ( orphanedPhotoId.HasValue )
                    {
                        BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                        var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        if ( binaryFile != null )
                        {
                            string errorMessage;
                            if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                            {
                                binaryFileService.Delete( binaryFile );
                                rockContext.SaveChanges();
                            }
                        }
                    }
                } );

                var qryParams = new Dictionary<string, string>();
                qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" );
                NavigateToParentPage( qryParams );
            }
        }
 public WorkflowTypeStateObj( ConnectionWorkflow connectionWorkflow )
 {
     Id = connectionWorkflow.Id;
     Guid = connectionWorkflow.Guid;
     ConnectionTypeId = connectionWorkflow.ConnectionTypeId;
     TriggerType = connectionWorkflow.TriggerType;
     QualifierValue = connectionWorkflow.QualifierValue;
     if ( connectionWorkflow.WorkflowType != null )
     {
         WorkflowTypeId = connectionWorkflow.WorkflowType.Id;
         WorkflowTypeName = connectionWorkflow.WorkflowType.Name;
     }
 }
Пример #38
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            ConnectionType connectionType;
            using ( var rockContext = new RockContext() )
            {
                if ( StatusesState.Any( s => s.IsDefault ) && ActivityTypesState.Any() )
                {
                    ConnectionTypeService connectionTypeService = new ConnectionTypeService( rockContext );
                    ConnectionActivityTypeService connectionActivityTypeService = new ConnectionActivityTypeService( rockContext );
                    ConnectionStatusService connectionStatusService = new ConnectionStatusService( rockContext );
                    ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                    AttributeService attributeService = new AttributeService( rockContext );
                    AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );

                    int connectionTypeId = int.Parse( hfConnectionTypeId.Value );

                    if ( connectionTypeId == 0 )
                    {
                        connectionType = new ConnectionType();
                        connectionTypeService.Add( connectionType );
                    }
                    else
                    {
                        connectionType = connectionTypeService.Queryable( "ConnectionActivityTypes, ConnectionWorkflows" ).Where( c => c.Id == connectionTypeId ).FirstOrDefault();

                        var uiWorkflows = WorkflowsState.Select( l => l.Guid );
                        foreach ( var connectionWorkflow in connectionType.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionWorkflows.Remove( connectionWorkflow );
                            connectionWorkflowService.Delete( connectionWorkflow );
                        }

                        var uiActivityTypes = ActivityTypesState.Select( r => r.Guid );
                        foreach ( var connectionActivityType in connectionType.ConnectionActivityTypes.Where( r => !uiActivityTypes.Contains( r.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionActivityTypes.Remove( connectionActivityType );
                            connectionActivityTypeService.Delete( connectionActivityType );
                        }

                        var uiStatuses = StatusesState.Select( r => r.Guid );
                        foreach ( var connectionStatus in connectionType.ConnectionStatuses.Where( r => !uiStatuses.Contains( r.Guid ) ).ToList() )
                        {
                            connectionType.ConnectionStatuses.Remove( connectionStatus );
                            connectionStatusService.Delete( connectionStatus );
                        }
                    }

                    connectionType.Name = tbName.Text;
                    connectionType.Description = tbDescription.Text;
                    connectionType.IconCssClass = tbIconCssClass.Text;
                    connectionType.DaysUntilRequestIdle = nbDaysUntilRequestIdle.Text.AsInteger();
                    connectionType.EnableFutureFollowup = cbFutureFollowUp.Checked;
                    connectionType.EnableFullActivityList = cbFullActivityList.Checked;
                    connectionType.RequiresPlacementGroupToConnect = cbRequiresPlacementGroup.Checked;

                    foreach ( var connectionActivityTypeState in ActivityTypesState )
                    {
                        ConnectionActivityType connectionActivityType = connectionType.ConnectionActivityTypes.Where( a => a.Guid == connectionActivityTypeState.Guid ).FirstOrDefault();
                        if ( connectionActivityType == null )
                        {
                            connectionActivityType = new ConnectionActivityType();
                            connectionType.ConnectionActivityTypes.Add( connectionActivityType );
                        }

                        connectionActivityType.CopyPropertiesFrom( connectionActivityTypeState );
                    }

                    foreach ( var connectionStatusState in StatusesState )
                    {
                        ConnectionStatus connectionStatus = connectionType.ConnectionStatuses.Where( a => a.Guid == connectionStatusState.Guid ).FirstOrDefault();
                        if ( connectionStatus == null )
                        {
                            connectionStatus = new ConnectionStatus();
                            connectionType.ConnectionStatuses.Add( connectionStatus );
                        }

                        connectionStatus.CopyPropertiesFrom( connectionStatusState );
                        connectionStatus.ConnectionTypeId = connectionType.Id;
                    }

                    foreach ( ConnectionWorkflow connectionWorkflowState in WorkflowsState )
                    {
                        ConnectionWorkflow connectionWorkflow = connectionType.ConnectionWorkflows.Where( a => a.Guid == connectionWorkflowState.Guid ).FirstOrDefault();
                        if ( connectionWorkflow == null )
                        {
                            connectionWorkflow = new ConnectionWorkflow();
                            connectionType.ConnectionWorkflows.Add( connectionWorkflow );
                        }
                        else
                        {
                            connectionWorkflowState.Id = connectionWorkflow.Id;
                            connectionWorkflowState.Guid = connectionWorkflow.Guid;
                        }

                        connectionWorkflow.CopyPropertiesFrom( connectionWorkflowState );
                        connectionWorkflow.ConnectionTypeId = connectionTypeId;
                    }

                    if ( !connectionType.IsValid )
                    {
                        // Controls will render the error messages
                        return;
                    }

                    // need WrapTransaction due to Attribute saves
                    rockContext.WrapTransaction( () =>
                    {
                        rockContext.SaveChanges();

                        /* Save Attributes */
                        string qualifierValue = connectionType.Id.ToString();
                        SaveAttributes( new ConnectionOpportunity().TypeId, "ConnectionTypeId", qualifierValue, AttributesState, rockContext );

                        connectionType = connectionTypeService.Get( connectionType.Id );
                        if ( connectionType != null )
                        {
                            if ( !connectionType.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.VIEW, CurrentPerson, rockContext );
                            }

                            if ( !connectionType.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                            }

                            if ( !connectionType.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) )
                            {
                                connectionType.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );
                            }
                        }
                    } );

                    ConnectionWorkflowService.FlushCachedTriggers();

                    var qryParams = new Dictionary<string, string>();
                    qryParams["ConnectionTypeId"] = connectionType.Id.ToString();

                    NavigateToPage( RockPage.Guid, qryParams );
                }
                else
                {
                    nbRequired.Visible = true;
                }
            }
        }
Пример #39
0
        /// <summary>
        /// Handles the SaveClick event of the dlgConnectionWorkflow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dlgConnectionWorkflow_SaveClick( object sender, EventArgs e )
        {
            ConnectionWorkflow connectionWorkflow = null;
            Guid guid = hfAddConnectionWorkflowGuid.Value.AsGuid();
            if ( !guid.IsEmpty() )
            {
                connectionWorkflow = WorkflowsState.FirstOrDefault( l => l.Guid.Equals( guid ) );
            }

            if ( connectionWorkflow == null )
            {
                connectionWorkflow = new ConnectionWorkflow();
            }
            try
            {
                connectionWorkflow.WorkflowType = new WorkflowTypeService( new RockContext() ).Get( ddlWorkflowType.SelectedValueAsId().Value );
            }
            catch { }
            connectionWorkflow.WorkflowTypeId = ddlWorkflowType.SelectedValueAsId().Value;
            connectionWorkflow.TriggerType = ddlTriggerType.SelectedValueAsEnum<ConnectionWorkflowTriggerType>();
            connectionWorkflow.QualifierValue = String.Format( "|{0}|{1}|", ddlPrimaryQualifier.SelectedValue, ddlSecondaryQualifier.SelectedValue );
            connectionWorkflow.ConnectionTypeId = 0;
            if ( !connectionWorkflow.IsValid )
            {
                return;
            }
            if ( WorkflowsState.Any( a => a.Guid.Equals( connectionWorkflow.Guid ) ) )
            {
                WorkflowsState.RemoveEntity( connectionWorkflow.Guid );
            }

            WorkflowsState.Add( connectionWorkflow );
            BindConnectionWorkflowsGrid();
            HideDialog();
        }
Пример #40
0
        /// <summary>
        /// Handles the SaveClick event of the dlgWorkflowDetails control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void dlgWorkflowDetails_SaveClick( object sender, EventArgs e )
        {
            ConnectionWorkflow connectionOpportunityWorkflow = null;
            Guid guid = hfWorkflowGuid.Value.AsGuid();
            if ( !guid.IsEmpty() )
            {
                connectionOpportunityWorkflow = WorkflowsState.FirstOrDefault( l => l.Guid.Equals( guid ) );
            }

            if ( connectionOpportunityWorkflow == null )
            {
                connectionOpportunityWorkflow = new ConnectionWorkflow();
            }

            connectionOpportunityWorkflow.WorkflowType = new WorkflowTypeService( new RockContext() ).Get( ddlWorkflowType.SelectedValueAsId().Value ) ?? null;
            connectionOpportunityWorkflow.WorkflowTypeId = ddlWorkflowType.SelectedValueAsId().Value;
            connectionOpportunityWorkflow.TriggerType = ddlTriggerType.SelectedValueAsEnum<ConnectionWorkflowTriggerType>();
            connectionOpportunityWorkflow.ConnectionOpportunityId = 0;

            if ( !connectionOpportunityWorkflow.IsValid )
            {
                return;
            }

            if ( WorkflowsState.Any( a => a.Guid.Equals( connectionOpportunityWorkflow.Guid ) ) )
            {
                WorkflowsState.RemoveEntity( connectionOpportunityWorkflow.Guid );
            }

            WorkflowsState.Add( connectionOpportunityWorkflow );
            BindWorkflowGrid();
            HideDialog();
        }
        private bool QualifiersMatch( RockContext rockContext, ConnectionWorkflow workflowTrigger, int connectionActivityTypeId )
        {
            var qualifierParts = ( workflowTrigger.QualifierValue ?? "" ).Split( new char[] { '|' } );

            bool matches = true;

            if ( matches && qualifierParts.Length > 1 && !string.IsNullOrWhiteSpace( qualifierParts[1] ) )
            {
                var qualifierGroupId = qualifierParts[1].AsIntegerOrNull();
                if ( qualifierGroupId.HasValue )
                {
                    matches = qualifierGroupId != 0 && qualifierGroupId == connectionActivityTypeId;
                }
                else
                {
                    matches = false;
                }
            }
            return matches;
        }
        private void LaunchWorkflow( RockContext rockContext, ConnectionWorkflow connectionWorkflow, string name )
        {
            var workflowTypeService = new WorkflowTypeService( rockContext );
            var workflowType = workflowTypeService.Get( connectionWorkflow.WorkflowTypeId.Value );
            if ( workflowType != null )
            {
                ConnectionRequestActivity connectionRequestActivity = null;
                if ( ConnectionRequestActivityGuid.HasValue )
                {
                    connectionRequestActivity = new ConnectionRequestActivityService( rockContext ).Get( ConnectionRequestActivityGuid.Value );
                    var workflow = Rock.Model.Workflow.Activate( workflowType, name );

                    List<string> workflowErrors;
                    new WorkflowService( rockContext ).Process( workflow, connectionRequestActivity, out workflowErrors );
                    if ( workflow.Id != 0 )
                    {
                        ConnectionRequestWorkflow connectionRequestWorkflow = new ConnectionRequestWorkflow();
                        connectionRequestWorkflow.ConnectionRequestId = connectionRequestActivity.ConnectionRequestId;
                        connectionRequestWorkflow.WorkflowId = workflow.Id;
                        connectionRequestWorkflow.ConnectionWorkflowId = connectionWorkflow.Id;
                        connectionRequestWorkflow.TriggerType = connectionWorkflow.TriggerType;
                        connectionRequestWorkflow.TriggerQualifier = connectionWorkflow.QualifierValue;
                        new ConnectionRequestWorkflowService( rockContext ).Add( connectionRequestWorkflow );
                        rockContext.SaveChanges();
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            ConnectionOpportunity connectionOpportunity = null;

            using ( RockContext rockContext = new RockContext() )
            {
                if ( !ValidPlacementGroups() )
                {
                    return;
                }

                ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext );
                EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext );
                ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext );
                ConnectionRequestWorkflowService connectionRequestWorkflowService = new ConnectionRequestWorkflowService( rockContext );
                ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext );
                ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext );
                ConnectionOpportunityGroupConfigService connectionOpportunityGroupConfigService = new ConnectionOpportunityGroupConfigService( rockContext );
                ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext );

                int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt();
                if ( connectionOpportunityId != 0 )
                {
                    connectionOpportunity = connectionOpportunityService
                        .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" )
                        .Where( ei => ei.Id == connectionOpportunityId )
                        .FirstOrDefault();
                }

                if ( connectionOpportunity == null )
                {
                    connectionOpportunity = new ConnectionOpportunity();
                    connectionOpportunity.Name = string.Empty;
                    connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger();
                    connectionOpportunityService.Add( connectionOpportunity );
                }

                connectionOpportunity.Name = tbName.Text;
                connectionOpportunity.Summary = htmlSummary.Text;
                connectionOpportunity.Description = htmlDescription.Text;
                connectionOpportunity.IsActive = cbIsActive.Checked;
                connectionOpportunity.PublicName = tbPublicName.Text;
                connectionOpportunity.IconCssClass = tbIconCssClass.Text;

                int? orphanedPhotoId = null;
                if ( imgupPhoto.BinaryFileId != null )
                {
                    if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = connectionOpportunity.PhotoId;
                    }
                    connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value;
                }

                // remove any workflows that removed in the UI
                var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid );
                foreach ( var connectionWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() )
                {
                    foreach( var requestWorkflow in connectionRequestWorkflowService.Queryable()
                        .Where( w => w.ConnectionWorkflowId == connectionWorkflow.Id ) )
                    {
                        connectionRequestWorkflowService.Delete( requestWorkflow );
                    }

                    connectionOpportunity.ConnectionWorkflows.Remove( connectionWorkflow );
                    connectionWorkflowService.Delete( connectionWorkflow );
                }

                // Add or Update workflows from the UI
                foreach ( var workflowTypeStateObj in WorkflowsState.Where( w => w.ConnectionTypeId == null ) )
                {
                    ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == workflowTypeStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityWorkflow == null )
                    {
                        connectionOpportunityWorkflow = new ConnectionWorkflow();
                        connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow );
                    }
                    connectionOpportunityWorkflow.Id = workflowTypeStateObj.Id;
                    connectionOpportunityWorkflow.Guid = workflowTypeStateObj.Guid;
                    connectionOpportunityWorkflow.ConnectionTypeId = workflowTypeStateObj.ConnectionTypeId;
                    connectionOpportunityWorkflow.WorkflowTypeId = workflowTypeStateObj.WorkflowTypeId;
                    connectionOpportunityWorkflow.TriggerType = workflowTypeStateObj.TriggerType;
                    connectionOpportunityWorkflow.QualifierValue = workflowTypeStateObj.QualifierValue;
                    connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any group campuses that removed in the UI
                var uiConnectorGroups = ConnectorGroupsState.Select( l => l.Guid );
                foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiConnectorGroups.Contains( l.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups );
                    connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups );
                }

                // Add or Update group campuses from the UI
                foreach ( var groupStateObj in ConnectorGroupsState )
                {
                    ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroup = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == groupStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityConnectorGroup == null )
                    {
                        connectionOpportunityConnectorGroup = new ConnectionOpportunityConnectorGroup();
                        connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroup );
                    }

                    connectionOpportunityConnectorGroup.CampusId = groupStateObj.CampusId;
                    connectionOpportunityConnectorGroup.ConnectorGroupId = groupStateObj.GroupId;
                    connectionOpportunityConnectorGroup.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // remove any campuses that removed in the UI
                var uiCampuses = cblSelectedItemsAsInt( cblCampus );
                foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus );
                    connectionOpportunityCampusService.Delete( connectionOpportunityCampus );
                }

                // Add or Update campuses from the UI
                foreach ( var campusId in uiCampuses )
                {
                    ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault();
                    if ( connectionOpportunityCampus == null )
                    {
                        connectionOpportunityCampus = new ConnectionOpportunityCampus();
                        connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus );
                    }

                    connectionOpportunityCampus.CampusId = campusId;
                    connectionOpportunityCampus.DefaultConnectorPersonAliasId = DefaultConnectors.ContainsKey( campusId ) ? DefaultConnectors[campusId] : (int?)null;
                }

                // remove any group configs that were removed in the UI
                var uiGroupConfigs = GroupConfigsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroupConfig in connectionOpportunity.ConnectionOpportunityGroupConfigs.Where( r => !uiGroupConfigs.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroupConfigs.Remove( connectionOpportunityGroupConfig );
                    connectionOpportunityGroupConfigService.Delete( connectionOpportunityGroupConfig );
                }

                // Add or Update group configs from the UI
                foreach ( var groupConfigStateObj in GroupConfigsState )
                {
                    ConnectionOpportunityGroupConfig connectionOpportunityGroupConfig = connectionOpportunity.ConnectionOpportunityGroupConfigs.Where( a => a.Guid == groupConfigStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroupConfig == null )
                    {
                        connectionOpportunityGroupConfig = new ConnectionOpportunityGroupConfig();
                        connectionOpportunity.ConnectionOpportunityGroupConfigs.Add( connectionOpportunityGroupConfig );
                    }

                    connectionOpportunityGroupConfig.GroupTypeId = groupConfigStateObj.GroupTypeId;
                    connectionOpportunityGroupConfig.GroupMemberRoleId = groupConfigStateObj.GroupMemberRoleId;
                    connectionOpportunityGroupConfig.GroupMemberStatus = groupConfigStateObj.GroupMemberStatus;
                    connectionOpportunityGroupConfig.UseAllGroupsOfType = groupConfigStateObj.UseAllGroupsOfType;

                    connectionOpportunityGroupConfig.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                // Remove any groups that were removed in the UI
                var uiGroups = GroupsState.Select( r => r.Guid );
                foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() )
                {
                    connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup );
                    connectionOpportunityGroupService.Delete( connectionOpportunityGroup );
                }

                // Add or Update groups from the UI
                foreach ( var groupStateObj in GroupsState )
                {
                    ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == groupStateObj.Guid ).FirstOrDefault();
                    if ( connectionOpportunityGroup == null )
                    {
                        connectionOpportunityGroup = new ConnectionOpportunityGroup();
                        connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup );
                    }

                    connectionOpportunityGroup.GroupId = groupStateObj.GroupId;
                    connectionOpportunityGroup.ConnectionOpportunityId = connectionOpportunity.Id;
                }

                connectionOpportunity.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity );

                if ( !Page.IsValid )
                {
                    return;
                }

                if ( !connectionOpportunity.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    connectionOpportunity.SaveAttributeValues( rockContext );

                    if ( orphanedPhotoId.HasValue )
                    {
                        BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                        var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        if ( binaryFile != null )
                        {
                            string errorMessage;
                            if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                            {
                                binaryFileService.Delete( binaryFile );
                                rockContext.SaveChanges();
                            }
                        }
                    }
                } );

                ConnectionWorkflowService.FlushCachedTriggers();

                var qryParams = new Dictionary<string, string>();
                qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" );
                NavigateToParentPage( qryParams );
            }
        }