Wednesday, February 8, 2017

How to cancel the workflows using SharePoint object model.

Solution: Using below code you can cancel the running workflows. it will work for default  and third part workflows like Nintex, K2 etc. First to cancel the active workflow must and should we have to use SPSecurity.RunWithElevatedPrivileges method.
Note: Please change list name and pass the item id value in GetItemById() method as per your logic.
              SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        using (SPSite spsite = new SPSite(SPContext.Current.Web.Site.ID))
                        {

                            using (SPWeb spweb = spsite.OpenWeb())
                            {

                               SPWorkflowManager spmanager = spsite.WorkflowManager;

                                //pass the list item id value in GetitemById method.

                               SPListItem spitem = spweb.Lists["SampleList"].GetItemById(27);

                               spitem.Web.AllowUnsafeUpdates = true;
                    foreach (SPWorkflow workflow in spmanager.GetItemActiveWorkflows(spitem))
                    {

                                    SPWorkflowManager.CancelWorkflow(workflow);

                    }

                                spitem.Web.AllowUnsafeUpdates = false;

                            }

                        }


                    });

No comments:

Post a Comment