Wednesday, October 13, 2010

Cancelling Unsuccessful Workflows through Coding

Just Call thsi method by Passing..1 WorkflowName.2.Guid id of the Entity at which its Fired.3.crmserviceObject
eg:
KillWorkflow("SynchLyrisToCrmAnuj", new Guid("7DAA4DD0-70AC-DF11-9575-40618664DD9A"), service);

Method:

public static void KillWorkflow(string workflowName, Guid entityId, CrmHelper service)
{
string error = "";

//CrmService service = Utils.GetCrm4Service(null, false);

ColumnSet colsWf = new ColumnSet(new string[] { "name", "statuscode", "asyncoperationid", "regardingobjectid" });


ConditionExpression conditionName = new ConditionExpression();
conditionName.AttributeName = "name";
conditionName.Values = new string[] { workflowName };

ConditionExpression conditionRegardingObjectId = new ConditionExpression();
conditionRegardingObjectId.AttributeName = "regardingobjectid";
conditionRegardingObjectId.Values = new string[] { entityId.ToString() };

FilterExpression filter = new FilterExpression();
filter.AddCondition(conditionName);
filter.AddCondition(conditionRegardingObjectId);
filter.FilterOperator = LogicalOperator.And;

QueryExpression query = new QueryExpression();
query.ColumnSet = colsWf;
query.EntityName = EntityName.asyncoperation.ToString();
query.Criteria = filter;

BusinessEntityCollection results = service.RetrieveMultiple(query);

if (results.BusinessEntities.Count > 0)
{
for (int i = 0; i < results.BusinessEntities.Count; i++)
{
asyncoperation singleWorkflowInstance = (asyncoperation)results.BusinessEntities[i];
if (singleWorkflowInstance.statuscode.Value == AsyncOperationStatus.WaitingForResources ||
singleWorkflowInstance.statuscode.Value == AsyncOperationStatus.Waiting ||
singleWorkflowInstance.statuscode.Value == AsyncOperationStatus.Pausing ||
singleWorkflowInstance.statuscode.Value == AsyncOperationStatus.InProgress)
{
try
{
Status statusCanceled = new Status();
statusCanceled.Value = AsyncOperationStatus.Canceled;

AsyncOperationStateInfo state = new AsyncOperationStateInfo();
state.Value = AsyncOperationState.Completed;

SetStateWorkflowRequest request = new SetStateWorkflowRequest();
singleWorkflowInstance.statuscode = statusCanceled;
singleWorkflowInstance.statecode = state;

TargetUpdateAsyncOperation operation = new TargetUpdateAsyncOperation();
operation.AsyncOperation = singleWorkflowInstance;

UpdateRequest update = new UpdateRequest();
update.Target = operation;
UpdateResponse updated = (UpdateResponse)service.Execute(update);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
error = "KillWorkflow Error " + ex.Message + "" + ex.StackTrace;
}
catch (Exception ex)
{
error = "KillWorkflow Error " + ex.Message + "" + ex.StackTrace;
}
}
}

if (error != null && !error.Equals(""))
{
throw new Exception(error);
}
}
}

Its working fine..........cheers.!!

No comments:

Post a Comment