Cancelling workflow programatically RRS feed

  • Question

  • hi

    I just want to cancel a workflow programatically using c#. I'm using the following code to do that


     using (ServiceContext serviceContext = new ServiceContext(service))

                    var processes = (from p in serviceContext.CreateQuery<AsyncOperation>()
                                     where p.PrimaryEntityType == "entity name"
                                           && p.RegardingObjectId.Id == "entityId"
                                           && p.Name == "WorkflowName"
                                           (p.StatusCode.Value == 10 ||       // Waiting
                                            p.StatusCode.Value == 20 ||       // In Process
                                            p.StatusCode.Value == 0)          // Waiting For Resources
                                     select new AsyncOperation { Id = p.Id, StateCode = p.StateCode, StatusCode = p.StatusCode }).FirstOrDefault();

                     var fetchXml=@"<fetch mapping='logical' version='1.0'>
                               <entity name='asyncoperation'>
                               <attribute name='statecode' />
                               <attribute name='statuscode' />
                               <condition attribute='asyncoperationid' operator='eq' value='{0}' />
                     EntityCollection op = service.RetrieveMultiple(new FetchExpression(string.Format(fetchXml, processes.Id.ToString())));

                     if (op.Entities.Count == 1)
                         AsyncOperation o = op.Entities[0].ToEntity<AsyncOperation>();
                         o.StateCode = AsyncOperationState.Completed;
                         o.StatusCode = new OptionSetValue(32);

    Even if i'm setting the StatusCode as 32 system is showing the workflow as succeeded. I just want to show the status as 'Cancelled'

    Please help.

    Wednesday, August 13, 2014 2:57 PM

All replies

  • We wanted to do something similar and provide custom errors back to the Workflow process.  The response we got from Microsoft was the Async Service does not accept inputs from a running process.  Thus, unless something has changed in more recent versions of CRM 2013 you may be out of luck.  If you are using CRM 2013, perhaps you could accomplish your goal using an Action rather than a Workflow?  An Action would allow you to return an actionable response value.
    Wednesday, August 13, 2014 8:54 PM
  • Based on the SDK documentation, only changes to the statecode and postponeuntil attributes are permitted. One option could be to postpone the workflows to some point far in the future, but that doesn't seem very satisfactory

    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Thursday, August 14, 2014 9:14 AM