public void Given_simple_workflow_runned_twice() { _service = new WorkflowService(); var instance1 = _service.Get<FooWorkflow>(SimpleWorkflowKey); instance1.Ping(); var instance2 = _service.Get<FooWorkflow>(SimpleWorkflowKey); instance2.Ping(); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var workflow = action.Activity.Workflow; if (workflow.Id >= 0) { // Create a new RockContext so that any previous updates are ignored and // workflow can be sucessfully deleted var newRockContext = new RockContext(); var workflowService = new WorkflowService(newRockContext); var workflowToDelete = workflowService.Get(workflow.Id); if (workflowToDelete != null) { workflowService.Delete(workflowToDelete); newRockContext.SaveChanges(); } } workflow.Id = 0; workflow.IsPersisted = false; return(true); }
/// <summary> /// Handles the SelectedIndexChanged event of the ddlWorkflows 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 ddlWorkflows_SelectedIndexChanged(object sender, EventArgs e) { RockContext rockContext = new RockContext(); WorkflowService workflowService = new WorkflowService(rockContext); mergeFields.Add("Workflow", workflowService.Get(ddlWorkflows.SelectedValueAsInt() ?? -1)); SetUserPreference(_USER_PREF_WORKFLOW, ddlWorkflows.SelectedValue); //ResolveLava(); litOutput.Text = string.Empty; }
public void Given_simple_workflow_runned_twice() { _service = new WorkflowService(); var instance1 = _service.Get<FooWorkflow>(SimpleWorkflowKey); try { instance1.Crash(); } catch (Exception ex) { _exception = ex; } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); Guid?workflowGuid = GetAttributeValue(action, "Workflow", true).AsGuidOrNull(); if (workflowGuid.HasValue) { using (var newRockContext = new RockContext()) { var workflowService = new WorkflowService(newRockContext); var workflow = workflowService.Get(workflowGuid.Value); if (workflow != null) { string status = GetAttributeValue(action, "Status").ResolveMergeFields(GetMergeFields(action)); workflow.Status = status; workflow.AddLogEntry(string.Format("Status set to '{0}' by another workflow: {1}", status, action.Activity.Workflow)); newRockContext.SaveChanges(); action.AddLogEntry(string.Format("Set Status to '{0}' on another workflow: {1}", status, workflow)); bool processNow = GetAttributeValue(action, "ProcessNow").AsBoolean(); if (processNow) { var processErrors = new List <string>(); if (!workflowService.Process(workflow, out processErrors)) { action.AddLogEntry("Error(s) occurred processing target workflow: " + processErrors.AsDelimited(", ")); } } return(true); } } action.AddLogEntry("Could not find selected workflow."); } else { action.AddLogEntry("Workflow attribute was not set."); return(true); // Continue processing in this case } return(false); }
/// <summary> /// Job that will close workflows. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var workflowTypeGuids = dataMap.GetString("WorkflowTypes").Split(',').Select(Guid.Parse).ToList(); int? expirationAge = dataMap.GetString("ExpirationAge").AsIntegerOrNull(); string closeStatus = dataMap.GetString("CloseStatus"); var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var qry = workflowService.Queryable().AsNoTracking() .Where(w => workflowTypeGuids.Contains(w.WorkflowType.Guid) && w.ActivatedDateTime.HasValue && !w.CompletedDateTime.HasValue); if (expirationAge.HasValue) { var expirationDate = RockDateTime.Now.AddMinutes(0 - expirationAge.Value); qry = qry.Where(w => w.CreatedDateTime <= expirationDate); } // Get a list of workflows to expire so we can open a new context in the loop var workflowIds = qry.Select(w => w.Id).ToList(); foreach (var workflowId in workflowIds) { rockContext = new RockContext(); workflowService = new WorkflowService(rockContext); var workflow = workflowService.Get(workflowId); if (workflow.IsNull()) { continue; } workflow.MarkComplete(); workflow.Status = closeStatus; rockContext.SaveChanges(); } context.Result = string.Format("{0} workflows were closed", workflowIds.Count); }
protected void btnReopen_Command(object sender, CommandEventArgs e) { using (RockContext rockContext = new RockContext()) { WorkflowService workflowService = new WorkflowService(rockContext); Workflow workflow = workflowService.Get(e.CommandArgument.ToString().AsInteger()); if (workflow != null && !workflow.IsActive) { workflow.Status = "Active"; workflow.CompletedDateTime = null; // Find the summary activity and activate it. WorkflowActivityType workflowActivityType = workflow.WorkflowType.ActivityTypes.Where(at => at.Name.Contains("Summary")).FirstOrDefault(); WorkflowActivity workflowActivity = WorkflowActivity.Activate(WorkflowActivityTypeCache.Get(workflowActivityType.Id, rockContext), workflow, rockContext); } rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Delete event of the gWorkflows 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 gWorkflows_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); WorkflowService workflowService = new WorkflowService(rockContext); Workflow workflow = workflowService.Get(e.RowKeyId); if (workflow != null) { string errorMessage; if (!workflowService.CanDelete(workflow, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } workflowService.Delete(workflow); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Delete event of the gWorkflows 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 gWorkflows_Delete(object sender, RowEventArgs e) { RockTransactionScope.WrapTransaction(() => { WorkflowService workflowService = new WorkflowService(); Workflow workflow = workflowService.Get((int)e.RowKeyValue); if (workflow != null) { string errorMessage; if (!workflowService.CanDelete(workflow, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } workflowService.Delete(workflow, CurrentPersonId); workflowService.Save(workflow, CurrentPersonId); } }); BindGrid(); }
private bool CanDelete(int id) { RockContext rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var workflow = workflowService.Get(id); string errorMessage; if (workflow == null) { ShowAlert("This item could not be found", ModalAlertType.Information); return(false); } if (!workflowService.CanDelete(workflow, out errorMessage)) { ShowAlert(errorMessage, ModalAlertType.Warning); return(false); } workflowService.Delete(workflow); rockContext.SaveChanges(); return(true); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); RockContext rockContext = new RockContext(); Guid? workflowGuid = PageParameter("Workflow").AsGuidOrNull(); Guid? landingActionGuid = PageParameter("LandingAction").AsGuidOrNull(); string documentId = PageParameter("document_id"); if (workflowGuid == null) { nbError.Text = "Error: A valid workflow parameter is required."; nbError.Visible = true; return; } if (landingActionGuid == null) { nbError.Text = "Error: A valid landing action parameter is required."; nbError.Visible = true; return; } if (string.IsNullOrWhiteSpace(documentId)) { nbError.Text = "Error: A valid DocumentId parameter is required."; nbError.Visible = true; return; } // Load the Workflow WorkflowService workflowService = new WorkflowService(rockContext); Workflow workflow = workflowService.Get(workflowGuid.Value); if (workflow == null) { nbError.Text = "Error: A valid workflow parameter is required."; nbError.Visible = true; return; } workflow.LoadAttributes(); WorkflowAction landingAction = workflow.Activities.SelectMany(a => a.Actions.Where(x => x.ActionType.Guid == landingActionGuid)).FirstOrDefault(); if (landingAction == null) { nbError.Text = "Error: A valid landing action parameter is required."; nbError.Visible = true; return; } landingAction.LoadAttributes(); // Load the attributes from the landing action and then update them var documentIdAttribute = AttributeCache.Get(ActionComponent.GetActionAttributeValue(landingAction, "SignNowDocumentId").AsGuid(), rockContext); if (documentIdAttribute.EntityTypeId == new Workflow().TypeId) { workflow.SetAttributeValue(documentIdAttribute.Key, documentId); } else if (documentIdAttribute.EntityTypeId == new WorkflowActivity().TypeId) { landingAction.Activity.SetAttributeValue(documentIdAttribute.Key, documentId); } var pdfSignedAttribute = AttributeCache.Get(ActionComponent.GetActionAttributeValue(landingAction, "PDFSigned").AsGuid(), rockContext); if (pdfSignedAttribute.EntityTypeId == new Workflow().TypeId) { workflow.SetAttributeValue(pdfSignedAttribute.Key, "True"); } else if (pdfSignedAttribute.EntityTypeId == new WorkflowActivity().TypeId) { landingAction.Activity.SetAttributeValue(documentIdAttribute.Key, "True"); } workflow.SaveAttributeValues(); landingAction.SaveAttributeValues(); // Process the workflow List <string> errorMessages; var output = workflowService.Process(workflow, out errorMessages); if (!HttpContext.Current.Response.IsRequestBeingRedirected) { // Redirect back to the workflow NavigateToLinkedPage("WorkflowEntryPage", new Dictionary <string, string>() { { "WorkflowTypeId", workflow.TypeId.ToString() }, { "WorkflowGuid", workflowGuid.ToString() } }); } }
protected void bbTest_Click(object sender, EventArgs e) { nbInstructions.Visible = false; try { // Save lava test string for future use. SetUserPreference(_USER_PREF_KEY, ceLava.Text); using (var rockContext = new RockContext()) { PersonService personService = new PersonService(rockContext); Person person; if (ppPerson.PersonId.HasValue) { person = personService.Get(ppPerson.PersonId ?? -1, false); } else { person = CurrentPerson; } // Get Lava mergeFields.Add("Person", person); if (gpGroups != null && gpGroups.SelectedValueAsInt().HasValue) { GroupService groupService = new GroupService(rockContext); mergeFields.Add("Group", groupService.Get(gpGroups.SelectedValueAsInt() ?? -1)); } if (ddlWorkflows != null && ddlWorkflows.Items.Count > 0 && ddlWorkflows.SelectedValueAsInt().HasValue) { WorkflowService workflowService = new WorkflowService(rockContext); if (mergeFields.ContainsKey("Workflow")) { mergeFields.Remove("Workflow"); } if (ddlWorkflows.SelectedValueAsInt() != null) { mergeFields.Add("Workflow", workflowService.Get(ddlWorkflows.SelectedValueAsInt() ?? -1)); } } if (ddlRegistrations != null && ddlRegistrations.Items.Count > 0 && ddlRegistrations.SelectedValueAsInt().HasValue) { if (mergeFields.ContainsKey("RegistrationInstance")) { mergeFields.Remove("RegistrationInstance"); } if (mergeFields.ContainsKey("Registration")) { mergeFields.Remove("RegistrationInstance"); } RegistrationService registrationService = new RegistrationService(rockContext); if (ddlRegistrations.SelectedValueAsInt() != null) { var registration = registrationService.Get(ddlRegistrations.SelectedValueAsInt() ?? -1); if (registration != null) { mergeFields.Add("RegistrationInstance", registration.RegistrationInstance); mergeFields.Add("Registration", registration); } } } ResolveLava(); } } catch (Exception ex) { //LogException( ex ); litDebug.Text = "<pre>" + ex.StackTrace + "</pre>"; } }
private static void Session2(WorkflowService reg) { var instance = reg.Get<PingForewerWorkflow>("PingForewer"); instance.Ping(); }
/// <summary> /// Updates the workflow, closing it if the reportStatus is blank and the recommendation is "Invitation Expired". /// </summary> /// <param name="id">The identifier.</param> /// <param name="recommendation">The recommendation.</param> /// <param name="reportLink">The report link.</param> /// <param name="reportStatus">The report status.</param> /// <param name="rockContext">The rock context.</param> private static void UpdateWorkflow(int id, string recommendation, string documentId, string reportStatus, RockContext rockContext) { // Make sure the workflow isn't locked (i.e., it's still being worked on by the 'SendRequest' method of the workflow // BackgroundCheckComponent) before we start working on it -- especially before we load the workflow's attributes. var lockObject = _lockObjects.GetOrAdd(id, new object()); lock ( lockObject ) { var workflowService = new WorkflowService(rockContext); var workflow = workflowService.Get(id); if (workflow != null && workflow.IsActive) { workflow.LoadAttributes(); if (workflow.Attributes.ContainsKey("ReportStatus")) { if (workflow.GetAttributeValue("ReportStatus").IsNotNullOrWhiteSpace() && reportStatus.IsNullOrWhiteSpace()) { // Don't override current values if Webhook is older than current values return; } } if (workflow.Attributes.ContainsKey("Report")) { if (workflow.GetAttributeValue("Report").IsNotNullOrWhiteSpace() && documentId.IsNullOrWhiteSpace()) { // Don't override current values if Webhook is older than current values return; } } // Save the recommendation if (!string.IsNullOrWhiteSpace(recommendation)) { if (SaveAttributeValue(workflow, "ReportRecommendation", recommendation, FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { } if (reportStatus.IsNullOrWhiteSpace() && recommendation == "Invitation Expired") { workflow.CompletedDateTime = RockDateTime.Now; workflow.MarkComplete(recommendation); } } // Save the report link if (documentId.IsNotNullOrWhiteSpace()) { int entityTypeId = EntityTypeCache.Get(typeof(Checkr)).Id; if (SaveAttributeValue(workflow, "Report", $"{entityTypeId},{documentId}", FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { } } if (!string.IsNullOrWhiteSpace(reportStatus)) { // Save the status if (SaveAttributeValue(workflow, "ReportStatus", reportStatus, FieldTypeCache.Get(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext, new Dictionary <string, string> { { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" } })) { } } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); workflow.SaveAttributeValues(rockContext); foreach (var activity in workflow.Activities) { activity.SaveAttributeValues(rockContext); } }); } rockContext.SaveChanges(); List <string> workflowErrors; workflowService.Process(workflow, out workflowErrors); _lockObjects.TryRemove(id, out _); // we no longer need that lock for this workflow } }
/// <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) { var rockContext = new RockContext(); var service = new WorkflowService(rockContext); ParseControls(rockContext, true); Workflow dbWorkflow = null; if (Workflow != null) { dbWorkflow = service.Get(Workflow.Id); if (dbWorkflow != null) { if (!dbWorkflow.CompletedDateTime.HasValue && Workflow.CompletedDateTime.HasValue) { dbWorkflow.AddLogEntry("Workflow Manually Completed."); dbWorkflow.CompletedDateTime = Workflow.CompletedDateTime; } else if (dbWorkflow.CompletedDateTime.HasValue && !Workflow.CompletedDateTime.HasValue) { dbWorkflow.AddLogEntry("Workflow Manually Re-Activated."); dbWorkflow.CompletedDateTime = null; } if (dbWorkflow.Name.Trim() != Workflow.Name.Trim()) { dbWorkflow.AddLogEntry(string.Format("Workflow name manually changed from '{0}' to '{0}'.", dbWorkflow.Name, tbName.Text)); dbWorkflow.Name = Workflow.Name; } if (dbWorkflow.Status.Trim() != Workflow.Status.Trim()) { dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.Status, tbStatus.Text)); dbWorkflow.Status = Workflow.Status; } if (!dbWorkflow.InitiatorPersonAliasId.Equals(Workflow.InitiatorPersonAliasId)) { dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.InitiatorPersonAlias != null ? dbWorkflow.InitiatorPersonAlias.Person.FullName : "", Workflow.InitiatorPersonAlias != null ? Workflow.InitiatorPersonAlias.Person.FullName : "")); dbWorkflow.InitiatorPersonAlias = Workflow.InitiatorPersonAlias; dbWorkflow.InitiatorPersonAliasId = Workflow.InitiatorPersonAliasId; } if (!Page.IsValid || !dbWorkflow.IsValid) { return; } foreach (var activity in Workflow.Activities) { if (!activity.IsValid) { return; } foreach (var action in activity.Actions) { if (!action.IsValid) { return; } } } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); dbWorkflow.LoadAttributes(rockContext); foreach (var attributeValue in Workflow.AttributeValues) { dbWorkflow.SetAttributeValue(attributeValue.Key, Workflow.GetAttributeValue(attributeValue.Key)); } dbWorkflow.SaveAttributeValues(rockContext); WorkflowActivityService workflowActivityService = new WorkflowActivityService(rockContext); WorkflowActionService workflowActionService = new WorkflowActionService(rockContext); var activitiesInUi = new List <Guid>(); var actionsInUI = new List <Guid>(); foreach (var activity in Workflow.Activities) { activitiesInUi.Add(activity.Guid); foreach (var action in activity.Actions) { actionsInUI.Add(action.Guid); } } // delete WorkflowActions that were removed in the UI foreach (var action in workflowActionService.Queryable() .Where(a => a.Activity.WorkflowId.Equals(dbWorkflow.Id) && !actionsInUI.Contains(a.Guid))) { workflowActionService.Delete(action); } // delete WorkflowActivities that aren't assigned in the UI anymore foreach (var activity in workflowActivityService.Queryable() .Where(a => a.WorkflowId.Equals(dbWorkflow.Id) && !activitiesInUi.Contains(a.Guid))) { workflowActivityService.Delete(activity); } rockContext.SaveChanges(); // add or update WorkflowActivities(and Actions) that are assigned in the UI foreach (var editorWorkflowActivity in Workflow.Activities) { // Add or Update the activity type WorkflowActivity workflowActivity = dbWorkflow.Activities.FirstOrDefault(a => a.Guid.Equals(editorWorkflowActivity.Guid)); if (workflowActivity == null) { workflowActivity = new WorkflowActivity(); workflowActivity.ActivityTypeId = editorWorkflowActivity.ActivityTypeId; dbWorkflow.Activities.Add(workflowActivity); } workflowActivity.AssignedPersonAliasId = editorWorkflowActivity.AssignedPersonAliasId; workflowActivity.AssignedGroupId = editorWorkflowActivity.AssignedGroupId; workflowActivity.ActivatedDateTime = editorWorkflowActivity.ActivatedDateTime; workflowActivity.LastProcessedDateTime = editorWorkflowActivity.LastProcessedDateTime; if (!workflowActivity.CompletedDateTime.HasValue && editorWorkflowActivity.CompletedDateTime.HasValue) { workflowActivity.AddLogEntry("Activity Manually Completed."); workflowActivity.CompletedDateTime = RockDateTime.Now; } if (workflowActivity.CompletedDateTime.HasValue && !editorWorkflowActivity.CompletedDateTime.HasValue) { workflowActivity.AddLogEntry("Activity Manually Re-Activated."); workflowActivity.CompletedDateTime = null; } // Save Activity Type rockContext.SaveChanges(); // Save ActivityType Attributes workflowActivity.LoadAttributes(rockContext); foreach (var attributeValue in editorWorkflowActivity.AttributeValues) { workflowActivity.SetAttributeValue(attributeValue.Key, editorWorkflowActivity.GetAttributeValue(attributeValue.Key)); } workflowActivity.SaveAttributeValues(rockContext); foreach (var editorWorkflowAction in editorWorkflowActivity.Actions) { WorkflowAction workflowAction = workflowActivity.Actions.FirstOrDefault(a => a.Guid.Equals(editorWorkflowAction.Guid)); if (workflowAction == null) { // New action workflowAction = new WorkflowAction(); workflowAction.ActionTypeId = editorWorkflowAction.ActionTypeId; workflowActivity.Actions.Add(workflowAction); } workflowAction.LastProcessedDateTime = editorWorkflowAction.LastProcessedDateTime; workflowAction.FormAction = editorWorkflowAction.FormAction; if (!workflowAction.CompletedDateTime.HasValue && editorWorkflowAction.CompletedDateTime.HasValue) { workflowAction.AddLogEntry("Action Manually Completed."); workflowAction.CompletedDateTime = RockDateTime.Now; } if (workflowAction.CompletedDateTime.HasValue && !editorWorkflowAction.CompletedDateTime.HasValue) { workflowAction.AddLogEntry("Action Manually Re-Activated."); workflowAction.CompletedDateTime = null; } } // Save action updates rockContext.SaveChanges(); } }); } Workflow = service .Queryable("WorkflowType,Activities.ActivityType,Activities.Actions.ActionType") .FirstOrDefault(w => w.Id == Workflow.Id); var errorMessages = new List <string>(); service.Process(Workflow, out errorMessages); } ShowReadonlyDetails(); }
/// <summary> /// Job that will close workflows. /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var workflowTypeGuids = dataMap.GetString("WorkflowTypes").Split(',').Select(Guid.Parse).ToList(); int? expirationAge = dataMap.GetString("ExpirationAge").AsIntegerOrNull(); bool lastUsed = dataMap.GetString("ExpirationCalcLastUsed").AsBoolean(); string closeStatus = dataMap.GetString("CloseStatus"); var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var workflowActionService = new WorkflowActionService(rockContext); var qry = workflowService.Queryable().AsNoTracking() .Where(w => workflowTypeGuids.Contains(w.WorkflowType.Guid) && w.ActivatedDateTime.HasValue && !w.CompletedDateTime.HasValue); if (expirationAge.HasValue) { var expirationDate = RockDateTime.Now.AddMinutes(0 - expirationAge.Value); if (!lastUsed) { qry = qry.Where(w => w.CreatedDateTime <= expirationDate); } else { var formEntityTypeId = EntityTypeCache.GetId(typeof(Rock.Workflow.Action.UserEntryForm)); qry = qry.Where(w => w.Activities .Where(a => a.CompletedDateTime == null) .SelectMany(a => a.Actions) .Where(ac => ac.CompletedDateTime == null && ac.CreatedDateTime <= expirationDate && ac.ActionType.EntityTypeId == formEntityTypeId) .Any()); } } // Get a list of workflows to expire so we can open a new context in the loop var workflowIds = qry.Select(w => w.Id).ToList(); foreach (var workflowId in workflowIds) { rockContext = new RockContext(); workflowService = new WorkflowService(rockContext); var workflow = workflowService.Get(workflowId); if (workflow.IsNull()) { continue; } workflow.MarkComplete(); workflow.Status = closeStatus; rockContext.SaveChanges(); } context.Result = string.Format("{0} workflows were closed", workflowIds.Count); }
/// <summary> /// Renders the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="result">The result.</param> public override void Render(Context context, TextWriter result) { // first ensure that entity commands are allowed in the context if (!this.IsAuthorized(context)) { result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name)); base.Render(context, result); return; } var attributes = new Dictionary <string, string>(); string parmWorkflowType = null; string parmWorkflowName = null; string parmWorkflowId = null; string parmActivityType = null; /* Parse the markup text to pull out configuration parameters. */ var parms = ParseMarkup(_markup, context); foreach (var p in parms) { if (p.Key.ToLower() == "workflowtype") { parmWorkflowType = p.Value; } else if (p.Key.ToLower() == "workflowname") { parmWorkflowName = p.Value; } else if (p.Key.ToLower() == "workflowid") { parmWorkflowId = p.Value; } else if (p.Key.ToLower() == "activitytype") { parmActivityType = p.Value; } else { attributes.AddOrReplace(p.Key, p.Value); } } /* Process inside a new stack level so our own created variables do not * persist throughout the rest of the workflow. */ context.Stack(() => { using (var rockContext = new RockContext()) { WorkflowService workflowService = new WorkflowService(rockContext); Rock.Model.Workflow workflow = null; WorkflowActivity activity = null; /* They provided a WorkflowType, so we need to kick off a new workflow. */ if (parmWorkflowType != null) { string type = parmWorkflowType; string name = parmWorkflowName ?? string.Empty; WorkflowTypeCache workflowType = null; /* Get the type of workflow */ if (type.AsGuidOrNull() != null) { workflowType = WorkflowTypeCache.Read(type.AsGuid()); } else if (type.AsIntegerOrNull() != null) { workflowType = WorkflowTypeCache.Read(type.AsInteger()); } /* Try to activate the workflow */ if (workflowType != null) { workflow = Rock.Model.Workflow.Activate(workflowType, parmWorkflowName); /* Set any workflow attributes that were specified. */ foreach (var attr in attributes) { if (workflow.Attributes.ContainsKey(attr.Key)) { workflow.SetAttributeValue(attr.Key, attr.Value.ToString()); } } if (workflow != null) { List <string> errorMessages; workflowService.Process(workflow, out errorMessages); if (errorMessages.Any()) { context["Error"] = string.Join("; ", errorMessages.ToArray()); } context["Workflow"] = workflow; } else { context["Error"] = "Could not activate workflow."; } } else { context["Error"] = "Workflow type not found."; } } /* They instead provided a WorkflowId, so we are working with an existing Workflow. */ else if (parmWorkflowId != null) { string id = parmWorkflowId.ToString(); /* Get the workflow */ if (id.AsGuidOrNull() != null) { workflow = workflowService.Get(id.AsGuid()); } else if (id.AsIntegerOrNull() != null) { workflow = workflowService.Get(id.AsInteger()); } if (workflow != null) { if (workflow.CompletedDateTime == null) { /* Currently we cannot activate an activity in a workflow that is currently * being processed. The workflow is held in-memory so the activity we would * activate would not show up for the processor and probably never run. */ if (!workflow.IsProcessing) { bool hasError = false; /* If they provided an ActivityType parameter then we need to activate * a new activity in the workflow. */ if (parmActivityType != null) { string type = parmActivityType.ToString(); WorkflowActivityTypeCache activityType = null; /* Get the type of activity */ if (type.AsGuidOrNull() != null) { activityType = WorkflowActivityTypeCache.Read(type.AsGuid()); } else if (type.AsIntegerOrNull() != null) { activityType = WorkflowActivityTypeCache.Read(type.AsInteger()); } if (activityType != null) { activity = WorkflowActivity.Activate(activityType, workflow); /* Set any workflow attributes that were specified. */ foreach (var attr in attributes) { if (activity.Attributes.ContainsKey(attr.Key)) { activity.SetAttributeValue(attr.Key, attr.Value.ToString()); } } } else { context["Error"] = "Activity type was not found."; hasError = true; } } /* Process the existing Workflow. */ if (!hasError) { List <string> errorMessages; workflowService.Process(workflow, out errorMessages); if (errorMessages.Any()) { context["Error"] = string.Join("; ", errorMessages.ToArray()); } context["Workflow"] = workflow; context["Activity"] = activity; } } else { context["Error"] = "Cannot activate activity on workflow that is currently being processed."; } } else { context["Error"] = "Workflow has already been completed."; } } else { context["Error"] = "Workflow not found."; } } else { context["Error"] = "Must specify one of WorkflowType or WorkflowId."; } RenderAll(NodeList, context, result); } }); }