public static void CreateAssociation(ref ClientContext clientContext, ref WorkflowServicesManager wfsm, Guid workflowDefinitionId, Guid listId, Guid historyListId, Guid taskListId)
        {
            WorkflowSubscriptionService subservice = wfsm.GetWorkflowSubscriptionService();

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

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

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

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

            //create association
            subservice.PublishSubscriptionForList(newSubscription, listId);
            clientContext.ExecuteQuery();
            Console.WriteLine("Workflow association created!");
            Console.ReadLine();
        }
        /// <summary>
        /// List all workflow associations for the specified workflow.
        /// </summary>
        public static void ListAllAssociations(ref ClientContext clientConext,
                                               ref WorkflowServicesManager wfServicesManager)
        {
            WorkflowSubscriptionService subService = wfServicesManager.GetWorkflowSubscriptionService();

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

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

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

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

            // write all associations out
            foreach (var wfSubscription in wfSubscriptions)
            {
                Console.WriteLine("{0} - {1}",
                                  wfSubscription.Id,
                                  wfSubscription.Name
                                  );
            }
        }
        /// <summary>
        /// Retrieves a single workflow subscription.
        /// </summary>
        public static WorkflowSubscription GetOneSubscription(ref ClientContext clientContext,
                                                              ref WorkflowServicesManager wfServicesManager)
        {
            WorkflowSubscriptionService subService = wfServicesManager.GetWorkflowSubscriptionService();

            WorkflowSubscriptionCollection wfSubscriptions = subService.EnumerateSubscriptions();

            clientContext.Load(wfSubscriptions);
            clientContext.ExecuteQuery();

            return(wfSubscriptions.FirstOrDefault());
        }
        /// <summary>
        /// Create a new workflow association (subscription).
        /// </summary>
        public static void CreateAssociation(ref ClientContext clientConext,
                                             ref WorkflowServicesManager wfServicesManager,
                                             Guid definitionId,
                                             Guid listId,
                                             Guid historyListId,
                                             Guid taskListId)
        {
            WorkflowSubscriptionService subService = wfServicesManager.GetWorkflowSubscriptionService();

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

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

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

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

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

            // create the association
            subService.PublishSubscriptionForList(newSubscription, listId); // creates association on list
            //subService.PublishSubscription(newSubscription);              // creates association on current site
            clientConext.ExecuteQuery();
            Console.WriteLine("Workflow association created!");
        }
        public static void RemoveAssociation(ref ClientContext clientContext, ref WorkflowServicesManager wfsm, Guid workflowDefinitionId, Guid listId, Guid historyListId, Guid taskListId)
        {
            WorkflowSubscriptionService subservice = wfsm.GetWorkflowSubscriptionService();

            Console.WriteLine();
            Console.WriteLine("Getting Existing subscription");
            WorkflowSubscriptionCollection wfsubscriptions = subservice.EnumerateSubscriptionsByDefinition(workflowDefinitionId);

            clientContext.Load(wfsubscriptions);
            clientContext.ExecuteQuery();
            foreach (var wfsub in wfsubscriptions)
            {
                Console.WriteLine("Subscription ID:{0} - Subscription Name:{1}", wfsub.DefinitionId, wfsub.Name);
            }
            var    LastWFDefId   = wfsubscriptions.Last().Id;
            string LastWFDefName = wfsubscriptions.Last().Name;

            Console.WriteLine("Last Subscription ID:{0} - Last Subscription ID:{1} ", LastWFDefId.ToString(), LastWFDefName);
            Console.WriteLine("Removing Workflow Association");
            subservice.DeleteSubscription(LastWFDefId);
        }
        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            if (properties.EventType != SPRemoteEventType.ItemAdded)
            {
                return;
            }

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

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

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

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

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

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

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

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

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

                    Web web = clientContext.Web;

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

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

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

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

                    clientContext.ExecuteQuery();

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

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

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

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

                    clientContext.ExecuteQuery();

                    return(true);
                }
            }



            catch (Exception err)
            {
                responseMsg = err.Message;
                return(false);
            }
        }