Programmatically Fire a Workflow in Dynamics CRM 2011

Roshan Mehta, 08 August 2012

Your Dynamics CRM 2011 implementation might have custom business logic split between plug-ins and workflows. There may be instances where you need to fire a workflow from your custom plug-in logic. There are a couple of approaches here – you could set a value for an entity via your plug-in which is configured to trigger the workflow or you could use other methods in the SDK to directly execute the workflow. In this post, I will show you how to execute a workflow programmatically.

Let’s assume our CRM implementation is designed for service management. We have already had a large number of cases migrated from a legacy system into CRM, and a new workflow has just been built to route newly created high priority Cases to a “high priority” Queue. The problem here is that any existing Cases will not automatically be routed since our workflow runs on create of new Cases.

We need to build a Console Application to route the existing Cases to the correct Queue. To simplify the development, we can grab all Cases created before our workflow was built and execute the workflow on those records. The following code snippet achieves this.

QueryExpression query = new QueryExpression { EntityName = "incident" };   
query.Criteria.AddCondition("createdon", ConditionOperator.OnOrBefore, DateTime.Today);
query.Criteria.AddCondition("prioritycode", ConditionOperator.Equal, 1);    //high priority

results = _sdk.RetrieveMultiple(query);
results.Entities.ToList().ForEach(a =>
    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest
        EntityId = a.Id,
        WorkflowId = workflowId

    _sdk.Execute(request);  //run the workflow

One important thing to note is that the workflow we are executing must be marked as an on-demand or child workflow; otherwise you will receive an error.

Programmatically Fire a Workflow in CRM 2011