public static WorkflowSubscription MakeListId(this WorkflowSubscription workflowSubscription, Guid listId)
        {
            workflowSubscription.SetProperty("ListId", listId.ToString());
            workflowSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", listId.ToString());

            return(workflowSubscription);
        }
示例#2
0
 protected virtual void MapProperties(WorkflowSubscription workflow, SP2013WorkflowSubscriptionDefinition definition)
 {
     foreach (var prop in definition.Properties)
     {
         workflow.SetProperty(prop.Name, prop.Value);
     }
 }
        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 Guid Subscribe(string name, Guid definitionId, Guid targetListId, WorkflowSubscritpionEventType eventTypes, Guid taskListId, Guid historyListId)
        {
            var eventTypesList = new List <string>();

            foreach (WorkflowSubscritpionEventType type in Enum.GetValues(typeof(WorkflowSubscritpionEventType)))
            {
                if ((type & eventTypes) > 0)
                {
                    eventTypesList.Add(type.ToString());
                }
            }

            var subscription = new WorkflowSubscription(ClientContext)
            {
                Name          = name,
                Enabled       = true,
                DefinitionId  = definitionId,
                EventSourceId = targetListId,
                EventTypes    = eventTypesList.ToArray()
            };

            subscription.SetProperty("TaskListId", taskListId.ToString());
            subscription.SetProperty("HistoryListId", historyListId.ToString());

            var subscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
            var result = subscriptionService.PublishSubscriptionForList(subscription, targetListId);

            ClientContext.ExecuteQuery();
            return(result.Value);
        }
        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);
        }
        public Guid Subscribe(string name, Guid definitionId, Guid targetListId, WorkflowSubscritpionEventType eventTypes, Guid taskListId, Guid historyListId)
        {
            var eventTypesList = new List<string>();
            foreach (WorkflowSubscritpionEventType type in Enum.GetValues(typeof(WorkflowSubscritpionEventType)))
            {
                if ((type & eventTypes) > 0)
                    eventTypesList.Add(type.ToString());
            }

            var subscription = new WorkflowSubscription(ClientContext)
            {
                Name = name,
                Enabled = true,
                DefinitionId = definitionId,
                EventSourceId = targetListId,
                EventTypes = eventTypesList.ToArray()
            };

            subscription.SetProperty("TaskListId", taskListId.ToString());
            subscription.SetProperty("HistoryListId", historyListId.ToString());

            var subscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
            var result = subscriptionService.PublishSubscriptionForList(subscription, targetListId);

            ClientContext.ExecuteQuery();
            return result.Value;
        }
        public static void GetWorkflowReport(string listName, List oList, ClientContext clientContext)
        {
            try
            {
                //Get all list items
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml =
                    "<View><Query>" +
                    "<Where>" +
                    "<And>" +
                    "<Neq><FieldRef Name=\"Stage\"/><Value Type=\"Text\">Complete</Value></Neq>" +
                    "<Neq><FieldRef Name=\"Stage\"/><Value Type=\"Text\">Draft</Value></Neq>" +
                    "</And>" +
                    "</Where>" +
                    // "<OrderBy><FieldRef Name=\"Modified\" Ascending=\"FALSE\"/></OrderBy>" +
                    "</Query>" +
                    //"<RowLimit>5000</RowLimit>" +
                    "</View>";
                ListItemCollection collListItem = oList.GetItems(camlQuery);

                clientContext.Load(collListItem,
                                   items => items.Include(
                                       item => item.Id,
                                       item => item["Title"],
                                       item => item.ParentList));
                clientContext.ExecuteQuery();
                List <CSVOutput> list = new List <CSVOutput>();

                foreach (ListItem oListItem in collListItem)
                {
                    WorkflowInstanceCollection allinstances = WorkflowExtensions.GetWorkflowInstances(oList.ParentWeb, oListItem);
                    //clientContext.Load(allinstances);
                    //clientContext.ExecuteQuery();

                    foreach (WorkflowInstance instance in allinstances)
                    {
                        if (instance.Status == WorkflowStatus.Suspended || instance.Status == WorkflowStatus.Terminated)
                        {
                            WorkflowSubscription subscription = WorkflowExtensions.GetWorkflowSubscription(oList.ParentWeb, instance.WorkflowSubscriptionId);
                            string itemUrl = String.Format(@"{0}/Lists/{1}/DispForm.aspx?ID={2}", oList.ParentWeb.Url, listName, oListItem.Id);

                            string WorkflowUrl = String.Format(@"{0}/_layouts/15/workflow.aspx?List={1}&ID={2}", oList.ParentWeb.Url, oList.Id, oListItem.Id);;

                            Console.WriteLine(string.Format("Item ID:{0}, Title:{1}, Item URL:{2} ", oListItem.Id, oListItem["Title"], itemUrl));
                            Console.Write(string.Format("Workflow Name:{0},Workflow Status:{1}, message:{2}, Workflow URL: {3} ", subscription.Name, instance.Status, instance.FaultInfo, WorkflowUrl));

                            CSVOutput item = new CSVOutput(oListItem.Id.ToString(), oListItem["Title"].ToString(), itemUrl, subscription.Name, instance.Status.ToString(), instance.FaultInfo, WorkflowUrl);
                            list.Add(item);
                        }
                    }
                }

                WriteCSV(list);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#8
0
        //private List LoadWorkflowCatalog(ClientContext cc)
        //{
        //    if (this.workflowCatalog != null)
        //    {
        //        return this.workflowCatalog;
        //    }

        //    //TODO: does this work for sub sites, verify that this library exists on sub sites?
        //    this.workflowCatalog = cc.Web.GetListByTitle("wfpub");
        //    if (this.workflowCatalog != null)
        //    {
        //        //this.workflowCatalog.EnsureProperty(p => p.RootFolder);
        //        this.workflowCatalog.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
        //    }

        //    return this.workflowCatalog;
        //}
        #endregion

        private string GetWorkflowProperty(WorkflowSubscription subscription, string propertyName)
        {
            if (subscription.PropertyDefinitions.ContainsKey(propertyName))
            {
                return(subscription.PropertyDefinitions[propertyName]);
            }

            return("");
        }
示例#9
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.ExecuteQuery();
        }
示例#10
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);
        }
示例#11
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;
        }
        /// <summary>
        /// Create a new workflow association (subscription).
        /// </summary>
        public static void CreateAssociation(ref ClientContext clientConext,
                                             ref WorkflowServicesManager wfServicesManager,
                                             Guid definitionId,
                                             Guid listId,
                                             Guid historyListId,
                                             Guid taskListId)
        {
            WorkflowSubscriptionService subService = wfServicesManager.GetWorkflowSubscriptionService();

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

            // create new association (aka: subscription)
            WorkflowSubscription newSubscription = new WorkflowSubscription(clientConext)
            {
                DefinitionId = definitionId,
                Enabled      = true,
                Name         = "Custom Association " + DateTime.Now
            };

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

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

            // OPTIONAL: if any values submitted by association form, add as properties here
            newSubscription.SetProperty("Prop1", "Value1");
            newSubscription.SetProperty("Prop2", "Value2");

            // create the association
            subService.PublishSubscriptionForList(newSubscription, listId); // creates association on list
            //subService.PublishSubscription(newSubscription);              // creates association on current site
            clientConext.ExecuteQuery();
            Console.WriteLine("Workflow association created!");
        }
        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();
            }
        }
示例#14
0
        /// <summary>
        /// Create a new workflow instance.
        /// </summary>
        public static void CreateInstance(ref ClientContext clientConext,
                                          ref WorkflowServicesManager wfServicesManager,
                                          WorkflowSubscription subscription)
        {
            WorkflowInstanceService instService = wfServicesManager.GetWorkflowInstanceService();

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

            Dictionary <string, object> startParameters = new Dictionary <string, object>();

            // if there are any values to send to the initiation form, add them here
            startParameters.Add("Name1", "Value1");
            startParameters.Add("Name2", "Value2");

            // start an instance
            instService.StartWorkflowOnListItem(subscription, 1, startParameters);
            //instService.StartWorkflow(subscription, startParameters); // when starting on a site

            clientConext.ExecuteQuery();
            Console.WriteLine("Workflow started!");
        }
        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 WriteSubscriptionInstances(List list, WorkflowInstanceService deploymentService, WorkflowSubscription workflowSubscription)
        {
            Instances = new List <SPWorkflowInstance>();

            if (workflowSubscription != null && !workflowSubscription.ServerObjectIsNull())
            {
                var countTerminated   = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Terminated);
                var countSuspended    = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Suspended);
                var countInvalid      = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Invalid);
                var countCancelled    = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Canceled);
                var countCanceling    = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Canceling);
                var countStarted      = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.Started);
                var countNotStarted   = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.NotStarted);
                var countNotSpecified = deploymentService.CountInstancesWithStatus(workflowSubscription, WorkflowStatus.NotSpecified);


                ClientContext.ExecuteQueryRetry();

                LogVerbose("Terminated => {0}", countTerminated.Value);
                LogVerbose("Suspended => {0}", countSuspended.Value);
                LogVerbose("Invalid => {0}", countInvalid.Value);
                LogVerbose("Canceled => {0}", countCancelled.Value);
                LogVerbose("Canceling => {0}", countCanceling.Value);
                LogVerbose("Started => {0}", countStarted.Value);
                LogVerbose("NotStarted => {0}", countNotStarted.Value);
                LogVerbose("NotSpecified => {0}", countNotSpecified.Value);


                if (!DeepScan)
                {
                    var instances = deploymentService.Enumerate(workflowSubscription);
                    ClientContext.Load(instances);
                    ClientContext.ExecuteQueryRetry();

                    LogVerbose($"Instance {instances.Count}...");

                    foreach (var instance in instances)
                    {
                        Instances.Add(new SPWorkflowInstance(instance));
                    }
                }
                else
                {
                    var idx      = 1;
                    var viewCaml = new CamlQuery()
                    {
                        ViewXml = CAML.ViewQuery(string.Empty, string.Empty, 100),
                        ListItemCollectionPosition = null
                    };

                    do
                    {
                        LogVerbose($"Deep search itr=>{idx++} paging => {viewCaml.ListItemCollectionPosition?.PagingInfo}");
                        var items = list.GetItems(viewCaml);
                        this.ClientContext.Load(items, ftx => ftx.ListItemCollectionPosition, ftx => ftx.Include(ftcx => ftcx.Id, ftcx => ftcx.ParentList.Id));
                        this.ClientContext.ExecuteQueryRetry();
                        viewCaml.ListItemCollectionPosition = items.ListItemCollectionPosition;

                        foreach (var item in items)
                        {
                            // Load ParentList ID to Pull Workflow Instances
                            var allinstances = ClientContext.Web.GetWorkflowInstances(item);
                            if (allinstances.Any())
                            {
                                foreach (var instance in allinstances)
                                {
                                    Instances.Add(new SPWorkflowInstance(instance, item.Id));
                                }
                            }
                        }
                    }while (viewCaml.ListItemCollectionPosition != null);
                }
            }
        }
        private void DeployListWorkflowSubscriptionDefinition(
            object host,
            ClientContext hostclientContext, List list, SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            // hostclientContext - it must be clientContext, not ClientRuntimeContext - won't work and would give some weirs error with wg publishing
            // use only clientContext instance for the workflow publishing, not ClientRuntimeContext

            var context = list.Context;
            var web     = list.ParentWeb;

            //This WorkflowServiceManager object is created for current web from client context,
            //but actually it has to be created for parent web of current web.
            //Otherwise it uses wrong web for provisions with multiple webs
            //var workflowServiceManager = new WorkflowServicesManager(hostclientContext, hostclientContext.Web);

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

            context.ExecuteQueryWithTrace();

            //This is creation of WorkflowServiceManager with right web
            var workflowServiceManager = new WorkflowServicesManager(hostclientContext, web);

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

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

            hostclientContext.Load(workflowSubscriptionService);
            hostclientContext.Load(workflowDeploymentService);
            hostclientContext.Load(tgtwis);

            hostclientContext.ExecuteQueryWithTrace();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            hostclientContext.Load(publishedWorkflows);
            hostclientContext.ExecuteQueryWithTrace();

            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));
            }

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(list.Id);

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

            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(hostclientContext);

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

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

                newSubscription.EventTypes    = workflowSubscriptionModel.EventTypes;
                newSubscription.EventSourceId = list.Id;

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

                newSubscription.SetProperty("ListId", list.Id.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.Id.ToString());

                MapProperties(newSubscription, workflowSubscriptionModel);

                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);
                hostclientContext.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow subscription");

                currentSubscription.EventTypes = workflowSubscriptionModel.EventTypes;

                MapProperties(currentSubscription, workflowSubscriptionModel);

                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);

                hostclientContext.ExecuteQueryWithTrace();
            }
        }
        /// <summary>
        /// Ensures that a workflow from the supplied definition id exists on the list, either updating or adding the subscription.
        /// </summary>
        /// <param name="web">The web</param>
        /// <param name="list">The list on which we are ensuring the workflow</param>
        /// <param name="workflowDefinitionId">The workflow definition id</param>
        /// <param name="displayName">The workflow display name</param>
        /// <param name="eventList">The list of events we are registering { possible: ["ItemAdded", "ItemUpdated", "WorkflowStart"] }</param>
        /// <param name="taskList">The task list.</param>
        /// <param name="historyList">The history list.</param>
        /// <param name="workflowPropertyData">The workflow property data.</param>
        /// <param name="remove">If true the workflow is removed, if false it is added or updated.</param>
        /// <returns>The workflow subscription id</returns>
        public static Guid EnsureWorkflowOnList(SPWeb web, SPList list, Guid workflowDefinitionId, string displayName, List <WorkflowStartEventType> eventList, SPList taskList, SPList historyList, Dictionary <string, string> workflowPropertyData, bool remove)
        {
            Guid subscriptionId = Guid.Empty;

            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            // get our manager and services
            var workflowServicesManager = new WorkflowServicesManager(web);

            if (!workflowServicesManager.IsConnected)
            {
                var notConnectedEx = new NotConnectedException();
                throw notConnectedEx;
            }

            var workflowDeploymentService   = workflowServicesManager.GetWorkflowDeploymentService();
            var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();

            var workflowDefinition = workflowDeploymentService.GetDefinition(workflowDefinitionId);

            if (workflowDefinition == null)
            {
                var ex = new SPException("Failed to load workflow definition with id: " + workflowDefinitionId);
                throw ex;
            }

            var workflowSubscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.ID);
            var workflowSubscription  = default(WorkflowSubscription);

            if (workflowSubscriptions != null)
            {
                workflowSubscription = workflowSubscriptions.FirstOrDefault((s) => s.DefinitionId.Equals(workflowDefinitionId));
            }

            // remove the workflow based on the supplied flag
            if (remove)
            {
                if (workflowSubscription != null)
                {
                    workflowSubscriptionService.DeleteSubscription(workflowSubscription.Id);
                }

                return(subscriptionId);
            }

            if (workflowSubscription == null)
            {
                workflowSubscription = new WorkflowSubscription();
                workflowSubscription.EventSourceId = list.ID;
                workflowSubscription.DefinitionId  = workflowDefinition.Id;
                workflowSubscription.Id            = Guid.NewGuid();
            }

            if (workflowPropertyData == null)
            {
                workflowPropertyData = new Dictionary <string, string>();
            }

            workflowPropertyData["TaskListId"]    = (taskList != null) ? taskList.ID.ToString("D") : string.Empty;
            workflowPropertyData["HistoryListId"] = (historyList != null) ? historyList.ID.ToString("D") : string.Empty;
            workflowPropertyData["FormData"]      = string.Empty;

            try
            {
                foreach (string propDataKey in workflowPropertyData.Keys)
                {
                    workflowSubscription.PropertyDefinitions[propDataKey] = workflowPropertyData[propDataKey];
                }

                List <string> events = TransformEvents(eventList);

                workflowSubscription.Name       = displayName;
                workflowSubscription.EventTypes = events;

                subscriptionId = workflowSubscriptionService.PublishSubscriptionForList(workflowSubscription, list.ID);
            }
            catch (Exception err)
            {
                throw;
            }

            return(subscriptionId);
        }
示例#19
0
        private void ValidateWorkflowSubscription(object modelHost,
                                                  ClientContext clientContext,
                                                  Web web,
                                                  WorkflowSubscription spObject,
                                                  SP2013WorkflowSubscriptionDefinition definition)
        {
            var spObjectContext = spObject.Context;

            //spObjectContext.Load(spObject);
            //spObjectContext.Load(spObject, o => o.PropertyDefinitions);
            //spObjectContext.Load(spObject, o => o.EventSourceId);
            //spObjectContext.Load(spObject, o => o.EventTypes);

            //spObjectContext.ExecuteQueryWithTrace();

            #region list accos

            var webContext = web.Context;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject)
                         .ShouldBeEqual(m => m.Name, o => o.Name);

            // [FALSE] - [WorkflowDisplayName] <!- check DefinitionId, load workflow
            //        [FALSE] - [HistoryListUrl]
            //        [FALSE] - [TaskListUrl]
            //        [FALSE] - [EventSourceId]
            //        [FALSE] - [EventTypes]

            #region event types

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.EventTypes);

                var hasAllEventTypes = true;

                foreach (var srcEventType in s.EventTypes)
                {
                    if (!d.EventTypes.Contains(srcEventType))
                    {
                        hasAllEventTypes = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = hasAllEventTypes
                });
            });

            #endregion

            #region validate DefinitionId

            var workflowDefinition = GetWorkflowDefinition(modelHost,
                                                           clientContext,
                                                           web,
                                                           definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.WorkflowDisplayName);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = d.DefinitionId == workflowDefinition.Id
                });
            });

            #endregion

            #region  validate task and history list

            var taskListId    = new Guid(spObject.PropertyDefinitions["TaskListId"]);
            var historyListId = new Guid(spObject.PropertyDefinitions["HistoryListId"]);

            var lists = webContext.LoadQuery <List>(web.Lists.Include(l => l.DefaultViewUrl, l => l.Id));
            webContext.ExecuteQueryWithTrace();

            var srcTaskList    = lists.FirstOrDefault(l => l.Id == taskListId);
            var srcHistoryList = lists.FirstOrDefault(l => l.Id == historyListId);

            var dstTaskList    = GetTaskList(web, definition);
            var dstHistoryList = GetHistoryList(web, definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.TaskListUrl);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcTaskList.Id == dstTaskList.Id
                });
            });

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.HistoryListUrl);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcHistoryList.Id == dstHistoryList.Id
                });
            });

            #endregion

            #endregion
        }
 public WorkflowSubscriptionPipeBind()
 {
     _sub = null;
     _id = Guid.Empty;
     _name = string.Empty;
 }
 public WorkflowSubscriptionPipeBind()
 {
     _sub  = null;
     _id   = Guid.Empty;
     _name = string.Empty;
 }
        private void ValidateWorkflowSubscription(object modelHost,
                                                  SPWeb web,
                                                  WorkflowSubscription spObject,
                                                  SP2013WorkflowSubscriptionDefinition definition)
        {
            #region list accos

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject)
                         .ShouldBeEqual(m => m.Name, o => o.Name);

            // [FALSE] - [WorkflowDisplayName] <!- check DefinitionId, load workflow
            //        [FALSE] - [HistoryListUrl]
            //        [FALSE] - [TaskListUrl]
            //        [FALSE] - [EventSourceId]
            //        [FALSE] - [EventTypes]


            #region event types

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.EventTypes);

                var hasAllEventTypes = true;

                foreach (var srcEventType in s.EventTypes)
                {
                    if (!d.EventTypes.Contains(srcEventType))
                    {
                        hasAllEventTypes = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = hasAllEventTypes
                });
            });

            #endregion

            #region validate DefinitionId

            var workflowDefinition = GetWorkflowDefinition(modelHost, web, definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.WorkflowDisplayName);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = d.DefinitionId == workflowDefinition.Id
                });
            });

            #endregion

            #region  validate task and history list

            var taskListId    = new Guid(spObject.PropertyDefinitions["TaskListId"]);
            var historyListId = new Guid(spObject.PropertyDefinitions["HistoryListId"]);

            var lists = web.Lists;

            var srcTaskList    = lists.OfType <SPList>().FirstOrDefault(l => l.ID == taskListId);
            var srcHistoryList = lists.OfType <SPList>().FirstOrDefault(l => l.ID == historyListId);

            var dstTaskList    = GetTaskList(web, definition);
            var dstHistoryList = GetHistoryList(web, definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.TaskListUrl);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcTaskList.ID == dstTaskList.ID
                });
            });

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.HistoryListUrl);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcHistoryList.ID == dstHistoryList.ID
                });
            });

            #endregion

            if (definition.Properties.Count() > 0)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Properties);
                    var dstProp = d.GetExpressionValue(ct => ct.PropertyDefinitions);

                    var isValid = true;

                    foreach (var prop in s.Properties)
                    {
                        var propName  = prop.Name;
                        var propValue = prop.Value;

                        if (!d.PropertyDefinitions.ContainsKey(propName))
                        {
                            isValid = false;
                        }

                        if (d.PropertyDefinitions[propName] != propValue)
                        {
                            isValid = false;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(p => p.Properties, ".Properties.Count() = 0. Skipping");
            }

            #endregion
        }
 public static WorkflowSubscription MakeTaskListId(this WorkflowSubscription workflowSubscription, Guid taskListId)
 {
     workflowSubscription.SetProperty("TaskListId", taskListId.ToString());
     return(workflowSubscription);
 }
 public static WorkflowSubscription MakeHistoryListId(this WorkflowSubscription workflowSubscription, Guid historyListId)
 {
     workflowSubscription.SetProperty("HistoryListId", historyListId.ToString());
     return(workflowSubscription);
 }
        private void DeployListWorkflowSubscriptionDefinition(
            object host,
            ClientContext hostclientContext, List list, SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            // hostclientContext - it must be clientContext, not ClientRuntimeContext - won't work and would give some weirs error with wg publishing
            // use only clientContext instance for the workflow publishing, not ClientRuntimeContext

            var context = list.Context;
            var web = list.ParentWeb;

            //This WorkflowServiceManager object is created for current web from client context, 
            //but actually it has to be created for parent web of current web.
            //Otherwise it uses wrong web for provisions with multiple webs
            //var workflowServiceManager = new WorkflowServicesManager(hostclientContext, hostclientContext.Web);

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

            context.ExecuteQueryWithTrace();

            //This is creation of WorkflowServiceManager with right web
            var workflowServiceManager = new WorkflowServicesManager(hostclientContext, web);

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

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

            hostclientContext.Load(workflowSubscriptionService);
            hostclientContext.Load(workflowDeploymentService);
            hostclientContext.Load(tgtwis);

            hostclientContext.ExecuteQueryWithTrace();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            hostclientContext.Load(publishedWorkflows);
            hostclientContext.ExecuteQueryWithTrace();

            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));

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByEventSource(list.Id);
            hostclientContext.Load(subscriptions);
            hostclientContext.ExecuteQueryWithTrace();

            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(hostclientContext);

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

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

                newSubscription.EventTypes = workflowSubscriptionModel.EventTypes;
                newSubscription.EventSourceId = list.Id;

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

                newSubscription.SetProperty("ListId", list.Id.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.Id.ToString());

                MapProperties(currentSubscription, workflowSubscriptionModel);

                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);
                hostclientContext.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow subscription");

                currentSubscription.EventTypes = workflowSubscriptionModel.EventTypes;

                MapProperties(currentSubscription, workflowSubscriptionModel);

                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);

                hostclientContext.ExecuteQueryWithTrace();
            }
        }
        private static bool CancelWorkflowOnListItem(SPListItem item, List <Guid> workflowDefinitionIds)
        {
            var result = false;

            try
            {
                Guid siteId = item.Web.Site.ID;
                Guid webId  = item.Web.ID;

                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(siteId))
                    {
                        using (SPWeb web = site.OpenWeb(webId))
                        {
                            // get our manager and services
                            var workflowServicesManager = new WorkflowServicesManager(web);

                            if (!workflowServicesManager.IsConnected)
                            {
                                throw new NotConnectedException();
                            }

                            var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
                            var workflowInstanceService     = workflowServicesManager.GetWorkflowInstanceService();

                            // get our subscription
                            WorkflowSubscription workflowSubscription = default(WorkflowSubscription);
                            var workflowSubscriptionCollection        = workflowSubscriptionService.EnumerateSubscriptionsByList(item.ParentList.ID);
                            foreach (var wfSubscription in workflowSubscriptionCollection)
                            {
                                foreach (Guid inputId in workflowDefinitionIds)
                                {
                                    if (wfSubscription.DefinitionId.Equals(inputId))
                                    {
                                        workflowSubscription = wfSubscription;
                                        break;
                                    }
                                }

                                if (workflowSubscription != null)
                                {
                                    break;
                                }
                            }

                            if (workflowSubscription == null)
                            {
                                throw new Exception("Could not load subscription.  Please ensure workflow is attached to list: " + item.ParentList.RootFolder.ServerRelativeUrl);
                            }

                            var itemGuid = Guid.Empty;
                            if (item.Fields.ContainsField("GUID") && item["GUID"] != null)
                            {
                                itemGuid = new Guid(item["GUID"].ToString());
                            }

                            var listGuid = Guid.Parse(workflowSubscription.GetProperty("Microsoft.SharePoint.ActivationProperties.ListId"));

                            WorkflowInstanceCollection instances = workflowInstanceService.EnumerateInstancesForListItem(listGuid, item.ID);

                            if (instances != null && instances.Count > 0)
                            {
                                foreach (var instance in instances)
                                {
                                    workflowInstanceService.CancelWorkflow(instance);
                                }
                            }

                            result = true;
                        }
                    }
                });
            }
            catch (Exception err)
            {
                result = false;
            }

            return(result);
        }
        private void ValidateWorkflowSubscription(object modelHost,
            SPWeb web,
            WorkflowSubscription spObject,
            SP2013WorkflowSubscriptionDefinition definition)
        {

            #region list accos

            var assert = ServiceFactory.AssertService
                .NewAssert(definition, spObject)
                .ShouldNotBeNull(spObject)
                .ShouldBeEqual(m => m.Name, o => o.Name);

            // [FALSE] - [WorkflowDisplayName] <!- check DefinitionId, load workflow
            //        [FALSE] - [HistoryListUrl] 
            //        [FALSE] - [TaskListUrl]
            //        [FALSE] - [EventSourceId]
            //        [FALSE] - [EventTypes]


            #region event types

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.EventTypes);

                var hasAllEventTypes = true;

                foreach (var srcEventType in s.EventTypes)
                    if (!d.EventTypes.Contains(srcEventType))
                        hasAllEventTypes = false;

                return new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = hasAllEventTypes
                };
            });

            #endregion

            #region validate DefinitionId

            var workflowDefinition = GetWorkflowDefinition(modelHost, web, definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.WorkflowDisplayName);

                return new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = d.DefinitionId == workflowDefinition.Id
                };
            });

            #endregion

            #region  validate task and history list

            var taskListId = new Guid(spObject.PropertyDefinitions["TaskListId"]);
            var historyListId = new Guid(spObject.PropertyDefinitions["HistoryListId"]);

            var lists = web.Lists;

            var srcTaskList = lists.OfType<SPList>().FirstOrDefault(l => l.ID == taskListId);
            var srcHistoryList = lists.OfType<SPList>().FirstOrDefault(l => l.ID == historyListId);

            var dstTaskList = GetTaskList(web, definition);
            var dstHistoryList = GetHistoryList(web, definition);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.TaskListUrl);

                return new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcTaskList.ID == dstTaskList.ID
                };
            });

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.HistoryListUrl);

                return new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    IsValid = srcHistoryList.ID == dstHistoryList.ID
                };
            });

            #endregion

            #endregion
        }
        /// <summary>
        /// Start a SharePoint List Workflow
        /// </summary>
        /// <param name="siteUrl">URL of the SharePoitn Site</param>
        /// <param name="workflowName">Name of the SharePoint2013 Workflow</param>
        /// <param name="itemID">ID of the Item on which to start the workflow List, if item ID is equal to 0 the worlflow to start is considered as site workflow</param>
        /// <param name="initiationData">Any custom parameters you want to send to the workflow</param>
        public bool Execute(worflowParameters param)
        {
            try
            {
                using (ClientContext clientContext = new ClientContext(param.siteUrl))
                {
                    string user     = ConfigurationManager.AppSettings["USER"];
                    string domain   = ConfigurationManager.AppSettings["DOMAIN"];
                    string password = ConfigurationManager.AppSettings["PASSWORD"];

                    System.Net.NetworkCredential cred = new System.Net.NetworkCredential(user, password, domain);
                    clientContext.Credentials = cred;

                    Web web = clientContext.Web;

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

                    //The Subscription service is used to get all the Associations currently on the SPSite
                    WorkflowSubscriptionService wfSubscriptionService = wfServicesManager.GetWorkflowSubscriptionService();

                    //All the subscriptions (associations)
                    WorkflowSubscriptionCollection wfSubscriptions = wfSubscriptionService.EnumerateSubscriptions();

                    //Load only the subscription (association) which we want. You can also get a subscription by definition id.
                    clientContext.Load(wfSubscriptions, wfSubs => wfSubs.Where(wfSub => wfSub.Name == param.workflowName));

                    clientContext.ExecuteQuery();

                    //Get the subscription.
                    WorkflowSubscription wfSubscription = wfSubscriptions.First();

                    //The Instance Service is used to start workflows and create instances.
                    WorkflowInstanceService wfInstanceService = wfServicesManager.GetWorkflowInstanceService();

                    if (param.initiationData == null)
                    {
                        param.initiationData = new Dictionary <string, object>();
                    }

                    //validate item id
                    if (param.itemID > 0)
                    {
                        wfInstanceService.StartWorkflowOnListItem(wfSubscription, param.itemID, param.initiationData);
                    }
                    else
                    {
                        wfInstanceService.StartWorkflow(wfSubscription, param.initiationData);
                    }

                    clientContext.ExecuteQuery();

                    return(true);
                }
            }



            catch (Exception err)
            {
                responseMsg = err.Message;
                return(false);
            }
        }
 public WorkflowSubscriptionPipeBind(WorkflowSubscription sub)
 {
     _sub = sub;
 }
        private void DeployWorkflowSubscriptionDefinition(
            SP2013WorkflowSubscriptionModelHost host,
            ClientContext hostClientContext, List list, SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            // hostClientContext - it must be ClientContext, not ClientRuntimeContext - won't work and would give some weirs error with wg publishing
            // use only ClientContext instance for the workflow pubnlishing, not ClientRuntimeContext

            var context = list.Context;
            var web = list.ParentWeb;

            var workflowServiceManager = new WorkflowServicesManager(hostClientContext, hostClientContext.Web);

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

            context.ExecuteQuery();

            hostClientContext.Load(workflowServiceManager);
            hostClientContext.ExecuteQuery();

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

            hostClientContext.Load(workflowSubscriptionService);
            hostClientContext.Load(workflowDeploymentService);
            hostClientContext.Load(tgtwis);

            hostClientContext.ExecuteQuery();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            hostClientContext.Load(publishedWorkflows);
            hostClientContext.ExecuteQuery();

            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));

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.Id);
            hostClientContext.Load(subscriptions);
            hostClientContext.ExecuteQuery();

            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 newSubscription = new WorkflowSubscription(hostClientContext);

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

                newSubscription.EventTypes = workflowSubscriptionModel.EventTypes;
                newSubscription.EventSourceId = list.Id;

                // lookup task and history lists, probaly need to think ab otehr strategy
                var taskList = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.TaskListUrl);
                var historyList = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.HistoryListUrl);

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

                newSubscription.SetProperty("ListId", list.Id.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.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
                });

                var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription);
                hostClientContext.ExecuteQuery();
            }
            else
            {
                currentSubscription.EventTypes = 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
                });

                workflowSubscriptionService.PublishSubscription(currentSubscription);
                hostClientContext.ExecuteQuery();
            }
        }
示例#31
0
        /// <summary>
        /// Adds a workflow subscription to a list
        /// </summary>
        /// <param name="list"></param>
        /// <param name="workflowDefinition">The workflow definition. <seealso cref="WorkflowExtensions.GetWorkflowDefinition"/></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.ExecuteQuery();

            return(subscriptionResult.Value);
        }
        private void DeployWorkflowSubscriptionDefinition(
            object host,
            SPList list,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var web = list.ParentWeb;
            var workflowServiceManager = new WorkflowServicesManager(list.ParentWeb);

            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));

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.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 newSubscription = new WorkflowSubscription();

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

                newSubscription.EventTypes = workflowSubscriptionModel.EventTypes.ToList();
                newSubscription.EventSourceId = list.ID;

                // lookup task and history lists, probaly need to think ab otehr strategy
                var taskList = web.GetList(SPUrlUtility.CombineUrl(web.Url, workflowSubscriptionModel.TaskListUrl));
                var historyList = web.GetList(SPUrlUtility.CombineUrl(web.Url, workflowSubscriptionModel.HistoryListUrl));

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

                newSubscription.SetProperty("ListId", list.ID.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.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
                });

                var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription);
            }
            else
            {
                currentSubscription.EventTypes = workflowSubscriptionModel.EventTypes.ToList();

                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
                });

                workflowSubscriptionService.PublishSubscription(currentSubscription);
            }
        }
 protected virtual void MapProperties(WorkflowSubscription workflow, SP2013WorkflowSubscriptionDefinition definition)
 {
     foreach (var prop in definition.Properties)
         workflow.SetProperty(prop.Name, prop.Value);
 }
示例#34
0
        public void UpdatWorkflowSubscription()
        {
            var template = new ProvisioningTemplate
            {
                Workflows = new Workflows(),
            };


            var wfDefinition = new WorkflowDefinition
            {
                DisplayName     = "PnP Test Workflow",
                Description     = "PnP Test Workflow Description",
                Id              = Guid.Parse("{19100c31-d561-42c3-88e0-5214d5c584c4}"),
                Published       = true,
                RestrictToType  = "List",
                RestrictToScope = _listId.ToString(),
                XamlPath        = SampleWorkflowPath,
                DraftVersion    = "1",
            };

            template.Workflows.WorkflowDefinitions.Add(wfDefinition);

            var wfSubscription = new WorkflowSubscription
            {
                Name          = "PnP Test Workflow",
                DefinitionId  = wfDefinition.Id,
                ListId        = _listId.ToString(),
                Enabled       = true,
                EventSourceId = _listId.ToString(),
                EventTypes    = new List <string>((new string[] { "WorkflowStart" })),
                ManualStartBypassesActivationLimit = false,
                StatusFieldName     = WFStatusFieldName01,
                ParentContentTypeId = "0x01"
            };

            wfSubscription.PropertyDefinitions.Add("SharePointWorkflowContext.Subscription.Id", "d21cf99d-ada1-486b-bfcf-7d58b8a56974");
            wfSubscription.PropertyDefinitions.Add("SharePointWorkflowContext.Subscription.Name", "PnPTestWorkflow_v1_0_0_WorkflowAssociation");

            template.Workflows.WorkflowSubscriptions.Add(wfSubscription);

            using (var ctx = TestCommon.CreateClientContext())
            {
                TokenParser parser = new TokenParser(ctx.Web, template);
                new ObjectWorkflows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                // Update Properties
                wfSubscription.EventTypes = new List <string>((new string[] { "WorkflowStart", "ItemUpdated" }));
                wfSubscription.Enabled    = !wfSubscription.Enabled;
                wfSubscription.ManualStartBypassesActivationLimit = !wfSubscription.ManualStartBypassesActivationLimit;
                wfSubscription.StatusFieldName = WFStatusFieldName02;

                // Provision Updated Workflow
                new ObjectWorkflows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                // Check if Values of the subscription are updated
                var subscription = ctx.Web.GetWorkflowSubscription(Guid.Parse(wfSubscription.PropertyDefinitions["SharePointWorkflowContext.Subscription.Id"]));
                Assert.AreEqual(subscription.StatusFieldName, wfSubscription.StatusFieldName);
                Assert.AreEqual(subscription.Enabled, wfSubscription.Enabled);
                Assert.AreEqual(subscription.ManualStartBypassesActivationLimit, wfSubscription.ManualStartBypassesActivationLimit);
                Assert.AreEqual(subscription.EventTypes[0], wfSubscription.EventTypes[0]);
                Assert.AreEqual(subscription.EventTypes[1], wfSubscription.EventTypes[1]);
            }
        }
 public WorkflowSubscriptionPipeBind(WorkflowSubscription sub)
 {
     _sub = sub;
 }
示例#36
0
        private void DeployWorkflowSubscriptionDefinition(
            object host,
            SPList list,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var web = list.ParentWeb;
            var workflowServiceManager = new WorkflowServicesManager(list.ParentWeb);

            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));
            }

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.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 newSubscription = new WorkflowSubscription();

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

                newSubscription.EventTypes    = workflowSubscriptionModel.EventTypes.ToList();
                newSubscription.EventSourceId = list.ID;

                // lookup task and history lists, probaly need to think ab otehr strategy
                var taskList    = web.GetList(SPUrlUtility.CombineUrl(web.Url, workflowSubscriptionModel.TaskListUrl));
                var historyList = web.GetList(SPUrlUtility.CombineUrl(web.Url, workflowSubscriptionModel.HistoryListUrl));

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

                newSubscription.SetProperty("ListId", list.ID.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.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
                });

                var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription);
            }
            else
            {
                currentSubscription.EventTypes = workflowSubscriptionModel.EventTypes.ToList();

                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
                });

                workflowSubscriptionService.PublishSubscription(currentSubscription);
            }
        }
示例#37
0
        private void DeployWorkflowSubscriptionDefinition(
            SP2013WorkflowSubscriptionModelHost host,
            ClientContext hostClientContext, List list, SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            // hostClientContext - it must be ClientContext, not ClientRuntimeContext - won't work and would give some weirs error with wg publishing
            // use only ClientContext instance for the workflow pubnlishing, not ClientRuntimeContext

            var context = list.Context;
            var web     = list.ParentWeb;

            var workflowServiceManager = new WorkflowServicesManager(hostClientContext, hostClientContext.Web);

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

            context.ExecuteQuery();

            hostClientContext.Load(workflowServiceManager);
            hostClientContext.ExecuteQuery();

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

            hostClientContext.Load(workflowSubscriptionService);
            hostClientContext.Load(workflowDeploymentService);
            hostClientContext.Load(tgtwis);

            hostClientContext.ExecuteQuery();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

            hostClientContext.Load(publishedWorkflows);
            hostClientContext.ExecuteQuery();

            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));
            }

            var subscriptions = workflowSubscriptionService.EnumerateSubscriptionsByList(list.Id);

            hostClientContext.Load(subscriptions);
            hostClientContext.ExecuteQuery();

            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 newSubscription = new WorkflowSubscription(hostClientContext);

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

                newSubscription.EventTypes    = workflowSubscriptionModel.EventTypes;
                newSubscription.EventSourceId = list.Id;

                // lookup task and history lists, probaly need to think ab otehr strategy
                var taskList    = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.TaskListUrl);
                var historyList = WebExtensions.QueryAndGetListByUrl(web, workflowSubscriptionModel.HistoryListUrl);

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

                newSubscription.SetProperty("ListId", list.Id.ToString());
                newSubscription.SetProperty("Microsoft.SharePoint.ActivationProperties.ListId", list.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
                });

                var currentSubscriptionId = workflowSubscriptionService.PublishSubscription(newSubscription);
                hostClientContext.ExecuteQuery();
            }
            else
            {
                currentSubscription.EventTypes = 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
                });

                workflowSubscriptionService.PublishSubscription(currentSubscription);
                hostClientContext.ExecuteQuery();
            }
        }
示例#38
0
        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);

            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());

                MapProperties(newSubscription, workflowSubscriptionModel);

                // to be able to change HistoryListId, TaskListId, ListId

                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);

                MapProperties(currentSubscription, workflowSubscriptionModel);

                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);
            }
        }
        public void CreateWorkflowAssociation(PSHWFAssociation WFAssociation)
        {
            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(WFAssociation.WFDefinitionId);
                clientContext.Load(workflowAssociations);
                clientContext.ExecuteQuery();

                if (workflowAssociations.AreItemsAvailable)
                {
                    foreach (WorkflowSubscription ws in workflowAssociations)
                    {
                        if (ws.Id == WFAssociation.WFAssoId)
                        {
                            ws.SetProperty("PrepareBriefValue", "06c07e59-cfce-e411-8e68-2c44fd94c786");

                            // create the association
                            workflowSubscriptionService.PublishSubscription(ws);
                            clientContext.ExecuteQuery();
                        }
                    }
                }
                else
                {
                    // create a new association / subscription
                    WorkflowSubscription newSubscription = new WorkflowSubscription(clientContext)
                    {
                        DefinitionId = WFAssociation.WFDefinitionId,
                        Enabled      = true,
                        Name         = WFAssociation.WFAssoName
                    };

                    //workflowHistoryListId = historyList.Id;
                    //workflowTaskListId = tasksList.Id;

                    //var startupOptions = new List<string>();
                    //// manual start
                    //startupOptions.Add("WorkflowStart");

                    // set the workflow start settings
                    newSubscription.EventTypes = WFAssociation.WFAssoEventTypes;// startupOptions;

                    // set the associated task and history lists
                    foreach (KeyValuePair <string, string> propertyDef in WFAssociation.WFAssoPropertyDefinitions)
                    {
                        newSubscription.SetProperty(propertyDef.Key, propertyDef.Value);
                    }
                    //newSubscription.SetProperty("HistoryListId",WFAssociation.WFAssoPropertyDefinitions["HistoryListId"]);// workflowHistoryListId.ToString());
                    //newSubscription.SetProperty("TaskListId", WFAssociation.WFAssoPropertyDefinitions["TaskListId"]);// workflowTaskListId.ToString());

                    //// OPTIONAL: add any association form values
                    //newSubscription.SetProperty("PrepareBriefValue", "06c07e59-cfce-e411-8e68-2c44fd94c786");

                    // create the association
                    workflowSubscriptionService.PublishSubscription(newSubscription);
                    clientContext.ExecuteQuery();
                }
            }
        }
        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.");
        }