/// <summary>
        /// Handles the Delete event of the gBenevolenceType control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gBenevolenceType_Delete(object sender, RowEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                rockContext.WrapTransaction(action: () =>
                {
                    var benevolenceWorkflowService = new BenevolenceWorkflowService(rockContext);
                    var benevolenceTypeService     = new BenevolenceTypeService(rockContext);
                    var authService = new AuthService(rockContext);
                    BenevolenceType benevolenceType = benevolenceTypeService.Get(e.RowKeyId);

                    if (benevolenceType != null)
                    {
                        // Do not allow deletions if the person is not authorized
                        if (!benevolenceType.IsAuthorized(Authorization.ADMINISTRATE, this.CurrentPerson))
                        {
                            mdGridWarning.Show("You are not authorized to delete this Benevolence type.", ModalAlertType.Information);
                            return;
                        }

                        // var benevolenceRequests = new Service<BenevolenceRequest>( rockContext ).Queryable().All( a => a.BenevolenceTypeId == BenevolenceType.Id );
                        var benevolenceRequests       = benevolenceType.BenevolenceRequests.ToList();
                        var benevolenceRequestService = new BenevolenceRequestService(rockContext);

                        string errorMessageBenevolenceRequest = string.Empty;

                        foreach (var benvolenceRequest in benevolenceRequests)
                        {
                            if (!benevolenceRequestService.CanDelete(benvolenceRequest, out errorMessageBenevolenceRequest))
                            {
                                mdGridWarning.Show(errorMessageBenevolenceRequest, ModalAlertType.Information);
                                return;
                            }

                            benevolenceRequestService.Delete(benvolenceRequest);
                        }

                        // Save deleting the benevolence requests for the benevolence type id
                        rockContext.SaveChanges();

                        string errorMessageBenevolenceType;
                        if (!benevolenceTypeService.CanDelete(benevolenceType, out errorMessageBenevolenceType))
                        {
                            mdGridWarning.Show(errorMessageBenevolenceType, ModalAlertType.Information);
                            return;
                        }

                        benevolenceTypeService.Delete(benevolenceType);
                        rockContext.SaveChanges();

                        // ToDo: benevolenceWorkflowService.RemoveCachedTriggers();
                    }
                });
            }

            BindGrid();
        }
        /// <summary>
        /// Execute method to check for any workflows to launch.
        /// </summary>
        public void Execute()
        {
            if (!(BenevolenceRequestGuid.HasValue && RequestByPersonId.HasValue))
            {
                return;
            }

            // Get all the workflows from cache
            var cachedWorkflows = BenevolenceWorkflowService.GetCachedTriggers();

            if (cachedWorkflows == null || !cachedWorkflows.Any())
            {
                return;
            }

            var workflows = cachedWorkflows
                            .Where(w =>
                                   w.TriggerType != BenevolenceWorkflowTriggerType.Manual & w.BenevolenceTypeId == BenevolenceTypeId
                                   )
                            .ToList();

            if (workflows.Any())
            {
                using (var rockContext = new RockContext())
                {
                    // Loop through benevolenceWorkflows and launch appropriate workflow
                    foreach (var benevolenceWorkflow in workflows)
                    {
                        switch (benevolenceWorkflow.TriggerType)
                        {
                        case BenevolenceWorkflowTriggerType.RequestStarted:
                        {
                            if (State == EntityState.Added)
                            {
                                LaunchWorkflow(rockContext, benevolenceWorkflow, "Request Started");
                            }
                            break;
                        }

                        case BenevolenceWorkflowTriggerType.CaseworkerAssigned:
                        {
                            if (CaseWorkerPersonAliasId.HasValue &&
                                !CaseWorkerPersonAliasId.Equals(PreviousCaseWorkerPersonAliasId))
                            {
                                LaunchWorkflow(rockContext, benevolenceWorkflow, "Case Worker Assigned");
                            }
                            break;
                        }

                        case BenevolenceWorkflowTriggerType.StatusChanged:
                        {
                            if (State == EntityState.Modified && QualifiersMatch(benevolenceWorkflow, PreviousRequestStatusValueId, RequestStatusValueId))
                            {
                                LaunchWorkflow(rockContext, benevolenceWorkflow, "Status Changed");
                            }
                            break;
                        }
                        }
                    }
                }
            }
        }
        /// <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)
        {
            Page.Validate();
            BenevolenceType benevolenceType = null;

            using (var rockContext = new RockContext())
            {
                var benevolenceService         = new BenevolenceTypeService(rockContext);
                var benevolenceWorkflowService = new BenevolenceWorkflowService(rockContext);

                var benevolenceTypeId = benevolenceTypeIdPageParameter;

                if (benevolenceTypeId != 0)
                {
                    benevolenceType = benevolenceService.Get(benevolenceTypeId);
                }

                if (benevolenceType == null)
                {
                    // Check for existing
                    var existingBenevolence = benevolenceService.Queryable()
                                              .Where(d => d.Name == tbName.Text)
                                              .FirstOrDefault();

                    if (existingBenevolence != null)
                    {
                        nbDuplicateDevice.Text    = $"A benevolence type already exists with the name '{existingBenevolence.Name}'. Please use a different benevolence type name.";
                        nbDuplicateDevice.Visible = true;
                    }
                    else
                    {
                        benevolenceType = new BenevolenceType();
                        benevolenceService.Add(benevolenceType);
                    }
                }

                if (benevolenceType != null)
                {
                    benevolenceType.Name                 = tbName.Text;
                    benevolenceType.Description          = tbDescription.Text;
                    benevolenceType.RequestLavaTemplate  = ceLavaTemplate.Text;
                    benevolenceType.ShowFinancialResults = cbShowFinancialResults.Checked;
                    benevolenceType.IsActive             = cbIsActive.Checked;

                    // remove any workflows that were removed in the UI
                    var uiWorkflows = WorkflowStateModel.Select(l => l.Guid);

                    foreach (var benevolenceWorkflow in benevolenceType.BenevolenceWorkflows.Where(l => !uiWorkflows.Contains(l.Guid)).ToList())
                    {
                        benevolenceType.BenevolenceWorkflows.Remove(benevolenceWorkflow);
                        benevolenceWorkflowService.Delete(benevolenceWorkflow);
                    }

                    // Add or Update workflows from the UI
                    foreach (var workflowStateModel in WorkflowStateModel)
                    {
                        BenevolenceWorkflow benevolenceWorkflow = benevolenceType.BenevolenceWorkflows
                                                                  .Where(b => !workflowStateModel.Guid.Equals(Guid.Empty) && b.Guid == workflowStateModel.Guid).FirstOrDefault();

                        if (benevolenceWorkflow == null)
                        {
                            benevolenceWorkflow = new BenevolenceWorkflow
                            {
                                BenevolenceTypeId = benevolenceTypeId
                            };
                            benevolenceType.BenevolenceWorkflows.Add(benevolenceWorkflow);
                        }

                        // Set the properties on the state model
                        benevolenceWorkflow.CopyPropertiesFrom(workflowStateModel);
                    }

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

                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.SaveChanges();
                    });

                    BenevolenceWorkflowService.RemoveCachedTriggers();
                    NavigateToParentPage();
                }
            }
        }