Thursday, December 20, 2012

MS CRM 2011: How to cancel/postpone Workfow Instance using C#

Today I had a task to cancel about 25k instances of the same workflow. Of course it was possible to create Advanced Find View and go through 100 pages cancelling all workflows on the page. But I’m too lazy and I know C# to do that manually.
First code that I wrote used SetState message to Cancel change state of workflow instance but during first lunch I’ve got an exception that SetState message is not applicable for AsyncOperation entity. I went to SDK and found following explanation:
Updates an asynchronous operation (system job). Typically, you would update only the AsyncOperation.StateCode or AsyncOperation.PostponeUntil attributes of the asynchronous operation (system job). You can also call the IOrganizationService.Update method.
So I rewrote my code using Update message:
Entity operation = new Entity("asyncoperation")
{
    Id = <Put identifier of Workflow Instance here>
};

operation["statecode"] = new OptionSetValue(3);
operation["statuscode"] = new OptionSetValue(32);

organizationservice.Update(operation);

UPD: Here is the code that allows to postpone asyncoperation till some date:

Entity operation = new Entity("asyncoperation")
{
    Id = <Put identifier of Workflow Instance here>
};

operation["postponeuntil"] = DateTime.Now.AddDays(1);

operation["statecode"] = new OptionSetValue(1);
operation["statuscode"] = new OptionSetValue(10);

organizationservice.Update(operation);