locked
Workflows for deleted records are showing as Cancelled RRS feed

  • Question

  • I had it in my head that deleting a record which contains a waiting workflow would remove the workflow.

    I am seeing the workflow remain behind in a cancelled state.  This is not doing any harm but is a little untidy.

    My workflow fires on a specific Status Reason change.  I'd like it to either mark itself and successful on the delete of the parent record (which will cause a cleanup) or remove itself.

    A wait branch would be an option but I don't think I can detect a delete in the clause of the branch?

    Wednesday, December 3, 2014 10:41 AM

All replies

  • Hi Gordon,

    You can write a plugin to delete the waiting workflows like below and register it on the pre-operation stage and delete message of the particular entity.

    public class RemoveRunningWorkflows : IPlugin
        {
            public void Execute(IServiceProvider serviceProvider)
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);
                OrganizationServiceContext serviceContext = new OrganizationServiceContext(service);
    
                if (context.MessageName.ToLower() == "delete")
                {
                    EntityReference entity = (EntityReference)context.InputParameters["Target"];
                    QueryExpression query = new QueryExpression("asyncoperation");
                    ConditionExpression entityExpression = new ConditionExpression("regardingobjectid", ConditionOperator.Equal, entity.Id);
                    ConditionExpression statusExpression = new ConditionExpression("statuscode", ConditionOperator.Equal, 10);//waiting
                    FilterExpression filter = new FilterExpression(LogicalOperator.And);
                    filter.AddCondition(entityExpression);
                    filter.AddCondition(statusExpression);
                    query.Criteria.AddFilter(filter);
                    var systemJobs = service.RetrieveMultiple(query);
                    foreach (var workflow in systemJobs.Entities)
                    {
                        service.Delete("asyncoperation", workflow.Id);
                    }
                }
            }
        }

    Thanks

    Sachith


    Sachith Chandrasiri

    Thursday, December 4, 2014 9:18 AM