Example #1
1
 /// <summary>
 /// Returns a workflow subscription (associations) for a list
 /// </summary>
 /// <param name="list"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static WorkflowSubscription GetWorkflowSubscription(this List list, string name)
 {
     var servicesManager = new WorkflowServicesManager(list.Context, list.ParentWeb);
     var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
     var subscriptions = subscriptionService.EnumerateSubscriptionsByList(list.Id);
     var subscriptionQuery = from sub in subscriptions where sub.Name == name select sub;
     var subscriptionResults = list.Context.LoadQuery(subscriptionQuery);
     list.Context.ExecuteQueryRetry();
     var subscription = subscriptionResults.FirstOrDefault();
     return subscription;
 }
        public static void CreateAssociation(ref ClientContext clientContext, ref WorkflowServicesManager wfsm, Guid workflowDefinitionId, Guid listId, Guid historyListId, Guid taskListId)
        {
            WorkflowSubscriptionService subservice = wfsm.GetWorkflowSubscriptionService();

            Console.WriteLine();
            Console.WriteLine("Creating workflow association...");

            WorkflowSubscription newSubscription = new WorkflowSubscription(clientContext)
            {
                DefinitionId = workflowDefinitionId,
                Enabled      = true,
                Name         = "Custom Association" + DateTime.Now
            };

            // define startup options
            newSubscription.EventTypes = new List <string> {
                "ItemAdded", "ItemUpdated", "WorkflowStart"
            };

            //define history & task list
            newSubscription.SetProperty("HistoryListId", historyListId.ToString());
            newSubscription.SetProperty("TaskListId", taskListId.ToString());

            //create association
            subservice.PublishSubscriptionForList(newSubscription, listId);
            clientContext.ExecuteQuery();
            Console.WriteLine("Workflow association created!");
            Console.ReadLine();
        }
        public override void ExecuteCmdlet()
        {
            var SelectedWeb = this.ClientContext.Web;


            var list = List.GetList(SelectedWeb);


            if (!string.IsNullOrEmpty(WorkflowName))
            {
                var servicesManager   = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var deploymentService = servicesManager.GetWorkflowInstanceService();

                WorkflowSubscription workflowSubscription = list.GetWorkflowSubscription(WorkflowName);
                WriteSubscriptionInstances(list, deploymentService, workflowSubscription);
            }
            else
            {
                var servicesManager   = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var deploymentService = servicesManager.GetWorkflowInstanceService();

                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                var subscriptions       = subscriptionService.EnumerateSubscriptionsByList(list.Id);
                ClientContext.Load(subscriptions);
                ClientContext.ExecuteQueryRetry();

                foreach (var subscription in subscriptions)
                {
                    WriteSubscriptionInstances(list, deploymentService, subscription);
                }
            }


            WriteObject(Instances);
        }
Example #4
0
        public static void Test(ClientContext context)
        {
            var workflowServiceManager      = new WorkflowServicesManager(context, context.Web);
            var workflowDeploymentService   = workflowServiceManager.GetWorkflowDeploymentService();
            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptions();

            context.Load(workflowDeploymentService);
            context.Load(workflowSubscriptionService);
            context.Load(subscriptions);
            context.ExecuteQuery();
            var subscription       = subscriptions.First(temp => temp.Name == "7777");
            var workflowDefination = workflowDeploymentService.GetDefinition(subscription.Id);

            context.Load(workflowDefination);
            context.ExecuteQuery();

            var folderUrl = workflowDefination.Properties["Definition.Path"];
            var folder    = context.Web.GetFolderByServerRelativeUrl(folderUrl);

            context.Load(folder);
            context.Load(folder.Files);
            context.ExecuteQuery();
            foreach (var file in folder.Files)
            {
                context.Load(file.Properties);
                context.Load(file.ListItemAllFields);
                context.ExecuteQuery();
            }
        }
        public List <SPWorkflow> GetWorkflows(ClientContext cc, string listName)
        {
            try
            {
                var result = new List <SPWorkflow>();
                var list   = cc.Web.GetListByTitle(listName);

                try
                {
                    var wfServicesManager        = new WorkflowServicesManager(cc, cc.Web);
                    var wfSubscriptionService    = wfServicesManager.GetWorkflowSubscriptionService();
                    var wfSubscriptionCollection = wfSubscriptionService.EnumerateSubscriptionsByList(list.Id);
                    cc.Load(wfSubscriptionCollection);
                    cc.ExecuteQuery();
                    foreach (var wfSubscription in wfSubscriptionCollection)
                    {
                        if (wfSubscription.Name.Contains("Previous Version"))
                        {
                            continue;
                        }
                        //2013
                        result.Add(new SPWorkflow()
                        {
                            ListTitle    = listName,
                            WebUrl       = cc.Url,
                            WorkflowName = wfSubscription.Name,
                            WorkflowType = WorkflowType.SP2013
                        });
                    }
                }
                catch (Exception wfEx)
                {
                    logger.Log(LogLevel.Error, wfEx, $"Site:{cc.Url}");
                }
                //2010
                var wfAssociations = cc.LoadQuery(list.WorkflowAssociations.Include(w => w.Name, w => w.Id, w => w.InternalName, w => w.IsDeclarative));
                cc.ExecuteQuery();
                foreach (var wfAssociation in wfAssociations)
                {
                    if (wfAssociation.Name.Contains("Previous Version"))
                    {
                        continue;
                    }
                    //2010
                    result.Add(new SPWorkflow()
                    {
                        ListTitle    = listName,
                        WebUrl       = cc.Url,
                        WorkflowName = wfAssociation.Name,
                        WorkflowType = WorkflowType.SP2010
                    });
                }
                return(result);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex, $"Site:{cc.Url}");
                throw ex;
            }
        }
        /// <summary>
        /// List all workflow associations for the specified workflow.
        /// </summary>
        public static void ListAllAssociations(ref ClientContext clientConext,
                                               ref WorkflowServicesManager wfServicesManager)
        {
            WorkflowSubscriptionService subService = wfServicesManager.GetWorkflowSubscriptionService();

            Console.WriteLine();
            Console.WriteLine("Listing all workflow associations: ");

            // get all associations
            WorkflowSubscriptionCollection wfSubscriptions = subService.EnumerateSubscriptions();

            //WorkflowSubscriptionCollection wfSubscriptions = subService.EnumerateSubscriptionsByDefinition(definitionId);
            //WorkflowSubscriptionCollection wfSubscriptions = subService.EnumerateSubscriptionsByList(listId);
            //WorkflowSubscriptionCollection wfSubscriptions = subService.EnumerateSubscriptionsByEventSource(eventSourceId);

            clientConext.Load(wfSubscriptions);
            clientConext.ExecuteQuery();

            // write all associations out
            foreach (var wfSubscription in wfSubscriptions)
            {
                Console.WriteLine("{0} - {1}",
                                  wfSubscription.Id,
                                  wfSubscription.Name
                                  );
            }
        }
        /// <summary>
        /// Starts a new instance of a workflow definition against the current web site
        /// </summary>
        /// <param name="web">The target web site</param>
        /// <param name="subscriptionId">The ID of the workflow subscription to start</param>
        /// <param name="payload">Any input argument for the workflow instance</param>
        /// <returns>The ID of the just started workflow instance</returns>
        public static Guid StartWorkflowInstance(this Web web, Guid subscriptionId, IDictionary <String, Object> payload)
        {
            Guid result = Guid.Empty;

            var clientContext   = web.Context as ClientContext;
            var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var workflowSubscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptions();

            clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Id == subscriptionId));
            clientContext.ExecuteQueryRetry();

            var subscription = subscriptions.FirstOrDefault();

            if (subscription != null)
            {
                var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
                var startAction             = workflowInstanceService.StartWorkflow(subscription, payload);
                clientContext.ExecuteQueryRetry();

                result = startAction.Value;
            }

            return(result);
        }
        public List <PSHWorkflowDefinition> GetWorkflowDefinitions()
        {
            List <PSHWorkflowDefinition> lstWFDefinitions = new List <PSHWorkflowDefinition>();

            using (var clientContext = new ClientContext(_PWAUrl))
            {
                var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

                // connect to the deployment service
                var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();
                Web oWeb = clientContext.Web;

                // get all installed workflows
                var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
                clientContext.Load(publishedWorkflowDefinitions);
                clientContext.ExecuteQuery();
                foreach (var pubwfDef in publishedWorkflowDefinitions)
                {
                    Console.WriteLine("Name:{0} \nID: {1}", pubwfDef.DisplayName, pubwfDef.Id.ToString());
                    Console.WriteLine("---------------------------------------");

                    PSHWorkflowDefinition objWFDefinition = new PSHWorkflowDefinition()
                    {
                        WFDefinitionId   = pubwfDef.Id,
                        WFDefinitionXAML = pubwfDef.Xaml,
                        WFName           = pubwfDef.DisplayName
                    };

                    lstWFDefinitions.Add(objWFDefinition);
                }
            }
            return(lstWFDefinitions);
        }
        /// <summary>
        /// Install a new workflow definition.
        /// </summary>
        public static void InstallWorkflow(ref ClientContext clientConext,
                                           ref WorkflowServicesManager wfServicesManager,
                                           Guid listId)
        {
            // connect to deployment service
            WorkflowDeploymentService depService = wfServicesManager.GetWorkflowDeploymentService();

            string workflowStamp = DateTime.Now.ToString();

            WorkflowDefinition workflowDefinition = new WorkflowDefinition(clientConext);

            workflowDefinition.Xaml            = _validWorkflow;
            workflowDefinition.DisplayName     = "Custom-" + workflowStamp;
            workflowDefinition.Description     = "new custom workflow created " + workflowStamp;
            workflowDefinition.RestrictToType  = "List"; // ["List" | "Site" | ""]
            workflowDefinition.RestrictToScope = listId.ToString();

            Console.WriteLine();
            Console.WriteLine("Creating new workflow");
            Console.WriteLine("   saving workflow...");
            ClientResult <Guid> result = depService.SaveDefinition(workflowDefinition);

            clientConext.ExecuteQuery();

            Console.WriteLine("   publishing workflow...");
            depService.PublishDefinition(result.Value);
            clientConext.ExecuteQuery();

            Console.WriteLine("Workflow published... use SharePoint Designer 2013 to see it.");
        }
        /// <summary>
        /// Validate a bad workflow.
        /// </summary>
        public static void ValidateBadWorkflow(ref ClientContext clientConext,
                                               ref WorkflowServicesManager wfServicesManager)
        {
            // connect to deployment service
            WorkflowDeploymentService depService = wfServicesManager.GetWorkflowDeploymentService();

            Console.WriteLine();
            Console.WriteLine("Validating workflow:");
            Console.WriteLine(_invalidWorkflow);

            ClientResult <string> result = depService.ValidateActivity(_invalidWorkflow);

            clientConext.ExecuteQuery();

            Console.WriteLine();
            Console.Write("Validation result: ");
            if (string.IsNullOrEmpty(result.Value))
            {
                Console.WriteLine("workflow validated");
            }
            else
            {
                Console.WriteLine("error: " + result.Value);
            }
        }
        public static void ProvisionWorkFlow()
        {
            templateSiteClientContext = new ClientContext(templateSiteUrl);

            templateSiteClientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord);

            var workflowServicesManager = new WorkflowServicesManager(templateSiteClientContext, templateSiteClientContext.Web);

            // connect to the deployment service 
            var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();

            // get all installed workflows
            var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
            templateSiteClientContext.Load(publishedWorkflowDefinitions);
            templateSiteClientContext.ExecuteQuery();

            // display list of all installed workflows
            WorkflowDefinition currentWorkFlow = publishedWorkflowDefinitions.Where(flow => flow.DisplayName.Equals("BBH Document Atestation")).First();
            if (currentWorkFlow != null)
            {
                var workFlowTemplate = currentWorkFlow;
                //var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();

                //// get all workflow associations
                //var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(currentWorkFlow.Id);
                //templateSiteClientContext.Load(workflowAssociations);
                //templateSiteClientContext.ExecuteQuery();

                //foreach (var association in workflowAssociations)
                //{
                //    Console.WriteLine("{0} - {1}",
                //      association.Id, association.Name);

                //}
                //var binderSiteUrl = "https://chennaitillidsoft.sharepoint.com/sites/POC/spotlight/HeroControlDev/";
                binderSiteClientContext = new ClientContext(binderSiteUrl);
                binderSiteClientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord);


                //Construct object with workflow template info
                WorkflowTemplateInfo solutionInfo = new WorkflowTemplateInfo();
                var solutionPath = "https://chennaitillidsoft.sharepoint.com/sites/developer5/SiteAssets/BBH Document Atestation.wsp";
                solutionInfo.PackageFilePath = solutionPath;
                //PackageName is mandatory
                solutionInfo.PackageName = Path.GetFileNameWithoutExtension(solutionPath);
                //Guid is automatically predefined in template file (.wsp)
                solutionInfo.PackageGuid = workFlowTemplate.Id;
                //Workflow feature Id is need to activate workflow in the web
                //solutionInfo.FeatureId = workFlowTemplate.;
                //Init workflow template deployer
                using (AddWorkFlowFormExistingTemplate workflowDeployer = new AddWorkFlowFormExistingTemplate(binderSiteClientContext))
                {
                    //Provisioning workflow resources
                    workflowDeployer.DeployWorkflowSolution(solutionPath);
                    //Activates workflow template
                    workflowDeployer.ActivateWorkflowSolution(solutionInfo);
                }
            }
            Console.ReadLine();
        }
Example #12
0
        /// <summary>
        /// Show all running workflow instances
        /// </summary>
        public static void ListAllInstances(ref ClientContext clientConext,
                                            ref WorkflowServicesManager wfServicesManager,
                                            Guid listId)
        {
            WorkflowInstanceService instService = wfServicesManager.GetWorkflowInstanceService();

            Console.WriteLine();
            Console.WriteLine("Show all running workflow instances...");

            int listItemId = 1;
            WorkflowInstanceCollection wfInstances = instService.EnumerateInstancesForListItem(listId, listItemId);

            // WorkflowInstanceCollection wfInstances = instService.EnumerateInstancesForSite(); // get instances running on the current site

            clientConext.Load(wfInstances);
            clientConext.ExecuteQuery();
            foreach (var wfInstance in wfInstances)
            {
                Console.WriteLine("{0} - {1} - {2}|{3}",
                                  wfInstance.Id,
                                  wfInstance.LastUpdated,
                                  wfInstance.Status,
                                  wfInstance.UserStatus);
            }
        }
        /// <summary>
        /// Starts a new instance of a workflow definition against the current item
        /// </summary>
        /// <param name="item">The target item</param>
        /// <param name="subscriptionId">The ID of the workflow subscription to start</param>
        /// <param name="payload">Any input argument for the workflow instance</param>
        /// <returns>The ID of the just started workflow instance</returns>
        public static Guid StartWorkflowInstance(this ListItem item, Guid subscriptionId, IDictionary <String, Object> payload)
        {
            Guid result = Guid.Empty;

            var parentList = item.EnsureProperty(i => i.ParentList);

            var clientContext   = item.Context as ClientContext;
            var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var workflowSubscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(parentList.Id);

            clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Id == subscriptionId));
            clientContext.ExecuteQueryRetry();

            var subscription = subscriptions.FirstOrDefault();

            if (subscription != null)
            {
                var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
                var startAction             = workflowInstanceService.StartWorkflowOnListItem(subscription, item.Id, payload);
                clientContext.ExecuteQueryRetry();

                result = startAction.Value;
            }

            return(result);
        }
Example #14
0
        protected override void ExecuteCmdlet()
        {
            int ListItemID;

            if (ListItem != null)
            {
                if (ListItem.Id != uint.MinValue)
                {
                    ListItemID = (int)ListItem.Id;
                }
                else if (ListItem.Item != null)
                {
                    ListItemID = ListItem.Item.Id;
                }
                else
                {
                    throw new PSArgumentException("No valid list item specified.", nameof(ListItem));
                }
            }
            else
            {
                throw new PSArgumentException("List Item is required", nameof(ListItem));
            }

            var subscription = Subscription.GetWorkflowSubscription(SelectedWeb)
                               ?? throw new PSArgumentException($"No workflow subscription found for '{Subscription}'", nameof(Subscription));

            var inputParameters = new Dictionary <string, object>();

            WorkflowServicesManager workflowServicesManager = new WorkflowServicesManager(ClientContext, SelectedWeb);
            WorkflowInstanceService instanceService         = workflowServicesManager.GetWorkflowInstanceService();

            instanceService.StartWorkflowOnListItem(subscription, ListItemID, inputParameters);
            ClientContext.ExecuteQueryRetry();
        }
Example #15
0
        public static Guid AddWorkflowDefinition(this Web web, WorkflowDefinition definition, bool publish = true)
        {
            var servicesManager   = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            WorkflowDefinition def = new WorkflowDefinition(web.Context);

            def.AssociationUrl = definition.AssociationUrl;
            def.Description    = definition.Description;
            def.DisplayName    = definition.DisplayName;
            def.DraftVersion   = definition.DraftVersion;
            def.FormField      = definition.FormField;
            def.Id             = definition.Id != Guid.Empty ? definition.Id : Guid.NewGuid();
            foreach (var prop in definition.Properties)
            {
                def.SetProperty(prop.Key, prop.Value);
            }
            def.RequiresAssociationForm = definition.RequiresAssociationForm;
            def.RequiresInitiationForm  = definition.RequiresInitiationForm;
            def.RestrictToScope         = definition.RestrictToScope;
            def.RestrictToType          = definition.RestrictToType;
            def.Xaml = definition.Xaml;

            var result = deploymentService.SaveDefinition(def);

            web.Context.ExecuteQueryRetry();

            if (publish)
            {
                deploymentService.PublishDefinition(result.Value);
                web.Context.ExecuteQueryRetry();
            }
            return(result.Value);
        }
        public List <PSHWFAssociation> GetWorkflowAssociations(PSHWorkflowDefinition WFDefinition)
        {
            List <PSHWFAssociation> lstWFAssociations = new List <PSHWFAssociation>();

            using (var clientContext = new ClientContext(_PWAUrl))
            {
                var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
                //connect to the subscription service
                var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();

                var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(WFDefinition.WFDefinitionId);
                clientContext.Load(workflowAssociations);
                clientContext.ExecuteQuery();

                if (workflowAssociations.AreItemsAvailable)
                {
                    foreach (WorkflowSubscription ws in workflowAssociations)
                    {
                        PSHWFAssociation objWFDefinition = new PSHWFAssociation()
                        {
                            WFDefinitionId            = ws.DefinitionId,
                            WFAssoId                  = ws.Id,
                            WFAssoName                = ws.Name,
                            WFAssoEventTypes          = ws.EventTypes,
                            WFAssoPropertyDefinitions = ws.PropertyDefinitions
                        };

                        lstWFAssociations.Add(objWFDefinition);
                    }
                }
            }
            return(lstWFAssociations);
        }
Example #17
0
        public WorkflowSubscription GetWorkflowSubscription(string workflowName)
        {
            var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            // find Approve Suppliers workflow definition
            var deploymentService = workflowServicesManager.GetWorkflowDeploymentService();
            var definitions       = deploymentService.EnumerateDefinitions(true);

            clientContext.Load(definitions);
            clientContext.ExecuteQuery();

            var definition = definitions
                             .Where(d => d.DisplayName == "Approve Suppliers")
                             .First();

            // find subscriptions
            var subscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
            var subscriptions       = subscriptionService.EnumerateSubscriptionsByDefinition(definition.Id);

            clientContext.Load(subscriptions);
            clientContext.ExecuteQuery();

            return(subscriptions
                   .Where(s => s.EventSourceId == list.Id)
                   .First());
        }
        protected WorkflowSubscription GetCurrentWebWorkflowSubscriptioBySourceId(
             object host,
             ClientContext hostclientContext,
            Web web,
            Guid eventSourceId,
             SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var context = web.Context;

            var workflowServiceManager = new WorkflowServicesManager(hostclientContext, web);

            context.Load(web);
            context.Load(web);

            context.ExecuteQueryWithTrace();

            hostclientContext.Load(workflowServiceManager);
            hostclientContext.ExecuteQueryWithTrace();

            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(eventSourceId);

            hostclientContext.Load(subscriptions);
            hostclientContext.ExecuteQueryWithTrace();

            return subscriptions.FirstOrDefault(s => s.Name == workflowSubscriptionModel.Name);
        }
        public static Guid AddWorkflowDefinition(this Web web, WorkflowDefinition definition, bool publish = true)
        {
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            WorkflowDefinition def = new WorkflowDefinition(web.Context);
            def.AssociationUrl = definition.AssociationUrl;
            def.Description = definition.Description;
            def.DisplayName = definition.DisplayName;
            def.DraftVersion = definition.DraftVersion;
            def.FormField = definition.FormField;
            def.Id = definition.Id != Guid.Empty ? definition.Id : Guid.NewGuid();
            foreach (var prop in definition.Properties)
            {
                def.SetProperty(prop.Key,prop.Value);
            }
            def.RequiresAssociationForm = definition.RequiresAssociationForm;
            def.RequiresInitiationForm = definition.RequiresInitiationForm;
            def.RestrictToScope = definition.RestrictToScope;
            def.RestrictToType = definition.RestrictToType;
            def.Xaml = definition.Xaml;

            var result = deploymentService.SaveDefinition(def);

            web.Context.ExecuteQueryRetry();

            if (publish)
            {
                deploymentService.PublishDefinition(result.Value);
                web.Context.ExecuteQueryRetry();
            }
            return result.Value;
        }
        protected WorkflowSubscription GetCurrentWebWorkflowSubscriptioBySourceId(
            object host,
            ClientContext hostclientContext,
            Web web,
            Guid eventSourceId,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var context = web.Context;

            var workflowServiceManager = new WorkflowServicesManager(hostclientContext, web);

            context.Load(web);
            context.Load(web);

            context.ExecuteQueryWithTrace();

            hostclientContext.Load(workflowServiceManager);
            hostclientContext.ExecuteQueryWithTrace();

            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(eventSourceId);

            hostclientContext.Load(subscriptions);
            hostclientContext.ExecuteQueryWithTrace();

            return(subscriptions.FirstOrDefault(s => s.Name == workflowSubscriptionModel.Name));
        }
Example #21
0
        public static void getAllWorkFlows()
        {
            var          siteURl  = "https://chennaitillidsoft.sharepoint.com/sites/developer5";
            var          context  = new ClientContext(siteURl);
            SecureString passWord = new SecureString();

            foreach (char c in "n@#eTD@098!".ToCharArray())
            {
                passWord.AppendChar(c);
            }
            context.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord);

            var workflowServicesManager = new WorkflowServicesManager(context, context.Web);

            // connect to the deployment service
            var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();

            // get all installed workflows
            var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);

            context.Load(publishedWorkflowDefinitions);
            context.ExecuteQuery();

            // display list of all installed workflows
            foreach (var workflowDefinition in publishedWorkflowDefinitions)
            {
                Console.WriteLine("{0} - {1}", workflowDefinition.Id.ToString(), workflowDefinition.DisplayName);
            }
            Console.ReadLine();
        }
        public static bool TriggerWorkflow(string SiteURL, string WorkflowName)
        {
            bool status = false;

            try
            {
                string siteUrl  = SiteURL;
                string userName = "******";
                string password = "******";

                //Name of the SharePoint 2010 Workflow to start.
                string workflowName = WorkflowName;

                using (ClientContext clientContext = new ClientContext(siteUrl))
                {
                    SecureString securePassword = new SecureString();

                    foreach (char c in password.ToCharArray())
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

                    Web web = clientContext.Web;

                    //Workflow Services Manager which will handle all the workflow interaction.
                    WorkflowServicesManager wfServicesManager = new WorkflowServicesManager(clientContext, web);

                    //Will return all Workflow Associations which are running on the SharePoint 2010 Engine
                    WorkflowAssociationCollection wfAssociations = web.WorkflowAssociations;

                    //Get the required Workflow Association
                    WorkflowAssociation wfAssociation = wfAssociations.GetByName(workflowName);

                    clientContext.Load(wfAssociation);

                    clientContext.ExecuteQuery();

                    //Get the instance of the Interop Service which will be used to create an instance of the Workflow
                    InteropService workflowInteropService = wfServicesManager.GetWorkflowInteropService();

                    var initiationData = new Dictionary <string, object>();

                    //Start the Workflow
                    ClientResult <Guid> resultGuid = workflowInteropService.StartWorkflow(wfAssociation.Name, new Guid(), Guid.Empty, Guid.Empty, initiationData);

                    clientContext.ExecuteQuery();
                    status = true;
                }
            }
            catch (Exception ex)
            {
                status = false;
                throw;
            }
            return(status);
        }
Example #23
0
 /// <summary>
 /// Returns a workflow subscription
 /// </summary>
 /// <param name="web"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 public static WorkflowSubscription GetWorkflowSubscription(this Web web, Guid id)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
     var subscription = subscriptionService.GetSubscription(id);
     web.Context.Load(subscription);
     web.Context.ExecuteQueryRetry();
     return subscription;
 }
Example #24
0
        public static void Delete(this WorkflowDefinition definition)
        {
            var clientContext     = definition.Context as ClientContext;
            var servicesManager   = new WorkflowServicesManager(clientContext, clientContext.Web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            deploymentService.DeleteDefinition(definition.Id);
            clientContext.ExecuteQuery();
        }
Example #25
0
        /// <summary>
        /// Publish a custom event to a target workflow instance
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="eventName">The name of the target event</param>
        /// <param name="payload">The payload that will be sent to the event</param>
        public static void PublishCustomEvent(this WorkflowInstance instance, String eventName, String payload)
        {
            var clientContext           = instance.Context as ClientContext;
            var servicesManager         = new WorkflowServicesManager(clientContext, clientContext.Web);
            var workflowInstanceService = servicesManager.GetWorkflowInstanceService();

            workflowInstanceService.PublishCustomEvent(instance, eventName, payload);
            clientContext.ExecuteQueryRetry();
        }
Example #26
0
        /// <summary>
        /// Resumes a workflow
        /// </summary>
        /// <param name="instance"></param>
        public static void ResumeWorkflow(this WorkflowInstance instance)
        {
            var clientContext           = instance.Context as ClientContext;
            var servicesManager         = new WorkflowServicesManager(clientContext, clientContext.Web);
            var workflowInstanceService = servicesManager.GetWorkflowInstanceService();

            workflowInstanceService.ResumeWorkflow(instance);
            clientContext.ExecuteQuery();
        }
        protected WorkflowDefinition GetCurrentWorkflowDefinition(SPWeb web,
            SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);
            return publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName);
        }
Example #28
0
        public WorkflowInstance GetWorkflowInstance(Guid instanceId)
        {
            var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
            var instanceService         = workflowServicesManager.GetWorkflowInstanceService();
            var instance = instanceService.GetInstance(instanceId);

            clientContext.Load(instance);
            clientContext.ExecuteQuery();
            return(instance);
        }
Example #29
0
        /// <summary>
        /// Returns alls workflow instances for a site
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static WorkflowInstanceCollection GetWorkflowInstances(this Web web)
        {
            var servicesManager         = new WorkflowServicesManager(web.Context, web);
            var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
            var instances = workflowInstanceService.EnumerateInstancesForSite();

            web.Context.Load(instances);
            web.Context.ExecuteQueryRetry();
            return(instances);
        }
Example #30
0
        /// <summary>
        /// Returns a workflow subscription
        /// </summary>
        /// <param name="web"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static WorkflowSubscription GetWorkflowSubscription(this Web web, Guid id)
        {
            var servicesManager     = new WorkflowServicesManager(web.Context, web);
            var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscription        = subscriptionService.GetSubscription(id);

            web.Context.Load(subscription);
            web.Context.ExecuteQuery();
            return(subscription);
        }
        protected WorkflowDefinition GetCurrentWorkflowDefinition(SPWeb web,
                                                                  SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager    = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);

            return(publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName));
        }
Example #32
0
        public void PublishCustomEvent(Guid instanceId, string eventName, string payload)
        {
            var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var instanceService = workflowServicesManager.GetWorkflowInstanceService();
            var instance        = instanceService.GetInstance(instanceId);

            instanceService.PublishCustomEvent(instance, eventName, payload);
            clientContext.ExecuteQuery();
        }
Example #33
0
        /// <summary>
        /// Returns a workflow definition
        /// </summary>
        /// <param name="web"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static WorkflowDefinition GetWorkflowDefinition(this Web web, Guid id)
        {
            var servicesManager   = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();
            var definition        = deploymentService.GetDefinition(id);

            web.Context.Load(definition);
            web.Context.ExecuteQuery();
            return(definition);
        }
Example #34
0
        /// <summary>
        /// Returns alls workflow instances for a list item
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static WorkflowInstanceCollection GetWorkflowInstances(this Web web, ListItem item)
        {
            var servicesManager         = new WorkflowServicesManager(web.Context, web);
            var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
            var instances = workflowInstanceService.EnumerateInstancesForListItem(item.ParentList.Id, item.Id);

            web.Context.Load(instances);
            web.Context.ExecuteQuery();
            return(instances);
        }
Example #35
0
        /// <summary>
        /// Returns all instances of a workflow for this subscription
        /// </summary>
        /// <param name="subscription"></param>
        /// <returns></returns>
        public static WorkflowInstanceCollection GetInstances(this WorkflowSubscription subscription)
        {
            var clientContext           = subscription.Context as ClientContext;
            var servicesManager         = new WorkflowServicesManager(clientContext, clientContext.Web);
            var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
            var instances = workflowInstanceService.Enumerate(subscription);

            clientContext.Load(instances);
            clientContext.ExecuteQuery();
            return(instances);
        }
        /// <summary>
        /// Returns all the workflow subscriptions (associations) for the web and the lists of that web
        /// </summary>
        /// <param name="web">The target Web</param>
        /// <returns></returns>
        public static WorkflowSubscription[] GetWorkflowSubscriptions(this Web web)
        {
            // Get a reference to infrastructural services
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

            // Retrieve all the subscriptions (site and lists)
            var subscriptions = subscriptionService.EnumerateSubscriptions();
            web.Context.Load(subscriptions);
            web.Context.ExecuteQueryRetry();
            return subscriptions.ToArray();
        }
        protected WorkflowSubscription GetCurrentWebWorkflowSubscriptioBySourceId(
             object host,
             SPWeb web,
             Guid eventSourceId,
             SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(eventSourceId);

            return subscriptions.FirstOrDefault(s => s.Name == workflowSubscriptionModel.Name);
        }
Example #38
0
        /// <summary>
        /// Returns a workflow subscription for a site.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static WorkflowSubscription GetWorkflowSubscription(this Web web, string name)
        {
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscriptions = subscriptionService.EnumerateSubscriptions();
            var subscriptionQuery = from sub in subscriptions where sub.Name == name select sub;
            var subscriptionsResults = web.Context.LoadQuery(subscriptionQuery);
            web.Context.ExecuteQueryRetry();
            var subscription = subscriptionsResults.FirstOrDefault();
            return subscription;

        }
        protected override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(Name))
            {
                var servicesManager = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var deploymentService = servicesManager.GetWorkflowDeploymentService();
                var definitions = deploymentService.EnumerateDefinitions(PublishedOnly);

                ClientContext.Load(definitions);

                ClientContext.ExecuteQueryRetry();
                WriteObject(definitions, true);
            }
            else
            {
                WriteObject(SelectedWeb.GetWorkflowDefinition(Name, PublishedOnly));
            }
        }
        protected WorkflowDefinition GetCurrentWorkflowDefinition(Web web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving workflow definition by DisplayName: [{0}]", workflowDefinitionModel.DisplayName);

            var clientContext = web.Context;

            var workflowServiceManager = new WorkflowServicesManager(clientContext, web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);
            clientContext.Load(publishedWorkflows, c => c.Include(
                        w => w.DisplayName,
                        w => w.Id,
                        w => w.Published
                        ));
            clientContext.ExecuteQueryWithTrace();

            return publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName);

        }
        protected override void ExecuteCmdlet()
        {
            if (List != null)
            {
                var list = SelectedWeb.GetList(List);

                if (string.IsNullOrEmpty(Name))
                {
                    var servicesManager = new WorkflowServicesManager(ClientContext, SelectedWeb);
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                    var subscriptions = subscriptionService.EnumerateSubscriptionsByList(list.Id);

                    ClientContext.Load(subscriptions);

                    ClientContext.ExecuteQueryRetry();
                    WriteObject(subscriptions, true);
                }
                else
                {
                    WriteObject(list.GetWorkflowSubscription(Name));
                }
            }
            else
            {
                if (string.IsNullOrEmpty(Name))
                {
                    var servicesManager = new WorkflowServicesManager(ClientContext, SelectedWeb);
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                    var subscriptions = subscriptionService.EnumerateSubscriptions();

                    ClientContext.Load(subscriptions);

                    ClientContext.ExecuteQueryRetry();
                    WriteObject(subscriptions, true);
                }
                else
                {
                    WriteObject(SelectedWeb.GetWorkflowSubscription(Name));
                }
            }
        }
        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            if (properties.EventType != SPRemoteEventType.ItemAdded)
            return;

              // build client context using S2S
              using (ClientContext context = TokenHelper.CreateRemoteEventReceiverClientContext(properties)) {
            Web web = context.Web;

            // create a collection of name/value pairs to pass to the workflow upon starting
            var args = new Dictionary<string, object>();
            args.Add("RemoteEventReceiverPassedValue", "Hello from the Remote Event Receiver! - " + DateTime.Now.ToString());

            // get reference to Workflow Service Manager (WSM) in SP...
            WorkflowServicesManager wsm = new WorkflowServicesManager(context, web);
            context.Load(wsm);
            context.ExecuteQuery();

            // get reference to subscription service
            WorkflowSubscriptionService subscriptionService = wsm.GetWorkflowSubscriptionService();
            context.Load(subscriptionService);
            context.ExecuteQuery();

            // get the only workflow association on item's list
            WorkflowSubscription association = subscriptionService.EnumerateSubscriptionsByList(properties.ItemEventProperties.ListId).FirstOrDefault();

            // get reference to instance service (to start a new workflow)
            WorkflowInstanceService instanceService = wsm.GetWorkflowInstanceService();
            context.Load(instanceService);
            context.ExecuteQuery();

            // start the workflow
            instanceService.StartWorkflowOnListItem(association, properties.ItemEventProperties.ListItemId, args);

            // execute the CSOM request
            context.ExecuteQuery();
              }
        }
        protected WorkflowDefinition GetWorkflowDefinition(object host,
            SPWeb web,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving workflow definition by DisplayName: [{0}]", workflowSubscriptionModel.WorkflowDisplayName);
            var workflowServiceManager = new WorkflowServicesManager(web);

            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();
            var tgtwis = workflowServiceManager.GetWorkflowInstanceService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            var result = publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowSubscriptionModel.WorkflowDisplayName);

            if (result == null)
            {
                TraceService.ErrorFormat((int)LogEventId.ModelProvisionCoreCall,
                    "Cannot find workflow definition with DisplayName: [{0}]. Provision might break.",
                    workflowSubscriptionModel.WorkflowDisplayName);
            }

            return result;
        }
Example #44
0
        /// <summary>
        /// Deletes the subscription
        /// </summary>
        /// <param name="subscription"></param>
        public static void Delete(this WorkflowSubscription subscription)
        {
            var clientContext = subscription.Context as ClientContext;
            var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

            subscriptionService.DeleteSubscription(subscription.Id);

            clientContext.ExecuteQueryRetry();
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                var servicesManager = new WorkflowServicesManager(web.Context, web);
                var deploymentService = servicesManager.GetWorkflowDeploymentService();
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                // Provision Workflow Definitions
                foreach (var definition in template.Workflows.WorkflowDefinitions)
                {
                    // Load the Workflow Definition XAML
                    Stream xamlStream = template.Connector.GetFileStream(definition.XamlPath);
                    System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                        {
                            AssociationUrl = definition.AssociationUrl,
                            Description = definition.Description,
                            DisplayName = definition.DisplayName,
                            FormField = definition.FormField,
                            DraftVersion = definition.DraftVersion,
                            Id = definition.Id,
                            InitiationUrl = definition.InitiationUrl,
                            RequiresAssociationForm = definition.RequiresAssociationForm,
                            RequiresInitiationForm = definition.RequiresInitiationForm,
                            RestrictToScope = parser.ParseString(definition.RestrictToScope),
                            RestrictToType = definition.RestrictToType != "Universal" ? definition.RestrictToType : null,
                            Xaml = xaml.ToString(),
                        };

                    //foreach (var p in definition.Properties)
                    //{
                    //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                    //}

                    // Save the Workflow Definition
                    var definitionId = deploymentService.SaveDefinition(workflowDefinition);
                    web.Context.Load(workflowDefinition);
                    web.Context.ExecuteQueryRetry();

                    // Let's publish the Workflow Definition, if needed
                    if (definition.Published)
                    {
                        deploymentService.PublishDefinition(definitionId.Value);
                    }
                }

                foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                {
            #if CLIENTSDKV15
                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId = subscription.DefinitionId,
                            Enabled = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes = subscription.EventTypes,
                            ManualStartBypassesActivationLimit =  subscription.ManualStartBypassesActivationLimit,
                            Name =  subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
            #else
                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId = subscription.DefinitionId,
                            Enabled = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes = subscription.EventTypes,
                            ManualStartBypassesActivationLimit =  subscription.ManualStartBypassesActivationLimit,
                            Name =  subscription.Name,
                            ParentContentTypeId = subscription.ParentContentTypeId,
                            StatusFieldName = subscription.StatusFieldName,
                        };
            #endif
                    foreach (var p in subscription.PropertyDefinitions
                        .Where(d => d.Key == "TaskListId" || d.Key == "HistoryListId"))
                    {
                        workflowSubscription.SetProperty(p.Key, parser.ParseString(p.Value));
                    }

                    if (!String.IsNullOrEmpty(subscription.ListId))
                    {
                        // It is a List Workflow
                        Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                        subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                    }
                    else
                    {
                        // It is a Site Workflow
                        subscriptionService.PublishSubscription(workflowSubscription);
                    }
                    web.Context.ExecuteQueryRetry();
                }
            }

            return parser;
        }
Example #46
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

                try
                {
                    servicesManager = new WorkflowServicesManager(web.Context, web);
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                if (servicesManager != null)
                {
                    var deploymentService = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    // Pre-load useful properties
                    web.EnsureProperty(w => w.Id);

                    // Provision Workflow Definitions
                    foreach (var definition in template.Workflows.WorkflowDefinitions)
                    {
                        // Load the Workflow Definition XAML
                        Stream xamlStream = template.Connector.GetFileStream(definition.XamlPath);
                        System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);

                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
                            {
                                AssociationUrl = definition.AssociationUrl,
                                Description = definition.Description,
                                DisplayName = definition.DisplayName,
                                FormField = definition.FormField,
                                DraftVersion = definition.DraftVersion,
                                Id = definition.Id,
                                InitiationUrl = definition.InitiationUrl,
                                RequiresAssociationForm = definition.RequiresAssociationForm,
                                RequiresInitiationForm = definition.RequiresInitiationForm,
                                RestrictToScope = parser.ParseString(definition.RestrictToScope),
                                RestrictToType = definition.RestrictToType != "Universal" ? definition.RestrictToType : null,
                                Xaml = xaml.ToString(),
                            };

                        //foreach (var p in definition.Properties)
                        //{
                        //    workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
                        //}

                        // Save the Workflow Definition
                        var definitionId = deploymentService.SaveDefinition(workflowDefinition);
                        web.Context.Load(workflowDefinition);
                        web.Context.ExecuteQueryRetry();

                        // Let's publish the Workflow Definition, if needed
                        if (definition.Published)
                        {
                            deploymentService.PublishDefinition(definitionId.Value);
                        }
                    }

                    // get existing subscriptions
                    var existingWorkflowSubscriptions = web.GetWorkflowSubscriptions();

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        // Check if the subscription already exists before adding it, and
                        // if already exists a subscription with the same name and with the same DefinitionId,
                        // it is a duplicate
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                            {
                                // Thus, skip it!
                                WriteWarning(string.Format("Workflow Subscription '{0}' already exists. Skipping...", subscription.Name), ProvisioningMessageType.Warning);
                                continue;
                            }
            #if CLIENTSDKV15
                    // Create the WorkflowDefinition instance
                    Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                        new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId = subscription.DefinitionId,
                            Enabled = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes = subscription.EventTypes,
                            ManualStartBypassesActivationLimit =  subscription.ManualStartBypassesActivationLimit,
                            Name =  subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
            #else
                        // Create the WorkflowDefinition instance
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                            {
                                DefinitionId = subscription.DefinitionId,
                                Enabled = subscription.Enabled,
                                EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                                EventTypes = subscription.EventTypes,
                                ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                                Name = subscription.Name,
                                ParentContentTypeId = subscription.ParentContentTypeId,
                                StatusFieldName = subscription.StatusFieldName,
                            };
            #endif
                        foreach (var propertyDefinition in subscription.PropertyDefinitions
                            .Where(d => d.Key == "TaskListId" ||
                                        d.Key == "HistoryListId" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                        d.Key == "SharePointWorkflowContext.Subscription.Name" ||
                                        d.Key == "CreatedBySPD"))
                        {
                            workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                        }
                        if (!String.IsNullOrEmpty(subscription.ListId))
                        {
                            // It is a List Workflow
                            Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                            subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                        }
                        else
                        {
                            // It is a Site Workflow
                            subscriptionService.PublishSubscription(workflowSubscription);
                        }
                        web.Context.ExecuteQueryRetry();
                    }
                }
            }

            return parser;
        }
Example #47
0
 public static void Delete(this WorkflowDefinition definition)
 {
     var clientContext = definition.Context as ClientContext;
     var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     deploymentService.DeleteDefinition(definition.Id);
     clientContext.ExecuteQueryRetry();
 }
        private void DeployWebWorkflowSubscriptionDefinition(
            object host,
            SPWeb web,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);

            var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();
            var tgtwis = workflowServiceManager.GetWorkflowInstanceService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            var currentWorkflowDefinition = publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowSubscriptionModel.WorkflowDisplayName);

            if (currentWorkflowDefinition == null)
                throw new Exception(string.Format("Cannot lookup workflow definition with display name: [{0}] on web:[{1}]", workflowSubscriptionModel.WorkflowDisplayName, web.Url));

            // EnumerateSubscriptionsByEventSource() somehow throws an exception
            //var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(web.ID);
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptions().Where(s => s.EventSourceId == web.ID);

            InvokeOnModelEvent<SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(null, ModelEventType.OnUpdating);

            var currentSubscription = subscriptions.FirstOrDefault(s => s.Name == workflowSubscriptionModel.Name);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentSubscription,
                ObjectType = typeof(WorkflowSubscription),
                ObjectDefinition = workflowSubscriptionModel,
                ModelHost = host
            });

            if (currentSubscription == null)
            {
                var taskList = GetTaskList(web, workflowSubscriptionModel);
                var historyList = GetHistoryList(web, workflowSubscriptionModel);

                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new SP2013 workflow subscription");

                var newSubscription = new WorkflowSubscription();

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Setting subscription properties");

                newSubscription.Name = workflowSubscriptionModel.Name;
                newSubscription.DefinitionId = currentWorkflowDefinition.Id;

                newSubscription.EventTypes = new List<string>(workflowSubscriptionModel.EventTypes);
                newSubscription.EventSourceId = web.ID;

                newSubscription.SetProperty("HistoryListId", historyList.ID.ToString());
                newSubscription.SetProperty("TaskListId", taskList.ID.ToString());

                newSubscription.SetProperty("WebId", web.ID.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.WebId", web.ID.ToString());

                // to be able to change HistoryListId, TaskListId, ListId
                InvokeOnModelEvent<SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(newSubscription, ModelEventType.OnUpdated);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newSubscription,
                    ObjectType = typeof(WorkflowSubscription),
                    ObjectDefinition = workflowSubscriptionModel,
                    ModelHost = host
                });

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishSubscription()");
                var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow subscription");

                currentSubscription.EventTypes = new List<string>(workflowSubscriptionModel.EventTypes);

                InvokeOnModelEvent<SP2013WorkflowSubscriptionDefinition, WorkflowSubscription>(currentSubscription, ModelEventType.OnUpdated);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = currentSubscription,
                    ObjectType = typeof(WorkflowSubscription),
                    ObjectDefinition = workflowSubscriptionModel,
                    ModelHost = host
                });

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishSubscription()");
                workflowSubscriptionService.PublishSubscription(currentSubscription);
            }
        }
        private void DeployWorkflowDefinition(object host, SPWeb web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);
            var currentWorkflowDefinition = publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentWorkflowDefinition,
                ObjectType = typeof(WorkflowDefinition),
                ObjectDefinition = workflowDefinitionModel,
                ModelHost = host
            });

            if (currentWorkflowDefinition == null)
            {
                var workflowDefinition = new WorkflowDefinition()
                {
                    Xaml = workflowDefinitionModel.Xaml,
                    DisplayName = workflowDefinitionModel.DisplayName
                };

                workflowDeploymentService.SaveDefinition(workflowDefinition);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = workflowDefinition,
                    ObjectType = typeof(WorkflowDefinition),
                    ObjectDefinition = workflowDefinitionModel,
                    ModelHost = host
                });

                workflowDeploymentService.PublishDefinition(workflowDefinition.Id);
            }
            else
            {
                if (workflowDefinitionModel.Override)
                {
                    currentWorkflowDefinition.Xaml = workflowDefinitionModel.Xaml;

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentWorkflowDefinition,
                        ObjectType = typeof(WorkflowDefinition),
                        ObjectDefinition = workflowDefinitionModel,
                        ModelHost = host
                    });

                    workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
                else
                {
                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = currentWorkflowDefinition,
                        ObjectType = typeof(WorkflowDefinition),
                        ObjectDefinition = workflowDefinitionModel,
                        ModelHost = host
                    });

                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
            }
        }
        /// <summary>
        /// Starts a new instance of a workflow definition against the current item
        /// </summary>
        /// <param name="item">The target item</param>
        /// <param name="subscriptionId">The ID of the workflow subscription to start</param>
        /// <param name="payload">Any input argument for the workflow instance</param>
        public static void StartWorkflowInstance(this ListItem item, Guid subscriptionId, IDictionary<String, Object> payload)
        {
            var parentList = item.EnsureProperty(i => i.ParentList);

            var clientContext = item.Context as ClientContext;
            var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var workflowSubscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(parentList.Id);

            clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Id == subscriptionId));
            clientContext.ExecuteQueryRetry();

            var subscription = subscriptions.FirstOrDefault();
            if (subscription != null)
            {
                var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
                workflowInstanceService.StartWorkflowOnListItem(subscription, item.Id, payload);
                clientContext.ExecuteQueryRetry();
            }
        }
        /// <summary>
        /// Starts a new instance of a workflow definition against the current web site
        /// </summary>
        /// <param name="web">The target web site</param>
        /// <param name="subscriptionId">The ID of the workflow subscription to start</param>
        /// <param name="payload">Any input argument for the workflow instance</param>
        public static void StartWorkflowInstance(this Web web, Guid subscriptionId, IDictionary<String, Object> payload)
        {
            var clientContext = web.Context as ClientContext;
            var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

            var workflowSubscriptionService = servicesManager.GetWorkflowSubscriptionService();
            var subscriptions = workflowSubscriptionService.EnumerateSubscriptions();

            clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Id == subscriptionId));
            clientContext.ExecuteQueryRetry();

            var subscription = subscriptions.FirstOrDefault();
            if (subscription != null)
            {
                var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
                workflowInstanceService.StartWorkflow(subscription, payload);
                clientContext.ExecuteQueryRetry();
            }
        }
        /// <summary>
        /// Returns all the workflow definitions
        /// </summary>
        /// <param name="web">The target Web</param>
        /// <param name="publishedOnly">Defines whether to include only published definition, or all the definitions</param>
        /// <returns></returns>
        public static WorkflowDefinition[] GetWorkflowDefinitions(this Web web, Boolean publishedOnly)
        {
            // Get a reference to infrastructural services
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            var definitions = deploymentService.EnumerateDefinitions(publishedOnly);
            web.Context.Load(definitions);
            web.Context.ExecuteQueryRetry();
            return definitions.ToArray();
        }
Example #53
0
        /// <summary>
        /// Adds a workflow subscription to a list
        /// </summary>
        /// <param name="list"></param>
        /// <param name="workflowDefinition">The workflow definition. <seealso>
        ///         <cref>WorkflowExtensions.GetWorkflowDefinition</cref>
        ///     </seealso>
        /// </param>
        /// <param name="subscriptionName">The name of the workflow subscription to create</param>
        /// <param name="startManually">if True the workflow can be started manually</param>
        /// <param name="startOnCreate">if True the workflow will be started on item creation</param>
        /// <param name="startOnChange">if True the workflow will be started on item change</param>
        /// <param name="historyListName">the name of the history list. If not available it will be created</param>
        /// <param name="taskListName">the name of the task list. If not available it will be created</param>
        /// <param name="associationValues"></param>
        /// <returns>Guid of the workflow subscription</returns>
        public static Guid AddWorkflowSubscription(this List list, WorkflowDefinition workflowDefinition, string subscriptionName, bool startManually, bool startOnCreate, bool startOnChange, string historyListName, string taskListName, Dictionary<string, string> associationValues = null)
        {
            // parameter validation
            subscriptionName.ValidateNotNullOrEmpty("subscriptionName");
            historyListName.ValidateNotNullOrEmpty("historyListName");
            taskListName.ValidateNotNullOrEmpty("taskListName");

            var historyList = list.ParentWeb.GetListByTitle(historyListName);
            if (historyList == null)
            {
                historyList = list.ParentWeb.CreateList(ListTemplateType.WorkflowHistory, historyListName, false);
            }
            var taskList = list.ParentWeb.GetListByTitle(taskListName);
            if (taskList == null)
            {
                taskList = list.ParentWeb.CreateList(ListTemplateType.Tasks, taskListName, false);
            }

            var sub = new WorkflowSubscription(list.Context);

            sub.DefinitionId = workflowDefinition.Id;
            sub.Enabled = true;
            sub.Name = subscriptionName;

            var eventTypes = new List<string>();
            if (startManually) eventTypes.Add("WorkflowStart");
            if (startOnCreate) eventTypes.Add("ItemAdded");
            if (startOnChange) eventTypes.Add("ItemUpdated");

            sub.EventTypes = eventTypes;

            sub.SetProperty("HistoryListId", historyList.Id.ToString());
            sub.SetProperty("TaskListId", taskList.Id.ToString());

            if (associationValues != null)
            {
                foreach (var key in associationValues.Keys)
                {
                    sub.SetProperty(key, associationValues[key]);
                }
            }

            var servicesManager = new WorkflowServicesManager(list.Context, list.ParentWeb);

            var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

            var subscriptionResult = subscriptionService.PublishSubscriptionForList(sub, list.Id);

            list.Context.ExecuteQueryRetry();

            return subscriptionResult.Value;
        }
Example #54
0
 /// <summary>
 /// Resumes a workflow
 /// </summary>
 /// <param name="instance"></param>
 public static void ResumeWorkflow(this WorkflowInstance instance)
 {
     var clientContext = instance.Context as ClientContext;
     var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
     var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
     workflowInstanceService.ResumeWorkflow(instance);
     clientContext.ExecuteQueryRetry();
 }
Example #55
0
 /// <summary>
 /// Publish a custom event to a target workflow instance
 /// </summary>
 /// <param name="instance"></param>
 /// <param name="eventName">The name of the target event</param>
 /// <param name="payload">The payload that will be sent to the event</param>
 public static void PublishCustomEvent(this WorkflowInstance instance, String eventName, String payload)
 {
     var clientContext = instance.Context as ClientContext;
     var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
     var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
     workflowInstanceService.PublishCustomEvent(instance, eventName, payload);
     clientContext.ExecuteQueryRetry();
 }
Example #56
0
 /// <summary>
 /// Returns alls workflow instances for a list item
 /// </summary>
 /// <param name="web"></param>
 /// <param name="item"></param>
 /// <returns></returns>
 public static WorkflowInstanceCollection GetWorkflowInstances(this Web web, ListItem item)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
     var instances = workflowInstanceService.EnumerateInstancesForListItem(item.ParentList.Id, item.Id);
     web.Context.Load(instances);
     web.Context.ExecuteQueryRetry();
     return instances;
 }
Example #57
0
 /// <summary>
 /// Returns a workflow definition
 /// </summary>
 /// <param name="web"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 public static WorkflowDefinition GetWorkflowDefinition(this Web web, Guid id)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     var definition = deploymentService.GetDefinition(id);
     web.Context.Load(definition);
     web.Context.ExecuteQueryRetry();
     return definition;
 }
Example #58
0
 /// <summary>
 /// Returns a workflow definition for a site
 /// </summary>
 /// <param name="web"></param>
 /// <param name="displayName"></param>
 /// <param name="publishedOnly"></param>
 /// <returns></returns>
 public static WorkflowDefinition GetWorkflowDefinition(this Web web, string displayName, bool publishedOnly = true)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     var definitions = deploymentService.EnumerateDefinitions(publishedOnly);
     var definitionQuery = from def in definitions where def.DisplayName == displayName select def;
     var definitionResults = web.Context.LoadQuery(definitionQuery);
     web.Context.ExecuteQueryRetry();
     var definition = definitionResults.FirstOrDefault();
     return definition;
 }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            WriteObject(string.Format("Deploying workflow subscription {0} to {1}", Name, SiteUrl));

            var workflowServicesManager = new WorkflowServicesManager(_clientContext, _clientContext.Web);
            var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();

            // Get list ids.
            GetIdsFromSharePoint();

            var workflowSubscription = workflowSubscriptionService.GetSubscription(new Guid(Id));
            _clientContext.Load(workflowSubscription, w => w);
            _clientContext.ExecuteQuery();
            if (workflowSubscription.ServerObjectIsNull == true)
            {
                workflowSubscription = new WorkflowSubscription(_clientContext);
            }
            workflowSubscription.Id = new Guid(Id);
            workflowSubscription.DefinitionId = new Guid(DefinitionId);
            workflowSubscription.Name = Name;
            workflowSubscription.EventSourceId = _eventSourceId;
            workflowSubscription.Enabled = Enabled;
            workflowSubscription.EventTypes = EventTypes ?? new string[] {};
            workflowSubscription.ManualStartBypassesActivationLimit = ManualStartBypassesActivationLimit;
            if (!string.IsNullOrEmpty(StatusFieldName))
            {
                workflowSubscription.StatusFieldName = StatusFieldName;
            }

            if (!string.IsNullOrEmpty(_taskListId))
            {
                workflowSubscription.SetProperty("TaskListId", _taskListId);
            }
            if (!string.IsNullOrEmpty(_historyListId))
            {
                workflowSubscription.SetProperty("HistoryListId", _historyListId);
            }

            if (string.IsNullOrEmpty(EventSourceName))
            {
                // We assume we are deploying a site workflow (no event source specified).
                workflowSubscriptionService.PublishSubscription(workflowSubscription);
            }
            else
            {
                // We assume we are deploying a list workflow otherwise.
                workflowSubscriptionService.PublishSubscriptionForList(workflowSubscription, _eventSourceId);
            }
            _clientContext.ExecuteQuery();
            WriteObject("Workflow subscription published.");
        }
Example #60
-1
 /// <summary>
 /// Returns all instances of a workflow for this subscription
 /// </summary>
 /// <param name="subscription"></param>
 /// <returns></returns>
 public static WorkflowInstanceCollection GetInstances(this WorkflowSubscription subscription)
 {
     var clientContext = subscription.Context as ClientContext;
     var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
     var workflowInstanceService = servicesManager.GetWorkflowInstanceService();
     var instances = workflowInstanceService.Enumerate(subscription);
     clientContext.Load(instances);
     clientContext.ExecuteQueryRetry();
     return instances;
 }