Exemplo n.º 1
0
        public static Guid AddWorkflowDefinition(this Web web, WorkflowDefinition definition, bool publish = true)
        {
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

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

            var result = deploymentService.SaveDefinition(def);

            web.Context.ExecuteQueryRetry();

            if (publish)
            {
                deploymentService.PublishDefinition(result.Value);
                web.Context.ExecuteQueryRetry();
            }
            return result.Value;
        }
        protected WorkflowDefinition GetCurrentWorkflowDefinition(SPWeb web,
            SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);
            return publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName);
        }
Exemplo n.º 3
0
        protected override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(Name))
            {
                var servicesManager   = new WorkflowServicesManager(ClientContext, this.SelectedWeb);
                var deploymentService = servicesManager.GetWorkflowDeploymentService();
                var definitions       = deploymentService.EnumerateDefinitions(PublishedOnly);

                ClientContext.Load(definitions);

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

                ClientContext.Load(definitions);

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

            var clientContext = web.Context;

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

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

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

        }
        public static void GetWorkFlowTemplate()
        {
            var templateSiteClientContext = new ClientContext(templateSiteUrl);

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

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

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

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

            // display list of all installed workflows
            WorkflowDefinition currentWorkFlow = publishedWorkflowDefinitions.Where(flow => flow.DisplayName.Equals("BBH Document Atestation")).FirstOrDefault();
            ProvisionWorkFlowAndRelatedList(currentWorkFlow.Xaml, binderSiteUrl);
        }
        protected WorkflowDefinition GetCurrentWorkflowDefinition(Web web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving workflow definition by DisplayName: [{0}]", workflowDefinitionModel.DisplayName);

            var clientContext = web.Context;

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

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);

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

            return(publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowDefinitionModel.DisplayName));
        }
Exemplo n.º 8
0
        public void UpdateWorkflowDefinitionXAML(PSHWorkflowDefinition WFDefinition)
        {
            using (var clientContext = new ClientContext(_PWAUrl))
            {
                var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

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

                //Get all the definitions from the Deployment Service, or get a specific definition using the GetDefinition method.
                WorkflowDefinitionCollection wfDefinitions = workflowDeploymentService.EnumerateDefinitions(false);
                clientContext.Load(wfDefinitions, wfDefs => wfDefs.Where(wfd => wfd.Id == WFDefinition.WFDefinitionId));
                clientContext.ExecuteQuery();

                WorkflowDefinition wfDefinition = wfDefinitions.First();
                wfDefinition.DisplayName = WFDefinition.WFName;
                wfDefinition.Xaml        = WFDefinition.WFDefinitionXAML;

                ClientResult <Guid> wfDefId = workflowDeploymentService.SaveDefinition(wfDefinition);
                workflowDeploymentService.PublishDefinition(wfDefinition.Id);
                clientContext.ExecuteQuery();
            }
        }
        /// <summary>
        /// Write out all installed workflows.
        /// </summary>
        public static void ShowAllInstalledWorkflows(ref ClientContext clientConext,
                                                     ref WorkflowServicesManager wfServicesManager)
        {
            // connect to deployment service
            WorkflowDeploymentService depService = wfServicesManager.GetWorkflowDeploymentService();

            // get all installed workflows
            bool showOnlyPublishedWorkflows           = true;
            WorkflowDefinitionCollection wfDefintions = depService.EnumerateDefinitions(showOnlyPublishedWorkflows);

            clientConext.Load(wfDefintions);
            clientConext.ExecuteQuery();

            // write all
            Console.WriteLine();
            Console.WriteLine("All Installed Workflows:");
            foreach (WorkflowDefinition wfDefintion in wfDefintions)
            {
                Console.WriteLine("{0} - {1}",
                                  wfDefintion.Id,
                                  wfDefintion.DisplayName);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Adds a workflow definition
        /// </summary>
        /// <param name="web">the target web</param>
        /// <param name="definition">the workflow definition to add</param>
        /// <param name="publish">specify true to publish workflow definition</param>
        /// <returns></returns>
        public static Guid AddWorkflowDefinition(this Web web, WorkflowDefinition definition, bool publish = true)
        {
            var servicesManager   = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            WorkflowDefinition def = new WorkflowDefinition(web.Context)
            {
                AssociationUrl = definition.AssociationUrl,
                Description    = definition.Description,
                DisplayName    = definition.DisplayName,
                DraftVersion   = definition.DraftVersion,
                FormField      = definition.FormField,
                Id             = definition.Id != Guid.Empty ? definition.Id : Guid.NewGuid()
            };

            foreach (var prop in definition.Properties)
            {
                def.SetProperty(prop.Key, prop.Value);
            }
            def.RequiresAssociationForm = definition.RequiresAssociationForm;
            def.RequiresInitiationForm  = definition.RequiresInitiationForm;
            def.RestrictToScope         = definition.RestrictToScope;
            def.RestrictToType          = definition.RestrictToType;
            def.Xaml = definition.Xaml;

            var result = deploymentService.SaveDefinition(def);

            web.Context.ExecuteQueryRetry();

            if (publish)
            {
                deploymentService.PublishDefinition(result.Value);
                web.Context.ExecuteQueryRetry();
            }
            return(result.Value);
        }
Exemplo n.º 11
0
        public PSHWorkflowDefinition GetWorkflowDefinition(string WFDefinitionName)
        {
            PSHWorkflowDefinition objWFDefinition = null;

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

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

                //Get all the definitions from the Deployment Service, or get a specific definition using the GetDefinition method.
                WorkflowDefinitionCollection wfDefinitions = workflowDeploymentService.EnumerateDefinitions(false);
                clientContext.Load(wfDefinitions, wfDefs => wfDefs.Where(wfd => wfd.DisplayName == WFDefinitionName));
                clientContext.ExecuteQuery();

                WorkflowDefinition wfDefinition = wfDefinitions.First();

                ClientResult <Guid> wfDefId = workflowDeploymentService.SaveDefinition(wfDefinition);
                workflowDeploymentService.PublishDefinition(wfDefinition.Id);
                clientContext.ExecuteQuery();

                if (wfDefinition != null)
                {
                    objWFDefinition = new PSHWorkflowDefinition()
                    {
                        WFDefinitionId   = wfDefinition.Id,
                        WFDefinitionXAML = wfDefinition.Xaml,
                        WFName           = wfDefinition.DisplayName
                    };
                }
            }

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

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

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

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

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

            return result;
        }
Exemplo n.º 13
0
        protected WorkflowDefinition GetWorkflowDefinition(object host,
                                                           SPWeb web,
                                                           SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving workflow definition by DisplayName: [{0}]", workflowSubscriptionModel.WorkflowDisplayName);
            var workflowServiceManager = new WorkflowServicesManager(web);

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

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

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

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

            return(result);
        }
        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();
            }
        }
Exemplo n.º 15
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();
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Analyses a web for it's workflow usage
        /// </summary>
        /// <param name="cc">ClientContext instance used to retrieve workflow data</param>
        /// <returns>Duration of the workflow analysis</returns>
        public override TimeSpan Analyze(ClientContext cc)
        {
            try
            {
                Web web = cc.Web;

                // Pre-load needed properties in a single call
                cc.Load(web, w => w.Id, w => w.ServerRelativeUrl, w => w.Url, w => w.WorkflowTemplates, w => w.WorkflowAssociations);
                cc.Load(web, p => p.ContentTypes.Include(ct => ct.WorkflowAssociations, ct => ct.Name, ct => ct.StringId));
                cc.Load(web, p => p.Lists.Include(li => li.Id, li => li.Title, li => li.Hidden, li => li.DefaultViewUrl, li => li.BaseTemplate, li => li.RootFolder, li => li.ItemCount, li => li.WorkflowAssociations));
                cc.ExecuteQueryRetry();

                var lists = web.Lists;

                // *******************************************
                // Site, reusable and list level 2013 workflow
                // *******************************************

                // Retrieve the 2013 site level workflow definitions (including unpublished ones)
                WorkflowDefinition[] siteDefinitions = null;
                // Retrieve the 2013 site level workflow subscriptions
                WorkflowSubscription[] siteSubscriptions = null;

                try
                {
                    var servicesManager     = new WorkflowServicesManager(web.Context, web);
                    var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    var definitions = deploymentService.EnumerateDefinitions(false);
                    web.Context.Load(definitions);

                    var subscriptions = subscriptionService.EnumerateSubscriptions();
                    web.Context.Load(subscriptions);

                    web.Context.ExecuteQueryRetry();

                    siteDefinitions   = definitions.ToArray();
                    siteSubscriptions = subscriptions.ToArray();
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                // We've found SP2013 site scoped workflows
                if (siteDefinitions.Count() > 0)
                {
                    foreach (var siteDefinition in siteDefinitions.Where(p => p.RestrictToType.Equals("site", StringComparison.InvariantCultureIgnoreCase) || p.RestrictToType.Equals("universal", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        // Check if this workflow is also in use
                        var siteWorkflowSubscriptions = siteSubscriptions.Where(p => p.DefinitionId.Equals(siteDefinition.Id));

                        if (siteWorkflowSubscriptions.Count() > 0)
                        {
                            foreach (var siteWorkflowSubscription in siteWorkflowSubscriptions)
                            {
                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl            = this.SiteCollectionUrl,
                                    SiteURL               = this.SiteUrl,
                                    ListTitle             = "",
                                    ListUrl               = "",
                                    ContentTypeId         = "",
                                    ContentTypeName       = "",
                                    Version               = "2013",
                                    Scope                 = "Site",
                                    RestrictToType        = siteDefinition.RestrictToType,
                                    DefinitionName        = siteDefinition.DisplayName,
                                    DefinitionDescription = siteDefinition.Description,
                                    SubscriptionName      = siteWorkflowSubscription.Name,
                                    HasSubscriptions      = true,
                                    Enabled               = siteWorkflowSubscription.Enabled,
                                    DefinitionId          = siteDefinition.Id,
                                    IsOOBWorkflow         = false,
                                    SubscriptionId        = siteWorkflowSubscription.Id,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2013 site workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                            {
                                SiteColUrl            = this.SiteCollectionUrl,
                                SiteURL               = this.SiteUrl,
                                ListTitle             = "",
                                ListUrl               = "",
                                ContentTypeId         = "",
                                ContentTypeName       = "",
                                Version               = "2013",
                                Scope                 = "Site",
                                RestrictToType        = siteDefinition.RestrictToType,
                                DefinitionName        = siteDefinition.DisplayName,
                                DefinitionDescription = siteDefinition.Description,
                                SubscriptionName      = "",
                                HasSubscriptions      = false,
                                Enabled               = false,
                                DefinitionId          = siteDefinition.Id,
                                IsOOBWorkflow         = false,
                                SubscriptionId        = Guid.Empty,
                            };

                            if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                            {
                                ScanError error = new ScanError()
                                {
                                    Error      = $"Could not add 2013 site workflow scan result for {workflowScanResult.SiteColUrl}",
                                    SiteColUrl = this.SiteCollectionUrl,
                                    SiteURL    = this.SiteUrl,
                                    Field1     = "WorkflowAnalyzer",
                                };
                                this.ScanJob.ScanErrors.Push(error);
                            }
                        }
                    }
                }

                // We've found SP2013 list scoped workflows
                if (siteDefinitions.Count() > 0)
                {
                    foreach (var listDefinition in siteDefinitions.Where(p => p.RestrictToType.Equals("list", StringComparison.InvariantCultureIgnoreCase) || p.RestrictToType.Equals("universal", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        // Check if this workflow is also in use
                        var listWorkflowSubscriptions = siteSubscriptions.Where(p => p.DefinitionId.Equals(listDefinition.Id));

                        if (listWorkflowSubscriptions.Count() > 0)
                        {
                            foreach (var listWorkflowSubscription in listWorkflowSubscriptions)
                            {
                                Guid   associatedListId    = Guid.Empty;
                                string associatedListTitle = "";
                                string associatedListUrl   = "";
                                if (Guid.TryParse(GetWorkflowProperty(listWorkflowSubscription, "Microsoft.SharePoint.ActivationProperties.ListId"), out Guid associatedListIdValue))
                                {
                                    associatedListId = associatedListIdValue;

                                    // Lookup this list and update title and url
                                    var listLookup = lists.Where(p => p.Id.Equals(associatedListId)).FirstOrDefault();
                                    if (listLookup != null)
                                    {
                                        associatedListTitle = listLookup.Title;
                                        associatedListUrl   = listLookup.RootFolder.ServerRelativeUrl;
                                    }
                                }

                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl            = this.SiteCollectionUrl,
                                    SiteURL               = this.SiteUrl,
                                    ListTitle             = associatedListTitle,
                                    ListUrl               = associatedListUrl,
                                    ListId                = associatedListId,
                                    ContentTypeId         = "",
                                    ContentTypeName       = "",
                                    Version               = "2013",
                                    Scope                 = "List",
                                    RestrictToType        = listDefinition.RestrictToType,
                                    DefinitionName        = listDefinition.DisplayName,
                                    DefinitionDescription = listDefinition.Description,
                                    SubscriptionName      = listWorkflowSubscription.Name,
                                    HasSubscriptions      = true,
                                    Enabled               = listWorkflowSubscription.Enabled,
                                    DefinitionId          = listDefinition.Id,
                                    IsOOBWorkflow         = false,
                                    SubscriptionId        = listWorkflowSubscription.Id,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2013 list workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                            {
                                SiteColUrl            = this.SiteCollectionUrl,
                                SiteURL               = this.SiteUrl,
                                ListTitle             = "",
                                ListUrl               = "",
                                ListId                = Guid.Empty,
                                ContentTypeId         = "",
                                ContentTypeName       = "",
                                Version               = "2013",
                                Scope                 = "List",
                                RestrictToType        = listDefinition.RestrictToType,
                                DefinitionName        = listDefinition.DisplayName,
                                DefinitionDescription = listDefinition.Description,
                                SubscriptionName      = "",
                                HasSubscriptions      = false,
                                Enabled               = false,
                                DefinitionId          = listDefinition.Id,
                                IsOOBWorkflow         = false,
                                SubscriptionId        = Guid.Empty,
                            };

                            if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                            {
                                ScanError error = new ScanError()
                                {
                                    Error      = $"Could not add 2013 list workflow scan result for {workflowScanResult.SiteColUrl}",
                                    SiteColUrl = this.SiteCollectionUrl,
                                    SiteURL    = this.SiteUrl,
                                    Field1     = "WorkflowAnalyzer",
                                };
                                this.ScanJob.ScanErrors.Push(error);
                            }
                        }
                    }
                }

                // ***********************************************
                // Site, list and content type level 2010 workflow
                // ***********************************************

                // Find all places where we have workflows associated (=subscribed) to SharePoint objects
                if (web.WorkflowAssociations.Count > 0)
                {
                    foreach (var workflowAssociation in web.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "Site", WorkflowAssociation = workflowAssociation
                        });
                    }
                }

                foreach (var list in lists.Where(p => p.WorkflowAssociations.Count > 0))
                {
                    foreach (var workflowAssociation in list.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "List", WorkflowAssociation = workflowAssociation, AssociatedList = list
                        });
                    }
                }

                foreach (var ct in web.ContentTypes.Where(p => p.WorkflowAssociations.Count > 0))
                {
                    foreach (var workflowAssociation in ct.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "ContentType", WorkflowAssociation = workflowAssociation, AssociatedContentType = ct
                        });
                    }
                }

                // Process 2010 worflows
                System.Collections.Generic.List <Guid> processedWorkflowAssociations = new System.Collections.Generic.List <Guid>(this.sp2010WorkflowAssociations.Count);
                if (web.WorkflowTemplates.Count > 0)
                {
                    foreach (var workflowTemplate in web.WorkflowTemplates)
                    {
                        // do we have workflows associated for this template?
                        var associatedWorkflows = this.sp2010WorkflowAssociations.Where(p => p.WorkflowAssociation.BaseId.Equals(workflowTemplate.Id));

                        if (associatedWorkflows.Count() > 0)
                        {
                            foreach (var associatedWorkflow in associatedWorkflows)
                            {
                                processedWorkflowAssociations.Add(associatedWorkflow.WorkflowAssociation.Id);

                                // Skip previous versions of a workflow
                                // todo: non-english sites will use another string
                                if (associatedWorkflow.WorkflowAssociation.Name.Contains("(Previous Version:"))
                                {
                                    continue;
                                }

                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl            = this.SiteCollectionUrl,
                                    SiteURL               = this.SiteUrl,
                                    ListTitle             = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Title : "",
                                    ListUrl               = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.RootFolder.ServerRelativeUrl : "",
                                    ListId                = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Id : Guid.Empty,
                                    ContentTypeId         = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.StringId : "",
                                    ContentTypeName       = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.Name : "",
                                    Version               = "2010",
                                    Scope                 = associatedWorkflow.Scope,
                                    RestrictToType        = "N/A",
                                    DefinitionName        = workflowTemplate.Name,
                                    DefinitionDescription = workflowTemplate.Description,
                                    SubscriptionName      = associatedWorkflow.WorkflowAssociation.Name,
                                    HasSubscriptions      = true,
                                    Enabled               = associatedWorkflow.WorkflowAssociation.Enabled,
                                    DefinitionId          = workflowTemplate.Id,
                                    IsOOBWorkflow         = IsOOBWorkflow(workflowTemplate.Id.ToString()),
                                    SubscriptionId        = associatedWorkflow.WorkflowAssociation.Id,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2010 {associatedWorkflow.Scope} type workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            // Only add non OOB workflow templates when there's no associated workflow - makes the dataset smaller
                            if (!IsOOBWorkflow(workflowTemplate.Id.ToString()))
                            {
                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl            = this.SiteCollectionUrl,
                                    SiteURL               = this.SiteUrl,
                                    ListTitle             = "",
                                    ListUrl               = "",
                                    ListId                = Guid.Empty,
                                    ContentTypeId         = "",
                                    ContentTypeName       = "",
                                    Version               = "2010",
                                    Scope                 = "",
                                    RestrictToType        = "N/A",
                                    DefinitionName        = workflowTemplate.Name,
                                    DefinitionDescription = workflowTemplate.Description,
                                    SubscriptionName      = "",
                                    HasSubscriptions      = false,
                                    Enabled               = false,
                                    DefinitionId          = workflowTemplate.Id,
                                    IsOOBWorkflow         = IsOOBWorkflow(workflowTemplate.Id.ToString()),
                                    SubscriptionId        = Guid.Empty,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2010 type workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                    }
                }

                // Are there associated workflows for which we did not find a template
                foreach (var associatedWorkflow in this.sp2010WorkflowAssociations)
                {
                    if (!processedWorkflowAssociations.Contains(associatedWorkflow.WorkflowAssociation.Id))
                    {
                        // Skip previous versions of a workflow
                        // todo: non-english sites will use another string
                        if (associatedWorkflow.WorkflowAssociation.Name.Contains("(Previous Version:"))
                        {
                            continue;
                        }

                        WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                        {
                            SiteColUrl            = this.SiteCollectionUrl,
                            SiteURL               = this.SiteUrl,
                            ListTitle             = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Title : "",
                            ListUrl               = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.RootFolder.ServerRelativeUrl : "",
                            ListId                = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Id : Guid.Empty,
                            ContentTypeId         = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.StringId : "",
                            ContentTypeName       = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.Name : "",
                            Version               = "2010",
                            Scope                 = associatedWorkflow.Scope,
                            RestrictToType        = "N/A",
                            DefinitionName        = associatedWorkflow.WorkflowAssociation.Name,
                            DefinitionDescription = "",
                            SubscriptionName      = associatedWorkflow.WorkflowAssociation.Name,
                            HasSubscriptions      = true,
                            Enabled               = associatedWorkflow.WorkflowAssociation.Enabled,
                            DefinitionId          = Guid.Empty,
                            IsOOBWorkflow         = false,
                            SubscriptionId        = associatedWorkflow.WorkflowAssociation.Id,
                        };

                        if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                        {
                            ScanError error = new ScanError()
                            {
                                Error      = $"Could not add 2010 {associatedWorkflow.Scope} type workflow scan result for {workflowScanResult.SiteColUrl}",
                                SiteColUrl = this.SiteCollectionUrl,
                                SiteURL    = this.SiteUrl,
                                Field1     = "WorkflowAnalyzer",
                            };
                            this.ScanJob.ScanErrors.Push(error);
                        }
                    }
                }
            }
            finally
            {
                this.StopTime = DateTime.Now;
            }

            // return the duration of this scan
            return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks)));
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Office 365 Login Name");
            string loginId = Console.ReadLine();
            string pwd     = GetInput("Password", true);

            Console.WriteLine("Web Url:");
            string webUrl = Console.ReadLine();

            Console.WriteLine("List Name:");
            string listName = Console.ReadLine();

            Console.WriteLine("Workflow Name");
            string workflowName = Console.ReadLine();

            var passWord = new SecureString();

            foreach (char c in pwd.ToCharArray())
            {
                passWord.AppendChar(c);
            }

            using (var ctx = new ClientContext(webUrl)) {
                ctx.Credentials = new SharePointOnlineCredentials(loginId, passWord);

                var workflowServicesManager     = new WorkflowServicesManager(ctx, ctx.Web);
                var workflowInteropService      = workflowServicesManager.GetWorkflowInteropService();
                var workflowSubscriptionService = workflowServicesManager.GetWorkflowSubscriptionService();
                var workflowDeploymentService   = workflowServicesManager.GetWorkflowDeploymentService();
                var workflowInstanceService     = workflowServicesManager.GetWorkflowInstanceService();

                var publishedWorkflowDefinitions = workflowDeploymentService.EnumerateDefinitions(true);
                ctx.Load(publishedWorkflowDefinitions);
                ctx.ExecuteQuery();

                var def = from defs in publishedWorkflowDefinitions
                          where defs.DisplayName == workflowName
                          select defs;

                WorkflowDefinition workflow = def.FirstOrDefault();

                if (workflow != null)
                {
                    // get all workflow associations
                    var workflowAssociations = workflowSubscriptionService.EnumerateSubscriptionsByDefinition(workflow.Id);
                    ctx.Load(workflowAssociations);
                    ctx.ExecuteQuery();

                    // find the first association
                    var firstWorkflowAssociation = workflowAssociations.First();

                    // start the workflow
                    var startParameters = new Dictionary <string, object>();

                    if (ctx.Web.ListExists(listName))
                    {
                        List list = ctx.Web.GetListByTitle(listName);

                        CamlQuery          query = CamlQuery.CreateAllItemsQuery();
                        ListItemCollection items = list.GetItems(query);

                        // Retrieve all items in the ListItemCollection from List.GetItems(Query).
                        ctx.Load(items);
                        ctx.ExecuteQuery();
                        foreach (ListItem listItem in items)
                        {
                            Console.WriteLine("Starting workflow for item: " + listItem.Id);
                            workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, listItem.Id, startParameters);
                            ctx.ExecuteQuery();
                        }
                    }
                }
            }

            Console.WriteLine("Press any key to close....");
            Console.ReadKey();
        }
        private void DeployWorkflowDefinition(object host, SPWeb web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

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

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

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

                workflowDeploymentService.SaveDefinition(workflowDefinition);

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

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

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

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

                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Analyses a web for it's workflow usage
        /// </summary>
        /// <param name="cc">ClientContext instance used to retrieve workflow data</param>
        /// <returns>Duration of the workflow analysis</returns>
        public override TimeSpan Analyze(ClientContext cc)
        {
            try
            {
                // Workflow analysis does not work as the xoml / xaml files can't be read with Sites.Read.All permission
                if (!this.ScanJob.AppOnlyHasFullControl)
                {
                    return(TimeSpan.Zero);
                }

                Web web = cc.Web;

                // Pre-load needed properties in a single call
                cc.Load(web, w => w.Id, w => w.ServerRelativeUrl, w => w.Url, w => w.WorkflowTemplates, w => w.WorkflowAssociations);
                cc.Load(web, p => p.ContentTypes.Include(ct => ct.WorkflowAssociations, ct => ct.Name, ct => ct.StringId));
                cc.Load(web, p => p.Lists.Include(li => li.Id, li => li.Title, li => li.Hidden, li => li.DefaultViewUrl, li => li.BaseTemplate, li => li.RootFolder.ServerRelativeUrl, li => li.ItemCount, li => li.WorkflowAssociations));
                cc.Load(cc.Site, p => p.RootWeb);
                cc.Load(cc.Site.RootWeb, p => p.Lists.Include(li => li.Id, li => li.Title, li => li.Hidden, li => li.DefaultViewUrl, li => li.BaseTemplate, li => li.RootFolder.ServerRelativeUrl, li => li.ItemCount, li => li.WorkflowAssociations));
                cc.ExecuteQueryRetry();

                var lists = web.Lists;

                // *******************************************
                // Site, reusable and list level 2013 workflow
                // *******************************************

                // Retrieve the 2013 site level workflow definitions (including unpublished ones)
                WorkflowDefinition[] siteDefinitions = null;
                // Retrieve the 2013 site level workflow subscriptions
                WorkflowSubscription[] siteSubscriptions = null;

                try
                {
                    var servicesManager     = new WorkflowServicesManager(web.Context, web);
                    var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                    var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

                    var definitions = deploymentService.EnumerateDefinitions(false);
                    web.Context.Load(definitions);

                    var subscriptions = subscriptionService.EnumerateSubscriptions();
                    web.Context.Load(subscriptions);

                    web.Context.ExecuteQueryRetry();

                    siteDefinitions   = definitions.ToArray();
                    siteSubscriptions = subscriptions.ToArray();
                }
                catch (ServerException ex)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                // We've found SP2013 site scoped workflows
                if (siteDefinitions != null && siteDefinitions.Count() > 0)
                {
                    foreach (var siteDefinition in siteDefinitions.Where(p => p.RestrictToType != null && (p.RestrictToType.Equals("site", StringComparison.InvariantCultureIgnoreCase) || p.RestrictToType.Equals("universal", StringComparison.InvariantCultureIgnoreCase))))
                    {
                        // Check if this workflow is also in use
                        var siteWorkflowSubscriptions = siteSubscriptions.Where(p => p.DefinitionId.Equals(siteDefinition.Id));

                        // Perform workflow analysis
                        WorkflowActionAnalysis  workFlowAnalysisResult        = null;
                        WorkflowTriggerAnalysis workFlowTriggerAnalysisResult = null;
                        if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                        {
                            workFlowAnalysisResult        = WorkflowManager.Instance.ParseWorkflowDefinition(siteDefinition.Xaml, WorkflowTypes.SP2013);
                            workFlowTriggerAnalysisResult = WorkflowManager.Instance.ParseWorkflowTriggers(GetWorkflowPropertyBool(siteDefinition.Properties, "SPDConfig.StartOnCreate"), GetWorkflowPropertyBool(siteDefinition.Properties, "SPDConfig.StartOnChange"), GetWorkflowPropertyBool(siteDefinition.Properties, "SPDConfig.StartManually"));
                        }

                        if (siteWorkflowSubscriptions.Count() > 0)
                        {
                            foreach (var siteWorkflowSubscription in siteWorkflowSubscriptions)
                            {
                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl               = this.SiteCollectionUrl,
                                    SiteURL                  = this.SiteUrl,
                                    ListTitle                = "",
                                    ListUrl                  = "",
                                    ContentTypeId            = "",
                                    ContentTypeName          = "",
                                    Version                  = "2013",
                                    Scope                    = "Site",
                                    RestrictToType           = siteDefinition.RestrictToType,
                                    DefinitionName           = siteDefinition.DisplayName,
                                    DefinitionDescription    = siteDefinition.Description,
                                    SubscriptionName         = siteWorkflowSubscription.Name,
                                    HasSubscriptions         = true,
                                    Enabled                  = siteWorkflowSubscription.Enabled,
                                    DefinitionId             = siteDefinition.Id,
                                    IsOOBWorkflow            = false,
                                    SubscriptionId           = siteWorkflowSubscription.Id,
                                    UsedActions              = workFlowAnalysisResult?.WorkflowActions,
                                    ActionCount              = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                    UsedTriggers             = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                    UnsupportedActionsInFlow = workFlowAnalysisResult?.UnsupportedActions,
                                    UnsupportedActionCount   = workFlowAnalysisResult != null ? workFlowAnalysisResult.UnsupportedAccountCount : 0,
                                    LastDefinitionEdit       = GetWorkflowPropertyDateTime(siteDefinition.Properties, "Definition.ModifiedDateUTC"),
                                    LastSubscriptionEdit     = GetWorkflowPropertyDateTime(siteWorkflowSubscription.PropertyDefinitions, "SharePointWorkflowContext.Subscription.ModifiedDateUTC"),
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2013 site workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                            {
                                SiteColUrl               = this.SiteCollectionUrl,
                                SiteURL                  = this.SiteUrl,
                                ListTitle                = "",
                                ListUrl                  = "",
                                ContentTypeId            = "",
                                ContentTypeName          = "",
                                Version                  = "2013",
                                Scope                    = "Site",
                                RestrictToType           = siteDefinition.RestrictToType,
                                DefinitionName           = siteDefinition.DisplayName,
                                DefinitionDescription    = siteDefinition.Description,
                                SubscriptionName         = "",
                                HasSubscriptions         = false,
                                Enabled                  = false,
                                DefinitionId             = siteDefinition.Id,
                                IsOOBWorkflow            = false,
                                SubscriptionId           = Guid.Empty,
                                UsedActions              = workFlowAnalysisResult?.WorkflowActions,
                                ActionCount              = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                UnsupportedActionsInFlow = workFlowAnalysisResult?.UnsupportedActions,
                                UnsupportedActionCount   = workFlowAnalysisResult != null ? workFlowAnalysisResult.UnsupportedAccountCount : 0,
                                UsedTriggers             = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                LastDefinitionEdit       = GetWorkflowPropertyDateTime(siteDefinition.Properties, "Definition.ModifiedDateUTC"),
                            };

                            if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                            {
                                ScanError error = new ScanError()
                                {
                                    Error      = $"Could not add 2013 site workflow scan result for {workflowScanResult.SiteColUrl}",
                                    SiteColUrl = this.SiteCollectionUrl,
                                    SiteURL    = this.SiteUrl,
                                    Field1     = "WorkflowAnalyzer",
                                };
                                this.ScanJob.ScanErrors.Push(error);
                            }
                        }
                    }
                }

                // We've found SP2013 list scoped workflows
                if (siteDefinitions != null && siteDefinitions.Count() > 0)
                {
                    foreach (var listDefinition in siteDefinitions.Where(p => p.RestrictToType != null && (p.RestrictToType.Equals("list", StringComparison.InvariantCultureIgnoreCase) || p.RestrictToType.Equals("universal", StringComparison.InvariantCultureIgnoreCase))))
                    {
                        // Check if this workflow is also in use
                        var listWorkflowSubscriptions = siteSubscriptions.Where(p => p.DefinitionId.Equals(listDefinition.Id));

                        // Perform workflow analysis
                        WorkflowActionAnalysis  workFlowAnalysisResult        = null;
                        WorkflowTriggerAnalysis workFlowTriggerAnalysisResult = null;
                        if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                        {
                            workFlowAnalysisResult        = WorkflowManager.Instance.ParseWorkflowDefinition(listDefinition.Xaml, WorkflowTypes.SP2013);
                            workFlowTriggerAnalysisResult = WorkflowManager.Instance.ParseWorkflowTriggers(GetWorkflowPropertyBool(listDefinition.Properties, "SPDConfig.StartOnCreate"), GetWorkflowPropertyBool(listDefinition.Properties, "SPDConfig.StartOnChange"), GetWorkflowPropertyBool(listDefinition.Properties, "SPDConfig.StartManually"));
                        }

                        if (listWorkflowSubscriptions.Count() > 0)
                        {
                            foreach (var listWorkflowSubscription in listWorkflowSubscriptions)
                            {
                                Guid   associatedListId    = Guid.Empty;
                                string associatedListTitle = "";
                                string associatedListUrl   = "";
                                if (Guid.TryParse(GetWorkflowProperty(listWorkflowSubscription, "Microsoft.SharePoint.ActivationProperties.ListId"), out Guid associatedListIdValue))
                                {
                                    associatedListId = associatedListIdValue;

                                    // Lookup this list and update title and url
                                    var listLookup = lists.Where(p => p.Id.Equals(associatedListId)).FirstOrDefault();
                                    if (listLookup != null)
                                    {
                                        associatedListTitle = listLookup.Title;
                                        associatedListUrl   = listLookup.RootFolder.ServerRelativeUrl;
                                    }
                                }

                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl               = this.SiteCollectionUrl,
                                    SiteURL                  = this.SiteUrl,
                                    ListTitle                = associatedListTitle,
                                    ListUrl                  = associatedListUrl,
                                    ListId                   = associatedListId,
                                    ContentTypeId            = "",
                                    ContentTypeName          = "",
                                    Version                  = "2013",
                                    Scope                    = "List",
                                    RestrictToType           = listDefinition.RestrictToType,
                                    DefinitionName           = listDefinition.DisplayName,
                                    DefinitionDescription    = listDefinition.Description,
                                    SubscriptionName         = listWorkflowSubscription.Name,
                                    HasSubscriptions         = true,
                                    Enabled                  = listWorkflowSubscription.Enabled,
                                    DefinitionId             = listDefinition.Id,
                                    IsOOBWorkflow            = false,
                                    SubscriptionId           = listWorkflowSubscription.Id,
                                    UsedActions              = workFlowAnalysisResult?.WorkflowActions,
                                    ActionCount              = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                    UsedTriggers             = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                    UnsupportedActionsInFlow = workFlowAnalysisResult?.UnsupportedActions,
                                    UnsupportedActionCount   = workFlowAnalysisResult != null ? workFlowAnalysisResult.UnsupportedAccountCount : 0,
                                    LastDefinitionEdit       = GetWorkflowPropertyDateTime(listDefinition.Properties, "Definition.ModifiedDateUTC"),
                                    LastSubscriptionEdit     = GetWorkflowPropertyDateTime(listWorkflowSubscription.PropertyDefinitions, "SharePointWorkflowContext.Subscription.ModifiedDateUTC"),
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2013 list workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                            {
                                SiteColUrl               = this.SiteCollectionUrl,
                                SiteURL                  = this.SiteUrl,
                                ListTitle                = "",
                                ListUrl                  = "",
                                ListId                   = Guid.Empty,
                                ContentTypeId            = "",
                                ContentTypeName          = "",
                                Version                  = "2013",
                                Scope                    = "List",
                                RestrictToType           = listDefinition.RestrictToType,
                                DefinitionName           = listDefinition.DisplayName,
                                DefinitionDescription    = listDefinition.Description,
                                SubscriptionName         = "",
                                HasSubscriptions         = false,
                                Enabled                  = false,
                                DefinitionId             = listDefinition.Id,
                                IsOOBWorkflow            = false,
                                SubscriptionId           = Guid.Empty,
                                UsedActions              = workFlowAnalysisResult?.WorkflowActions,
                                ActionCount              = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                UsedTriggers             = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                UnsupportedActionsInFlow = workFlowAnalysisResult?.UnsupportedActions,
                                UnsupportedActionCount   = workFlowAnalysisResult != null ? workFlowAnalysisResult.UnsupportedAccountCount : 0,
                                LastDefinitionEdit       = GetWorkflowPropertyDateTime(listDefinition.Properties, "Definition.ModifiedDateUTC"),
                            };

                            if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                            {
                                ScanError error = new ScanError()
                                {
                                    Error      = $"Could not add 2013 list workflow scan result for {workflowScanResult.SiteColUrl}",
                                    SiteColUrl = this.SiteCollectionUrl,
                                    SiteURL    = this.SiteUrl,
                                    Field1     = "WorkflowAnalyzer",
                                };
                                this.ScanJob.ScanErrors.Push(error);
                            }
                        }
                    }
                }

                // ***********************************************
                // Site, list and content type level 2010 workflow
                // ***********************************************

                // Find all places where we have workflows associated (=subscribed) to SharePoint objects
                if (web.WorkflowAssociations.Count > 0)
                {
                    foreach (var workflowAssociation in web.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "Site", WorkflowAssociation = workflowAssociation
                        });
                    }
                }

                foreach (var list in lists.Where(p => p.WorkflowAssociations.Count > 0))
                {
                    foreach (var workflowAssociation in list.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "List", WorkflowAssociation = workflowAssociation, AssociatedList = list
                        });
                    }
                }

                foreach (var ct in web.ContentTypes.Where(p => p.WorkflowAssociations.Count > 0))
                {
                    foreach (var workflowAssociation in ct.WorkflowAssociations)
                    {
                        this.sp2010WorkflowAssociations.Add(new SP2010WorkFlowAssociation()
                        {
                            Scope = "ContentType", WorkflowAssociation = workflowAssociation, AssociatedContentType = ct
                        });
                    }
                }

                // Process 2010 worflows
                List <Guid> processedWorkflowAssociations = new List <Guid>(this.sp2010WorkflowAssociations.Count);

                if (web.WorkflowTemplates.Count > 0)
                {
                    // Process the templates
                    foreach (var workflowTemplate in web.WorkflowTemplates)
                    {
                        // do we have workflows associated for this template?
                        var associatedWorkflows = this.sp2010WorkflowAssociations.Where(p => p.WorkflowAssociation.BaseId.Equals(workflowTemplate.Id));
                        if (associatedWorkflows.Count() > 0)
                        {
                            // Perform workflow analysis
                            // If returning null than this workflow template was an OOB workflow one
                            WorkflowActionAnalysis   workFlowAnalysisResult = null;
                            Tuple <string, DateTime> loadedWorkflow         = null;

                            if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                            {
                                loadedWorkflow = LoadWorkflowDefinition(cc, workflowTemplate);
                                if (!string.IsNullOrEmpty(loadedWorkflow?.Item1))
                                {
                                    workFlowAnalysisResult = WorkflowManager.Instance.ParseWorkflowDefinition(loadedWorkflow.Item1, WorkflowTypes.SP2010);
                                }
                            }

                            foreach (var associatedWorkflow in associatedWorkflows)
                            {
                                processedWorkflowAssociations.Add(associatedWorkflow.WorkflowAssociation.Id);

                                // Skip previous versions of a workflow
                                // TODO: non-english sites will use another string
                                if (associatedWorkflow.WorkflowAssociation.Name.Contains("(Previous Version:"))
                                {
                                    continue;
                                }

                                WorkflowTriggerAnalysis workFlowTriggerAnalysisResult = null;
                                if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                                {
                                    workFlowTriggerAnalysisResult = WorkflowManager.Instance.ParseWorkflowTriggers(associatedWorkflow.WorkflowAssociation.AutoStartCreate, associatedWorkflow.WorkflowAssociation.AutoStartChange, associatedWorkflow.WorkflowAssociation.AllowManual);
                                }

                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl               = this.SiteCollectionUrl,
                                    SiteURL                  = this.SiteUrl,
                                    ListTitle                = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Title : "",
                                    ListUrl                  = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.RootFolder.ServerRelativeUrl : "",
                                    ListId                   = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Id : Guid.Empty,
                                    ContentTypeId            = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.StringId : "",
                                    ContentTypeName          = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.Name : "",
                                    Version                  = "2010",
                                    Scope                    = associatedWorkflow.Scope,
                                    RestrictToType           = "N/A",
                                    DefinitionName           = workflowTemplate.Name,
                                    DefinitionDescription    = workflowTemplate.Description,
                                    SubscriptionName         = associatedWorkflow.WorkflowAssociation.Name,
                                    HasSubscriptions         = true,
                                    Enabled                  = associatedWorkflow.WorkflowAssociation.Enabled,
                                    DefinitionId             = workflowTemplate.Id,
                                    IsOOBWorkflow            = IsOOBWorkflow(workflowTemplate.Id.ToString()),
                                    SubscriptionId           = associatedWorkflow.WorkflowAssociation.Id,
                                    UsedActions              = workFlowAnalysisResult?.WorkflowActions,
                                    ActionCount              = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                    UsedTriggers             = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                    UnsupportedActionsInFlow = workFlowAnalysisResult?.UnsupportedActions,
                                    UnsupportedActionCount   = workFlowAnalysisResult != null ? workFlowAnalysisResult.UnsupportedAccountCount : 0,
                                    LastDefinitionEdit       = loadedWorkflow != null ? loadedWorkflow.Item2 : associatedWorkflow.WorkflowAssociation.Modified,
                                    LastSubscriptionEdit     = associatedWorkflow.WorkflowAssociation.Modified,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2010 {associatedWorkflow.Scope} type workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                        else
                        {
                            // Only add non OOB workflow templates when there's no associated workflow - makes the dataset smaller
                            if (!IsOOBWorkflow(workflowTemplate.Id.ToString()))
                            {
                                // Perform workflow analysis
                                WorkflowActionAnalysis   workFlowAnalysisResult        = null;
                                WorkflowTriggerAnalysis  workFlowTriggerAnalysisResult = null;
                                Tuple <string, DateTime> loadedWorkflow = null;

                                if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                                {
                                    loadedWorkflow = LoadWorkflowDefinition(cc, workflowTemplate);
                                    if (!string.IsNullOrEmpty(loadedWorkflow?.Item1))
                                    {
                                        workFlowAnalysisResult = WorkflowManager.Instance.ParseWorkflowDefinition(loadedWorkflow.Item1, WorkflowTypes.SP2010);
                                    }
                                    workFlowTriggerAnalysisResult = WorkflowManager.Instance.ParseWorkflowTriggers(workflowTemplate.AutoStartCreate, workflowTemplate.AutoStartChange, workflowTemplate.AllowManual);
                                }

                                WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                                {
                                    SiteColUrl            = this.SiteCollectionUrl,
                                    SiteURL               = this.SiteUrl,
                                    ListTitle             = "",
                                    ListUrl               = "",
                                    ListId                = Guid.Empty,
                                    ContentTypeId         = "",
                                    ContentTypeName       = "",
                                    Version               = "2010",
                                    Scope                 = "",
                                    RestrictToType        = "N/A",
                                    DefinitionName        = workflowTemplate.Name,
                                    DefinitionDescription = workflowTemplate.Description,
                                    SubscriptionName      = "",
                                    HasSubscriptions      = false,
                                    Enabled               = false,
                                    DefinitionId          = workflowTemplate.Id,
                                    IsOOBWorkflow         = IsOOBWorkflow(workflowTemplate.Id.ToString()),
                                    SubscriptionId        = Guid.Empty,
                                    UsedActions           = workFlowAnalysisResult?.WorkflowActions,
                                    ActionCount           = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                                    UsedTriggers          = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                                    LastDefinitionEdit    = loadedWorkflow != null ? loadedWorkflow.Item2 : DateTime.MinValue,
                                };

                                if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                                {
                                    ScanError error = new ScanError()
                                    {
                                        Error      = $"Could not add 2010 type workflow scan result for {workflowScanResult.SiteColUrl}",
                                        SiteColUrl = this.SiteCollectionUrl,
                                        SiteURL    = this.SiteUrl,
                                        Field1     = "WorkflowAnalyzer",
                                    };
                                    this.ScanJob.ScanErrors.Push(error);
                                }
                            }
                        }
                    }
                }

                // Are there associated workflows for which we did not find a template (especially when the WF is created for a list)
                foreach (var associatedWorkflow in this.sp2010WorkflowAssociations)
                {
                    if (!processedWorkflowAssociations.Contains(associatedWorkflow.WorkflowAssociation.Id))
                    {
                        // Skip previous versions of a workflow
                        // TODO: non-english sites will use another string
                        if (associatedWorkflow.WorkflowAssociation.Name.Contains("(Previous Version:"))
                        {
                            continue;
                        }

                        // Perform workflow analysis
                        WorkflowActionAnalysis   workFlowAnalysisResult        = null;
                        WorkflowTriggerAnalysis  workFlowTriggerAnalysisResult = null;
                        Tuple <string, DateTime> loadedWorkflow = null;

                        if (Options.IncludeWorkflowWithDetails(this.ScanJob.Mode))
                        {
                            loadedWorkflow = LoadWorkflowDefinition(cc, associatedWorkflow.WorkflowAssociation);
                            if (!string.IsNullOrEmpty(loadedWorkflow?.Item1))
                            {
                                workFlowAnalysisResult = WorkflowManager.Instance.ParseWorkflowDefinition(loadedWorkflow.Item1, WorkflowTypes.SP2010);
                            }
                            workFlowTriggerAnalysisResult = WorkflowManager.Instance.ParseWorkflowTriggers(associatedWorkflow.WorkflowAssociation.AutoStartCreate, associatedWorkflow.WorkflowAssociation.AutoStartChange, associatedWorkflow.WorkflowAssociation.AllowManual);
                        }

                        WorkflowScanResult workflowScanResult = new WorkflowScanResult()
                        {
                            SiteColUrl            = this.SiteCollectionUrl,
                            SiteURL               = this.SiteUrl,
                            ListTitle             = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Title : "",
                            ListUrl               = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.RootFolder.ServerRelativeUrl : "",
                            ListId                = associatedWorkflow.AssociatedList != null ? associatedWorkflow.AssociatedList.Id : Guid.Empty,
                            ContentTypeId         = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.StringId : "",
                            ContentTypeName       = associatedWorkflow.AssociatedContentType != null ? associatedWorkflow.AssociatedContentType.Name : "",
                            Version               = "2010",
                            Scope                 = associatedWorkflow.Scope,
                            RestrictToType        = "N/A",
                            DefinitionName        = associatedWorkflow.WorkflowAssociation.Name,
                            DefinitionDescription = "",
                            SubscriptionName      = associatedWorkflow.WorkflowAssociation.Name,
                            HasSubscriptions      = true,
                            Enabled               = associatedWorkflow.WorkflowAssociation.Enabled,
                            DefinitionId          = Guid.Empty,
                            IsOOBWorkflow         = false,
                            SubscriptionId        = associatedWorkflow.WorkflowAssociation.Id,
                            UsedActions           = workFlowAnalysisResult?.WorkflowActions,
                            ActionCount           = workFlowAnalysisResult != null ? workFlowAnalysisResult.ActionCount : 0,
                            UsedTriggers          = workFlowTriggerAnalysisResult?.WorkflowTriggers,
                            LastSubscriptionEdit  = associatedWorkflow.WorkflowAssociation.Modified,
                            LastDefinitionEdit    = loadedWorkflow != null ? loadedWorkflow.Item2 : associatedWorkflow.WorkflowAssociation.Modified,
                        };

                        if (!this.ScanJob.WorkflowScanResults.TryAdd($"workflowScanResult.SiteURL.{Guid.NewGuid()}", workflowScanResult))
                        {
                            ScanError error = new ScanError()
                            {
                                Error      = $"Could not add 2010 {associatedWorkflow.Scope} type workflow scan result for {workflowScanResult.SiteColUrl}",
                                SiteColUrl = this.SiteCollectionUrl,
                                SiteURL    = this.SiteUrl,
                                Field1     = "WorkflowAnalyzer",
                            };
                            this.ScanJob.ScanErrors.Push(error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ScanError error = new ScanError()
                {
                    Error      = ex.Message,
                    SiteColUrl = this.SiteCollectionUrl,
                    SiteURL    = this.SiteUrl,
                    Field1     = "WorkflowAnalyzer",
                    Field2     = ex.StackTrace,
                };

                // Send error to telemetry to make scanner better
                if (this.ScanJob.ScannerTelemetry != null)
                {
                    this.ScanJob.ScannerTelemetry.LogScanError(ex, error);
                }

                this.ScanJob.ScanErrors.Push(error);
            }
            finally
            {
                this.StopTime = DateTime.Now;
            }

            // return the duration of this scan
            return(new TimeSpan((this.StopTime.Subtract(this.StartTime).Ticks)));
        }
        private void DeployWorkflowDefinition(object host, SPWeb web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager    = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var currentWorkflowDefinition = GetCurrentWorkflowDefinition(web, workflowDefinitionModel);

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

            if (currentWorkflowDefinition == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new SP2013 workflow definition");

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

                MapProperties(workflowDefinition, workflowDefinitionModel);

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                var wfId = workflowDeploymentService.SaveDefinition(workflowDefinition);

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

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                workflowDeploymentService.PublishDefinition(wfId);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow definition");

                if (workflowDefinitionModel.Override)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = true. Overriding workflow definition");

                    currentWorkflowDefinition.Xaml = workflowDefinitionModel.Xaml;

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

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

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                    var wfId = workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(wfId);
                }
                else
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = false. Skipping workflow definition");

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

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

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
            }
        }
        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();
            }
        }
Exemplo n.º 22
0
        public WorkflowSubscription GetWorkflowSubscription(string workflowName)
        {
            var workflowServicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);

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

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

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

            return subscriptions
                .Where(s => s.EventSourceId == list.Id)
                .First();
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            var SelectedWeb = this.ClientContext.Web;

            var ilogger = new DefaultUsageLogger(
                (string msg, object[] margs) =>
            {
                LogDebugging(msg, margs);
            },
                (string msg, object[] margs) =>
            {
                LogWarning(msg, margs);
            },
                (Exception ex, string msg, object[] margs) =>
            {
                LogError(ex, msg, margs);
            });

            IEnumerable <WorkflowSubscription> subscriptionCollection = null;

            if (!string.IsNullOrEmpty(WorkflowName))
            {
                var name                = WorkflowName;
                var servicesManager     = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                var subscriptions       = subscriptionService.EnumerateSubscriptions();
                subscriptionCollection = ClientContext.LoadQuery(from sub in subscriptions where sub.Name == name select sub);
                ClientContext.ExecuteQueryRetry();
            }
            else
            {
                var servicesManager     = new WorkflowServicesManager(ClientContext, SelectedWeb);
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
                var subscriptions       = subscriptionService.EnumerateSubscriptions();
                ClientContext.Load(subscriptions);
                ClientContext.ExecuteQueryRetry();

                subscriptionCollection = subscriptions.ToArray();
            }

            // Log the workflow subscription
            foreach (var itemId in subscriptionCollection)
            {
                var msg = $"Workflow Subscription {itemId.Id} => Name {itemId.Name}";
                LogWarning(msg);
            }



            var workflowDefinitions = SelectedWeb.GetWorkflowDefinitions(false);

            foreach (var wfDefinition in workflowDefinitions)
            {
                var msg = $"Workflow Definition {wfDefinition.Id} => Name {wfDefinition.DisplayName}";
                LogWarning(msg);
            }


            var workflowInstances = SelectedWeb.GetWorkflowInstances();

            foreach (var wfInstance in workflowInstances)
            {
                var msg = $"Workflow Instance {wfInstance.Id} => Fault {wfInstance.FaultInfo}";
                LogWarning(msg);
            }


            var omservicesManager     = new WorkflowServicesManager(ClientContext, SelectedWeb);
            var omsubscriptionService = omservicesManager.GetWorkflowDeploymentService();
            var omsubscriptions       = omsubscriptionService.EnumerateDefinitions(false);

            ClientContext.Load(omsubscriptions);
            ClientContext.ExecuteQueryRetry();
            foreach (var omsub in omsubscriptions)
            {
                var msg = $"Workflow DS Def {omsub.Id} => List {omsub.AssociationUrl} => Name {omsub.DisplayName}";
                LogWarning(msg);
            }


            var queryAssociations = ClientContext.LoadQuery(SelectedWeb.WorkflowAssociations);

            ClientContext.ExecuteQueryRetry();
            foreach (var wfTemplate in queryAssociations)
            {
                var msg = $"Workflow Template {wfTemplate.Id} => List {wfTemplate.ListId} => Name {wfTemplate.Name}";
                LogWarning(msg);
            }


            var query = ClientContext.LoadQuery(SelectedWeb.WorkflowTemplates);

            ClientContext.ExecuteQueryRetry();
            foreach (var wfTemplate in query)
            {
                var msg = $"Workflow Template {wfTemplate.Id} => Declaritive {wfTemplate.IsDeclarative} => Name {wfTemplate.Name}";
                LogWarning(msg);
            }
        }
        private void DeployWorkflowDefinition(object host, SPWeb web, SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);
            var workflowDeploymentService = workflowServiceManager.GetWorkflowDeploymentService();

            var currentWorkflowDefinition = GetCurrentWorkflowDefinition(web, workflowDefinitionModel);

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

            if (currentWorkflowDefinition == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new SP2013 workflow definition");

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

                MapProperties(workflowDefinition, workflowDefinitionModel);

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                var wfId = workflowDeploymentService.SaveDefinition(workflowDefinition);

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

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                workflowDeploymentService.PublishDefinition(wfId);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing SP2013 workflow definition");

                if (workflowDefinitionModel.Override)
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = true. Overriding workflow definition");

                    currentWorkflowDefinition.Xaml = workflowDefinitionModel.Xaml;

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

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

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling SaveDefinition()");
                    var wfId = workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(wfId);
                }
                else
                {
                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Override = false. Skipping workflow definition");

                    MapProperties(currentWorkflowDefinition, workflowDefinitionModel);

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

                    TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling PublishDefinition()");
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
            }
        }
        private void DeployWorkflowDefinition(WebModelHost host,
            Web web,
            SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var clientContext = web.Context;

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

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

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

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

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

                clientContext.Load(workflowDefinition);
                workflowDeploymentService.SaveDefinition(workflowDefinition);

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

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

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

                    workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);

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

                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                    clientContext.ExecuteQuery();
                }
            }
        }
        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);
            }
        }
Exemplo n.º 27
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                var servicesManager = new WorkflowServicesManager(web.Context, web);
                var deploymentService = servicesManager.GetWorkflowDeploymentService();
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

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

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

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

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

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

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

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

            return parser;
        }
        protected void ProcessFile(FileInfo xamlFile)
        {
            // Load and validate XAML.
            var workflowServicesManager = new WorkflowServicesManager(_clientContext, _clientContext.Web);
            var workflowDeploymentService = workflowServicesManager.GetWorkflowDeploymentService();
            var xaml = File.ReadAllText(xamlFile.FullName);
            var validationResult = workflowDeploymentService.ValidateActivity(xaml);
            _clientContext.ExecuteQuery();
            if (!string.IsNullOrEmpty(validationResult.Value))
            {
                throw new PSSnapInException(string.Format("XAML validation failed: {0}.", validationResult.Value));
            }

            var workflowDefinition = workflowDeploymentService.GetDefinition(new Guid(Id));
            _clientContext.Load(workflowDefinition, w => w);
            _clientContext.ExecuteQuery();

            // Create new definition if not exists.
            if (workflowDefinition.ServerObjectIsNull == true)
            {
                workflowDefinition = new WorkflowDefinition(_clientContext);
            }

            // Determine list name before setting other values (requires a round-trip to server)
            workflowDefinition.RestrictToScope = RestrictToScope ?? GetRestrictToScopeFromListName();
            workflowDefinition.AssociationUrl = AssociationUrl;
            workflowDefinition.Description = Description;
            workflowDefinition.DisplayName = DisplayName;
            workflowDefinition.DraftVersion = DraftVersion;
            workflowDefinition.FormField = FormField;
            workflowDefinition.Id = new Guid(Id);
            workflowDefinition.InitiationUrl = InitiationUrl;
            workflowDefinition.RequiresAssociationForm = RequiresAssociationForm;
            workflowDefinition.RequiresInitiationForm = RequiresInitiationForm;
            workflowDefinition.RestrictToType = RestrictToType;
            workflowDefinition.Xaml = xaml;

            // Save changes.
            workflowDeploymentService.SaveDefinition(workflowDefinition);
            _clientContext.ExecuteQuery();
            WriteObject("Workflow definition saved.");

            // Publish the workflow.
            if (Publish)
            {
                workflowDeploymentService.PublishDefinition(workflowDefinition.Id);
                _clientContext.ExecuteQuery();
                WriteObject("Workflow definition published.");
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Returns a workflow definition for a site
 /// </summary>
 /// <param name="web"></param>
 /// <param name="displayName"></param>
 /// <param name="publishedOnly"></param>
 /// <returns></returns>
 public static WorkflowDefinition GetWorkflowDefinition(this Web web, string displayName, bool publishedOnly = true)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     var definitions = deploymentService.EnumerateDefinitions(publishedOnly);
     var definitionQuery = from def in definitions where def.DisplayName == displayName select def;
     var definitionResults = web.Context.LoadQuery(definitionQuery);
     web.Context.ExecuteQueryRetry();
     var definition = definitionResults.FirstOrDefault();
     return definition;
 }
        private void DeployWebWorkflowSubscriptionDefinition(
            object host,
            SPWeb web,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            var workflowServiceManager = new WorkflowServicesManager(web);

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

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(true);

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

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

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

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

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

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

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

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

                var newSubscription = new WorkflowSubscription();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                workflowDeploymentService.SaveDefinition(workflowDefinition);

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

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

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

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

                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                }
            }
        }
Exemplo n.º 32
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                var servicesManager     = new WorkflowServicesManager(web.Context, web);
                var deploymentService   = servicesManager.GetWorkflowDeploymentService();
                var subscriptionService = servicesManager.GetWorkflowSubscriptionService();

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

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

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

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

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

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

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

            return(parser);
        }
        /// <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);
        }
Exemplo n.º 34
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

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

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

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

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

                        int retryCount    = 5;
                        int retryAttempts = 1;
                        int delay         = 2000;

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

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

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

                                // Let's publish the Workflow Definition, if needed
                                if (templateDefinition.Published)
                                {
                                    deploymentService.PublishDefinition(newDefinition.Value);
                                    web.Context.ExecuteQueryRetry();
                                }

                                break; // no errors so exit loop
                            }
                            catch (Exception ex)
                            {
                                // check exception is due to connection closed issue
                                if (ex is ServerException && ((ServerException)ex).ServerErrorCode == -2130575223 &&
                                    ((ServerException)ex).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPException", StringComparison.InvariantCultureIgnoreCase) &&
                                    ((ServerException)ex).Message.Contains("A connection that was expected to be kept alive was closed by the server.")
                                    )
                                {
                                    WriteWarning(String.Format("Connection closed whilst adding Workflow Definition, trying again in {0}ms", delay), ProvisioningMessageType.Warning);

                                    Thread.Sleep(delay);

                                    retryAttempts++;
                                    delay = delay * 2; // double delay for next retry
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }


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

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription = null;

                        // Check if the subscription already exists before adding it, and
                        // if already exists a subscription with the same name and with the same DefinitionId,
                        // it is a duplicate and we just need to update it
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                        {
                            // Thus, delete it before adding it again!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. It will be updated.", subscription.Name), ProvisioningMessageType.Warning);
                            workflowSubscription = existingWorkflowSubscriptions.FirstOrDefault((s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId));

                            if (workflowSubscription != null)
                            {
                                subscriptionService.DeleteSubscription(workflowSubscription.Id);
                                web.Context.ExecuteQueryRetry();
                            }
                        }

#if ONPREMISES
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name            = subscription.Name,
                            StatusFieldName = subscription.StatusFieldName,
                        };
#else
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                        {
                            DefinitionId  = subscription.DefinitionId,
                            Enabled       = subscription.Enabled,
                            EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                            EventTypes    = subscription.EventTypes,
                            ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                            Name = subscription.Name,
                            ParentContentTypeId = subscription.ParentContentTypeId,
                            StatusFieldName     = subscription.StatusFieldName,
                        };
#endif

                        if (workflowSubscription != null)
                        {
                            foreach (var propertyDefinition in subscription.PropertyDefinitions
                                     .Where(d => d.Key == "TaskListId" ||
                                            d.Key == "HistoryListId" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Name" ||
                                            d.Key == "CreatedBySPD"))
                            {
                                workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                            }
                            if (!String.IsNullOrEmpty(subscription.ListId))
                            {
                                // It is a List Workflow
                                Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                                subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                            }
                            else
                            {
                                // It is a Site Workflow
                                subscriptionService.PublishSubscription(workflowSubscription);
                            }
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                }
            }

            return(parser);
        }
Exemplo n.º 35
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);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Returns all the workflow definitions
        /// </summary>
        /// <param name="web">The target Web</param>
        /// <param name="publishedOnly">Defines whether to include only published definition, or all the definitions</param>
        /// <returns></returns>
        public static WorkflowDefinition[] GetWorkflowDefinitions(this Web web, Boolean publishedOnly)
        {
            // Get a reference to infrastructural services
            var servicesManager = new WorkflowServicesManager(web.Context, web);
            var deploymentService = servicesManager.GetWorkflowDeploymentService();

            var definitions = deploymentService.EnumerateDefinitions(publishedOnly);
            web.Context.Load(definitions);
            web.Context.ExecuteQueryRetry();
            return definitions.ToArray();
        }
        private void DeployWorkflowDefinition(WebModelHost host,
                                              Web web,
                                              SP2013WorkflowDefinition workflowDefinitionModel)
        {
            var clientContext = web.Context;

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

            var publishedWorkflows = workflowDeploymentService.EnumerateDefinitions(false);

            clientContext.Load(publishedWorkflows, c => c.Include(
                                   w => w.DisplayName,
                                   w => w.Id,
                                   w => w.Published
                                   ));
            clientContext.ExecuteQuery();

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

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

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

                clientContext.Load(workflowDefinition);
                workflowDeploymentService.SaveDefinition(workflowDefinition);

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

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

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

                    workflowDeploymentService.SaveDefinition(currentWorkflowDefinition);
                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);

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

                    workflowDeploymentService.PublishDefinition(currentWorkflowDefinition.Id);
                    clientContext.ExecuteQuery();
                }
            }
        }
Exemplo n.º 38
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

            return(parser);
        }
Exemplo n.º 40
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);
            }
        }
        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();
            }
        }
Exemplo n.º 42
0
 public static void Delete(this WorkflowDefinition definition)
 {
     var clientContext = definition.Context as ClientContext;
     var servicesManager = new WorkflowServicesManager(clientContext, clientContext.Web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     deploymentService.DeleteDefinition(definition.Id);
     clientContext.ExecuteQueryRetry();
 }
        protected WorkflowDefinition GetWorkflowDefinition(object host,
            ClientContext hostclientContext,
            Web web,
            SP2013WorkflowSubscriptionDefinition workflowSubscriptionModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving workflow definition by DisplayName: [{0}]", workflowSubscriptionModel.WorkflowDisplayName);

            var context = hostclientContext;
            //var web = list.ParentWeb;

            var workflowServiceManager = new WorkflowServicesManager(hostclientContext, web);

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

            context.ExecuteQueryWithTrace();

            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 result = publishedWorkflows.FirstOrDefault(w => w.DisplayName == workflowSubscriptionModel.WorkflowDisplayName);

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

            return result;
        }
Exemplo n.º 44
0
 /// <summary>
 /// Returns a workflow definition
 /// </summary>
 /// <param name="web"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 public static WorkflowDefinition GetWorkflowDefinition(this Web web, Guid id)
 {
     var servicesManager = new WorkflowServicesManager(web.Context, web);
     var deploymentService = servicesManager.GetWorkflowDeploymentService();
     var definition = deploymentService.GetDefinition(id);
     web.Context.Load(definition);
     web.Context.ExecuteQueryRetry();
     return definition;
 }
Exemplo n.º 45
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Get a reference to infrastructural services
                WorkflowServicesManager servicesManager = null;

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

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

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

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

                        int retryCount = 5;
                        int retryAttempts = 1;
                        int delay = 2000;

                        while (retryAttempts <= retryCount)
                        {
                            try
                            {

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

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

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

                                // Let's publish the Workflow Definition, if needed
                                if (templateDefinition.Published)
                                {
                                    deploymentService.PublishDefinition(newDefinition.Value);
                                    web.Context.ExecuteQueryRetry();
                                }

                                break; // no errors so exit loop
                            }
                            catch (Exception ex)
                            {
                                // check exception is due to connection closed issue
                                if (ex is ServerException && ((ServerException)ex).ServerErrorCode == -2130575223 &&
                                    ((ServerException)ex).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPException", StringComparison.InvariantCultureIgnoreCase) &&
                                    ((ServerException)ex).Message.Contains("A connection that was expected to be kept alive was closed by the server.")
                                    )
                                {
                                    WriteWarning(String.Format("Connection closed whilst adding Workflow Definition, trying again in {0}ms", delay), ProvisioningMessageType.Warning);

                                    Thread.Sleep(delay);

                                    retryAttempts++;
                                    delay = delay * 2; // double delay for next retry
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }


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

                    foreach (var subscription in template.Workflows.WorkflowSubscriptions)
                    {
                        Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription = null;

                        // Check if the subscription already exists before adding it, and 
                        // if already exists a subscription with the same name and with the same DefinitionId, 
                        // it is a duplicate and we just need to update it
                        string subscriptionName;
                        if (subscription.PropertyDefinitions.TryGetValue("SharePointWorkflowContext.Subscription.Name", out subscriptionName) &&
                            existingWorkflowSubscriptions.Any(s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId))
                        {
                            // Thus, delete it before adding it again!
                            WriteWarning(string.Format("Workflow Subscription '{0}' already exists. It will be updated.", subscription.Name), ProvisioningMessageType.Warning);
                            workflowSubscription = existingWorkflowSubscriptions.FirstOrDefault((s => s.PropertyDefinitions["SharePointWorkflowContext.Subscription.Name"] == subscriptionName && s.DefinitionId == subscription.DefinitionId));

                            if (workflowSubscription != null)
                            {
                                subscriptionService.DeleteSubscription(workflowSubscription.Id);
                                web.Context.ExecuteQueryRetry();
                            }
                        }

#if ONPREMISES
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                            {
                                DefinitionId = subscription.DefinitionId,
                                Enabled = subscription.Enabled,
                                EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                                EventTypes = subscription.EventTypes,
                                ManualStartBypassesActivationLimit =  subscription.ManualStartBypassesActivationLimit,
                                Name =  subscription.Name,
                                StatusFieldName = subscription.StatusFieldName,
                            };
#else
                        // Create the WorkflowDefinition instance
                        workflowSubscription =
                            new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
                            {
                                DefinitionId = subscription.DefinitionId,
                                Enabled = subscription.Enabled,
                                EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
                                EventTypes = subscription.EventTypes,
                                ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
                                Name = subscription.Name,
                                ParentContentTypeId = subscription.ParentContentTypeId,
                                StatusFieldName = subscription.StatusFieldName,
                            };
#endif

                        if (workflowSubscription != null)
                        {
                            foreach (var propertyDefinition in subscription.PropertyDefinitions
                                .Where(d => d.Key == "TaskListId" ||
                                            d.Key == "HistoryListId" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Id" ||
                                            d.Key == "SharePointWorkflowContext.Subscription.Name" ||
                                            d.Key == "CreatedBySPD"))
                            {
                                workflowSubscription.SetProperty(propertyDefinition.Key, parser.ParseString(propertyDefinition.Value));
                            }
                            if (!String.IsNullOrEmpty(subscription.ListId))
                            {
                                // It is a List Workflow
                                Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
                                subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
                            }
                            else
                            {
                                // It is a Site Workflow
                                subscriptionService.PublishSubscription(workflowSubscription);
                            }
                            web.Context.ExecuteQueryRetry();
                        }
                    }
                }
            }

            return parser;
        }