public Process ( Workflow workflow, List |
||
workflow | Workflow | The workflow. |
errorMessages | List |
The error messages. |
return | bool |
private void LaunchWorkflow(WorkflowTypeCache workflowType, FinancialTransaction transaction) { if (workflowType != null && (workflowType.IsActive ?? true)) { using (var rockContext = new RockContext()) { string workflowName = transaction.TransactionCode; if (transaction.AuthorizedPersonAliasId != null) { var person = new PersonAliasService(rockContext).GetPerson(transaction.AuthorizedPersonAliasId.Value); if (person != null) { workflowName = person.FullName; } } var workflowService = new WorkflowService(rockContext); var workflow = Rock.Model.Workflow.Activate(workflowType, workflowName, rockContext); if (workflow != null) { List <string> workflowErrors; workflowService.Process(workflow, transaction, out workflowErrors); } } } }
/// <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, Attendance attendance, PersonAlias pagePersonAlias, WorkflowType pageWorkflowType) { if (pageWorkflowType != null) { var workflow = Rock.Model.Workflow.Activate(pageWorkflowType, pageWorkflowType.WorkTerm, rockContext); if (workflow != null) { workflow.SetAttributeValue("Person", attendance.PersonAlias.Guid); workflow.SetAttributeValue("PagePerson", pagePersonAlias.Guid); var workflowService = new Rock.Model.WorkflowService(rockContext); List <string> workflowErrors; if (workflowService.Process(workflow, attendance, out workflowErrors)) { if (workflow.Id != 0) { if (workflow.HasActiveEntryForm(CurrentPerson)) { var qryParam = new Dictionary <string, string>(); qryParam.Add("WorkflowTypeId", pageWorkflowType.Id.ToString()); qryParam.Add("WorkflowId", workflow.Id.ToString()); NavigateToLinkedPage("WorkflowEntryPage", qryParam); } else { mdWorkflowLaunched.Show(string.Format("A '{0}' workflow has been started.", pageWorkflowType.Name), ModalAlertType.Information); } } else { mdWorkflowLaunched.Show(string.Format("A '{0}' workflow was processed (but not persisted).", pageWorkflowType.Name), ModalAlertType.Information); } } else { mdWorkflowLaunched.Show("Workflow Processing Error(s):<ul><li>" + workflowErrors.AsDelimited("</li><li>") + "</li></ul>", ModalAlertType.Information); } return; } } Dictionary <string, string> qParams = new Dictionary <string, string>(); qParams.Add("AttendanceId", attendance.Id.ToString()); qParams.Add("PagePersonId", pagePersonAlias.Person.Id.ToString()); NavigateToLinkedPage("WorkflowEntryPage", qParams); }
/// <summary> /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" /> /// fires that is associated with the <see cref="IJob" />. /// </summary> /// <param name="context">The execution context.</param> /// <remarks> /// The implementation may wish to set a result object on the /// JobExecutionContext before this method exits. The result itself /// is meaningless to Quartz, but may be informative to /// <see cref="IJobListener" />s or /// <see cref="ITriggerListener" />s that are watching the job's /// execution. /// </remarks> public virtual void Execute( IJobExecutionContext context ) { var service = new WorkflowService(); foreach ( var workflow in service.GetActive() ) { if ( !workflow.LastProcessedDateTime.HasValue || DateTime.Now.Subtract( workflow.LastProcessedDateTime.Value ).TotalSeconds >= workflow.WorkflowType.ProcessingIntervalSeconds ) { var errorMessages = new List<string>(); service.Process( workflow, null, out errorMessages ); } } }
/// <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> /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" /> /// fires that is associated with the <see cref="IJob" />. /// </summary> /// <param name="context">The execution context.</param> /// <remarks> /// The implementation may wish to set a result object on the /// JobExecutionContext before this method exits. The result itself /// is meaningless to Quartz, but may be informative to /// <see cref="IJobListener" />s or /// <see cref="ITriggerListener" />s that are watching the job's /// execution. /// </remarks> public virtual void Execute( IJobExecutionContext context ) { foreach ( var workflowId in new WorkflowService( new RockContext() ).GetActive().Select(a => a.Id).ToList() ) { // create a new rockContext and service for every workflow to prevent a build-up of Context.ChangeTracker.Entries() var rockContext = new RockContext(); var workflowService = new WorkflowService( rockContext ); var workflow = workflowService.Queryable( "WorkflowType" ).FirstOrDefault( a => a.Id == workflowId ); if ( workflow != null ) { if ( !workflow.LastProcessedDateTime.HasValue || RockDateTime.Now.Subtract( workflow.LastProcessedDateTime.Value ).TotalSeconds >= ( workflow.WorkflowType.ProcessingIntervalSeconds ?? 0 ) ) { var errorMessages = new List<string>(); workflowService.Process( workflow, out errorMessages ); } } } }
private void LaunchWorkflow( WorkflowType workflowType, FinancialTransaction transaction ) { if ( workflowType != null ) { using ( var rockContext = new RockContext() ) { string workflowName = transaction.TransactionCode; if ( transaction.AuthorizedPersonAliasId != null ) { var person = new PersonAliasService( rockContext ).GetPerson( transaction.AuthorizedPersonAliasId.Value ); if ( person != null ) { workflowName = person.FullName; } } var workflowService = new WorkflowService( rockContext ); var workflow = Rock.Model.Workflow.Activate( workflowType, workflowName, rockContext ); if ( workflow != null ) { List<string> workflowErrors; workflowService.Process( workflow, transaction, out workflowErrors ); } } } }
/// <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(); }
protected void lbProfileNext_Click( object sender, EventArgs e ) { // setup merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); mergeFields.Add( "PersonId", hfPersonId.Value ); mergeFields.Add( "FirstName", tbFirstName.Text ); mergeFields.Add( "LastName", tbLastName.Text ); mergeFields.Add( "StreetAddress", acAddress.Street1 ); mergeFields.Add( "City", acAddress.City ); mergeFields.Add( "State", acAddress.State ); mergeFields.Add( "PostalCode", acAddress.PostalCode ); mergeFields.Add( "Country", acAddress.Country ); mergeFields.Add( "Email", tbEmail.Text ); mergeFields.Add( "HomePhone", pnbHomePhone.Text ); mergeFields.Add( "MobilePhone", pnbHomePhone.Text ); mergeFields.Add( "BirthDate", dpBirthdate.Text ); mergeFields.Add( "OtherUpdates", tbOtherUpdates.Text ); // if an email was provided email results RockContext rockContext = new RockContext(); if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "UpdateEmail" ) ) ) { var receiptEmail = new SystemEmailService( rockContext ).Get( new Guid( GetAttributeValue( "UpdateEmail" ) ) ); if ( receiptEmail != null ) { var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "PublicApplicationRoot" ); var recipients = new List<RecipientData>(); recipients.Add( new RecipientData( null, mergeFields ) ); Email.Send( receiptEmail.Guid, recipients, appRoot ); } } // launch workflow if configured if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "WorkflowType" ) ) ) { var workflowTypeService = new WorkflowTypeService( rockContext ); var workflowService = new WorkflowService( rockContext ); var workflowType = workflowTypeService.Get( new Guid( GetAttributeValue( "WorkflowType" ) ) ); if ( workflowType != null ) { var workflow = Rock.Model.Workflow.Activate( workflowType, "Kiosk Update Info" ); // set attributes workflow.SetAttributeValue( "PersonId", hfPersonId.Value ); workflow.SetAttributeValue( "FirstName", tbFirstName.Text ); workflow.SetAttributeValue( "LastName", tbLastName.Text ); workflow.SetAttributeValue( "StreetAddress", acAddress.Street1 ); workflow.SetAttributeValue( "City", acAddress.City ); workflow.SetAttributeValue( "State", acAddress.State ); workflow.SetAttributeValue( "PostalCode", acAddress.PostalCode ); workflow.SetAttributeValue( "Country", acAddress.Country ); workflow.SetAttributeValue( "Email", tbEmail.Text ); workflow.SetAttributeValue( "HomePhone", pnbHomePhone.Text ); workflow.SetAttributeValue( "MobilePhone", pnbHomePhone.Text ); workflow.SetAttributeValue( "BirthDate", dpBirthdate.Text ); workflow.SetAttributeValue( "OtherUpdates", tbOtherUpdates.Text ); // lauch workflow List<string> workflowErrors; workflowService.Process( workflow, out workflowErrors ); } } HidePanels(); pnlComplete.Visible = true; lCompleteMessage.Text = GetAttributeValue( "CompleteMessageLava" ).ResolveMergeFields( mergeFields ); bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean(); if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) ) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } }
/// <summary> /// Launch a specific workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="workflowTrigger">The connection workflow.</param> /// <param name="target">The name.</param> private bool LaunchWorkflow(RockContext rockContext, Step target, StepWorkflowTrigger workflowTrigger) { if (target == null || workflowTrigger == null) { mdWorkflowResult.Show("Workflow Processing Failed:<ul><li>The workflow parameters are invalid.</li></ul>", ModalAlertType.Information); return(false); } var workflowType = workflowTrigger.WorkflowType; if (workflowType == null || !(workflowType.IsActive ?? true)) { mdWorkflowResult.Show("Workflow Processing Failed:<ul><li>This workflow is unavailable.</li></ul>", ModalAlertType.Information); return(false); } if (!workflowType.IsAuthorized(Authorization.VIEW, CurrentPerson)) { mdWorkflowResult.Show("Workflow Processing Failed:<ul><li>You are not authorized to access this workflow.</li></ul>", ModalAlertType.Information); return(false); } var workflowTypeCache = WorkflowTypeCache.Get(workflowType); var workflow = Rock.Model.Workflow.Activate(workflowTypeCache, workflowTrigger.WorkflowType.WorkTerm, rockContext); if (workflow == null) { mdWorkflowResult.Show("Workflow Processing Failed:<ul><li>The workflow could not be activated.</li></ul>", ModalAlertType.Information); return(false); } var workflowService = new Rock.Model.WorkflowService(rockContext); List <string> workflowErrors; var processed = workflowService.Process(workflow, target, out workflowErrors); if (processed) { if (workflow.HasActiveEntryForm(CurrentPerson)) { // If the workflow has a user entry form that can be displayed for the current user, show it now. // Note that for a non-persisted workflow, a new instance of the workflow will be created after the user form is saved. var qryParam = new Dictionary <string, string>(); qryParam.Add("WorkflowTypeId", workflowType.Id.ToString()); if (workflow.Id != 0) { qryParam.Add("WorkflowId", workflow.Id.ToString()); } var entryPage = this.GetAttributeValue(AttributeKey.WorkflowEntryPage); if (string.IsNullOrWhiteSpace(entryPage)) { mdWorkflowResult.Show("A Workflow Entry Page has not been configured for this block.", ModalAlertType.Alert); return(false); } NavigateToLinkedPage(AttributeKey.WorkflowEntryPage, qryParam); return(false); } else if (workflow.Id != 0) { // The workflow has been started and persisted, but it has no requirement for user interaction. mdWorkflowResult.Show(string.Format("A '{0}' workflow has been started.", workflowType.Name), ModalAlertType.Information); return(true); } else { // The workflow has run to completion, and it has no requirement for user interaction. mdWorkflowResult.Show(string.Format("A '{0}' workflow was processed.", workflowType.Name), ModalAlertType.Information); return(true); } } else { mdWorkflowResult.Show("Workflow Processing Failed:<ul><li>" + workflowErrors.AsDelimited("</li><li>") + "</li></ul>", ModalAlertType.Information); } return(false); }
/// <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 ); } } } }
protected void LaunchWorkflow(Guid workflowGuid, Dictionary<string, string> attributes) { RockContext _rockContext = new RockContext(); WorkflowService _workflowService = new WorkflowService(_rockContext); WorkflowTypeService _workflowTypeService = new WorkflowTypeService(_rockContext); WorkflowType _workflowType = _workflowTypeService.Get(workflowGuid); Workflow _workflow = Rock.Model.Workflow.Activate(_workflowType, "New Test" + _workflowType.WorkTerm); foreach (KeyValuePair<string, string> attribute in attributes) { _workflow.SetAttributeValue(attribute.Key, attribute.Value); } List<string> errorMessages; if ( _workflowService.Process( _workflow, out errorMessages ) ) { // If the workflow type is persisted, save the workflow if (_workflow.IsPersisted || _workflowType.IsPersisted) { if (_workflow.Id == 0) { _workflowService.Add(_workflow); } _rockContext.WrapTransaction(() => { _rockContext.SaveChanges(); _workflow.SaveAttributeValues(_rockContext); foreach (var activity in _workflow.Activities) { activity.SaveAttributeValues(_rockContext); } }); } } }
/// <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, Attendance attendance, PersonAlias pagePersonAlias, WorkflowType pageWorkflowType ) { if ( pageWorkflowType != null ) { var workflow = Rock.Model.Workflow.Activate( pageWorkflowType, pageWorkflowType.WorkTerm, rockContext ); if ( workflow != null ) { workflow.SetAttributeValue( "Person", attendance.PersonAlias.Guid ); workflow.SetAttributeValue( "PagePerson", pagePersonAlias.Guid ); var workflowService = new Rock.Model.WorkflowService( rockContext ); List<string> workflowErrors; if ( workflowService.Process( workflow, attendance, out workflowErrors ) ) { if ( workflow.Id != 0 ) { if ( workflow.HasActiveEntryForm( CurrentPerson ) ) { var qryParam = new Dictionary<string, string>(); qryParam.Add( "WorkflowTypeId", pageWorkflowType.Id.ToString() ); qryParam.Add( "WorkflowId", workflow.Id.ToString() ); NavigateToLinkedPage( "WorkflowEntryPage", qryParam ); } else { mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow has been started.", pageWorkflowType.Name ), ModalAlertType.Information ); } } else { mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow was processed (but not persisted).", pageWorkflowType.Name ), ModalAlertType.Information ); } } else { mdWorkflowLaunched.Show( "Workflow Processing Error(s):<ul><li>" + workflowErrors.AsDelimited( "</li><li>" ) + "</li></ul>", ModalAlertType.Information ); } return; } } Dictionary<string, string> qParams = new Dictionary<string, string>(); qParams.Add( "AttendanceId", attendance.Id.ToString() ); qParams.Add( "PagePersonId", pagePersonAlias.Person.Id.ToString() ); NavigateToLinkedPage( "WorkflowEntryPage", qParams ); }
/// <summary> /// Triggers all the workflows of the given triggerType for the given entity item. /// </summary> /// <param name="item">The item.</param> /// <param name="triggerType">Type of the trigger.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private bool TriggerWorkflows( ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias ) { IEntity entity = item.Entity; Dictionary<string, PropertyInfo> properties = null; using ( var rockContext = new RockContext() ) { var workflowTypeService = new WorkflowTypeService( rockContext ); var workflowService = new WorkflowService( rockContext ); // Look at each trigger for this entity and for the given trigger type // and see if it's a match. foreach ( var trigger in TriggerCache.Triggers( entity.TypeName, triggerType ).Where( t => t.IsActive == true ) ) { bool match = true; // If a qualifier column was given, then we need to check the previous or current qualifier value // otherwise it's just an automatic match. if ( !string.IsNullOrWhiteSpace( trigger.EntityTypeQualifierColumn ) ) { // Get and cache the properties https://lotsacode.wordpress.com/2010/04/13/reflection-type-getproperties-and-performance/ // (Note: its possible that none of the triggers need them, so future TODO could be to // bypass all this in that case. if ( properties == null ) { properties = new Dictionary<string, PropertyInfo>(); foreach ( PropertyInfo propertyInfo in entity.GetType().GetProperties() ) { properties.Add( propertyInfo.Name.ToLower(), propertyInfo ); } } match = IsQualifierMatch( item, properties, trigger ); } // If we found a matching trigger, then fire it; otherwise do nothing. if ( match ) { // If it's one of the pre or immediate triggers, fire it immediately; otherwise queue it. if ( triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete || triggerType == WorkflowTriggerType.ImmediatePostSave ) { var workflowType = workflowTypeService.Get( trigger.WorkflowTypeId ); if ( workflowType != null ) { var workflow = Rock.Model.Workflow.Activate( workflowType, trigger.WorkflowName ); List<string> workflowErrors; if ( !workflowService.Process( workflow, entity, out workflowErrors ) ) { SaveErrorMessages.AddRange( workflowErrors ); return false; } } } else { var transaction = new Rock.Transactions.WorkflowTriggerTransaction(); transaction.Trigger = trigger; transaction.Entity = entity.Clone(); transaction.PersonAlias = personAlias; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } } } return true; }
/// <summary> /// Activates and processes a workflow activity. If the workflow has not yet been activated, it will /// also be activated /// </summary> /// <param name="activityName">Name of the activity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> protected bool ProcessActivity( string activityName, out List<string> errorMessages ) { errorMessages = new List<string>(); Guid? guid = GetAttributeValue( "WorkflowType" ).AsGuidOrNull(); if ( guid.HasValue ) { using ( var rockContext = new RockContext() ) { var workflowTypeService = new WorkflowTypeService( rockContext ); var workflowService = new WorkflowService( rockContext ); var workflowType = workflowTypeService.Queryable( "ActivityTypes" ) .Where( w => w.Guid.Equals( guid.Value ) ) .FirstOrDefault(); if ( workflowType != null ) { if ( CurrentWorkflow == null ) { CurrentWorkflow = Rock.Model.Workflow.Activate( workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext ); if ( IsOverride ) { CurrentWorkflow.SetAttributeValue( "Override", "True" ); } } var activityType = workflowType.ActivityTypes.Where( a => a.Name == activityName ).FirstOrDefault(); if ( activityType != null ) { WorkflowActivity.Activate( activityType, CurrentWorkflow, rockContext ); if ( workflowService.Process( CurrentWorkflow, CurrentCheckInState, out errorMessages ) ) { // Keep workflow active for continued processing CurrentWorkflow.CompletedDateTime = null; return true; } } else { errorMessages.Add( string.Format( "Workflow type does not have a '{0}' activity type", activityName ) ); } } else { errorMessages.Add( "Invalid Workflow Type" ); } } } return false; }
/// <summary> /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" /> /// fires that is associated with the <see cref="IJob" />. /// </summary> /// <param name="context">The execution context.</param> /// <remarks> /// The implementation may wish to set a result object on the /// JobExecutionContext before this method exits. The result itself /// is meaningless to Quartz, but may be informative to /// <see cref="IJobListener" />s or /// <see cref="ITriggerListener" />s that are watching the job's /// execution. /// </remarks> public virtual void Execute( IJobExecutionContext context ) { int workflowsProcessed = 0; int workflowErrors = 0; int workflowExceptions = 0; var ProcessingErrors = new List<string>(); var exceptionMsgs = new List<string>(); foreach ( var workflowId in new WorkflowService( new RockContext() ) .GetActive() .Select( w => w.Id ) .ToList() ) { try { // create a new rockContext and service for every workflow to prevent a build-up of Context.ChangeTracker.Entries() var rockContext = new RockContext(); var workflowService = new WorkflowService( rockContext ); var workflow = workflowService.Queryable( "WorkflowType" ).FirstOrDefault( a => a.Id == workflowId ); if ( workflow != null ) { try { if ( !workflow.LastProcessedDateTime.HasValue || RockDateTime.Now.Subtract( workflow.LastProcessedDateTime.Value ).TotalSeconds >= ( workflow.WorkflowType.ProcessingIntervalSeconds ?? 0 ) ) { var errorMessages = new List<string>(); var processed = workflowService.Process( workflow, out errorMessages ); if ( processed ) { workflowsProcessed++; } else { workflowErrors++; ProcessingErrors.Add( string.Format( "{0} [{1}] - {2} [{3}]: {4}", workflow.WorkflowType.Name, workflow.WorkflowTypeId, workflow.Name, workflow.Id, errorMessages.AsDelimited( ", " ) ) ); } } } catch ( Exception ex ) { string workflowDetails = string.Format( "{0} [{1}] - {2} [{3}]", workflow.WorkflowType.Name, workflow.WorkflowTypeId, workflow.Name, workflow.Id ); exceptionMsgs.Add( workflowDetails + ": " + ex.Message ); throw new Exception( "Exception occurred processing workflow: " + workflowDetails, ex ); } } } catch ( Exception ex ) { ExceptionLogService.LogException( ex, null ); workflowExceptions++; } } var resultMsg = new StringBuilder(); resultMsg.AppendFormat( "{0} workflows processed", workflowsProcessed ); if ( workflowErrors > 0 ) { resultMsg.AppendFormat( ", {0} workflows reported an error", workflowErrors ); } if ( workflowExceptions > 0 ) { resultMsg.AppendFormat( ", {0} workflows caused an exception", workflowExceptions ); } if ( ProcessingErrors.Any() ) { resultMsg.Append( Environment.NewLine + ProcessingErrors.AsDelimited( Environment.NewLine ) ); } if ( exceptionMsgs.Any() ) { throw new Exception( "One or more exceptions occurred processing workflows..." + Environment.NewLine + exceptionMsgs.AsDelimited( Environment.NewLine ) ); } context.Result = resultMsg.ToString(); }
/// <summary> /// Starts the workflow. /// </summary> /// <param name="workflowService">The workflow service.</param> /// <param name="workflowType">Type of the workflow.</param> /// <param name="attributes">The attributes.</param> /// <param name="workflowNameSuffix">The workflow instance name suffix (the part that is tacked onto the end fo the name to distinguish one instance from another).</param> protected void StartWorkflow( WorkflowService workflowService, WorkflowType workflowType, Dictionary<string, string> attributes, string workflowNameSuffix ) { // launch workflow if configured if ( workflowType != null ) { var workflow = Rock.Model.Workflow.Activate( workflowType, "SendCreditCardExpiration " + workflowNameSuffix ); // set attributes foreach ( KeyValuePair<string, string> attribute in attributes ) { workflow.SetAttributeValue( attribute.Key, attribute.Value ); } // lauch workflow List<string> workflowErrors; workflowService.Process( workflow, out workflowErrors ); } }