Thursday, 1 September 2016

Get all Suspended or Terminated Workflow instances in SharePoint Online

Here is some quick code I put together today to get all Suspended workflow instances on a list in SharePoint Online.

This code can be used to get all instances for a given status. (Suspended, Terminated etc.)

I have used the SharePoint Online CSOM August 2016 Update for this code:
http://dev.office.com/blogs/new-sharepoint-csom-version-released-for-Office-365-august-2016-updated

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WorkflowServices;
using System;
using System.Linq;
using System.Security;
namespace WFExplorer
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "https://tenant.sharepoint.com/sites/intranet";
string userName = "admin@tenant.onmicrosoft.com";
string password = "adminpassword";
string listTitle = "MyList";
string workflowName = "MyWorkflow";
var workflowStatus = WorkflowStatus.Suspended; // WorkflowStatus.Terminated or any value from the WorkflowStatus enumeration.
var clientContext = GetClientContext(siteUrl, userName, password);
Web web = clientContext.Web;
Guid listGUID= GetListGUID(clientContext, listTitle);
//Get the workflow subscription (workflow definition)
var wfServicesManager = new WorkflowServicesManager(clientContext, web);
var wfSubscriptionService = wfServicesManager.GetWorkflowSubscriptionService();
var wfSubscriptions = wfSubscriptionService.EnumerateSubscriptionsByList(listGUID);
clientContext.Load(wfSubscriptions, wfSubs => wfSubs.Where(wfSub => wfSub.Name == workflowName));
clientContext.ExecuteQuery();
var wfSubscription = wfSubscriptions.First();
//Get the workflow instances
var wfInstanceService = wfServicesManager.GetWorkflowInstanceService();
var wfInstanceCollection = wfInstanceService.Enumerate(wfSubscription);
clientContext.Load(wfInstanceCollection, wfInstances => wfInstances.Where(wfI => wfI.Status == workflowStatus));
clientContext.ExecuteQuery();
//List all instances with the selected status.
foreach (var wfInstance in wfInstanceCollection)
{
Console.WriteLine(wfInstance.Properties["Microsoft.SharePoint.ActivationProperties.CurrentItemUrl"]);
}
Console.ReadKey();
}
private static ClientContext GetClientContext(string siteUrl, string userName, string password)
{
ClientContext clientContext = new ClientContext(siteUrl);
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);
return clientContext;
}
private static Guid GetListGUID(ClientContext context, string listTitle)
{
var list = context.Web.Lists.GetByTitle(listTitle);
context.Load(list, l => l.Id);
context.ExecuteQuery();
return list.Id;
}
}
}
view raw WFInstances.cs hosted with ❤ by GitHub

Thanks for reading!

No comments: