Workflows are an extremely useful tool in Microsoft Dynamics CRM. In today’s blog, we’ll discuss how to execute a workflow using the CRM ExecuteWorkflowRequest message in a console application.
In this scenario, a workflow has failed a couple of times. Instead of re-running this workflow manually, we can use the code below to automate the process.
The screenshot below shows the System Jobs view of the workflow named Workflow Test that has failed.
The ExecuteWorkflowRequest message can be used to execute any given workflow. The ExecuteWorkflowMessage requires two values:
Note: You must ensure that the WorkflowId is of an active workflow.
You can manually set these values by using the CRM interface to attain each of these values and simply call the ExecuteWorkflowRequest in the console application.
The following code automates this process by doing the following:
- Query the System Jobs (asyncoperation entity) to retrieve failed worklows by the workflow name.
- Check to see if the workflow hasn’t already succeeded.
- Select one failed workflow to rerun.
Console application code
After the console application executed, the failed workflow was rerun.
System Jobs view after console application was executed and workflow succeeded
When a workflow is created, CRM creates two entries in the workflow entity. When retrieving failed workflows from the asyncoperation entity, you will notice the workflowactivationid attribute has a reference to the workflow. If you attempt to use this value as the WorkflowId, you will get an error stating “Workflow must be in a published state” when the ExecuteWorkflowRequest message is executed.
The GetWorkflowId helper method is used to retrieve the published workflow by querying the workflow entity and retrieving the parentworkflowid attribute. This value will correspond to the WorkflowId that you will get when using the CRM interface.
You will want to expand the logic to determine a distinct set of failed workflows and regarding entity that have not succeeded.
There you have it! An easy way to automatically execute a workflow using a console application. If you are looking for help with your workflows, PowerObjects can help! Contact us for more information.