How to add, remove and start workflow programmatically?
Removing Association
1: SPSite site = new SPSite("https://localhost");
2: SPWeb web = site.OpenWeb();
3: SPList list = web.Lists["Shared Documents"];
4: SPWorkflowAssociation _association = null;
5: foreach (SPWorkflowAssociation association in list.WorkflowAssociations)
6: {
7: if (association.Name == "Approval")
8: {
9: _association = association;
10: break;
11: }
12: }
13: if(_association !=null)
14: list.RemoveWorkflowAssociation(_association);
Adding workflow to the library
1: SPSite site = new SPSite("https://localhost");
2: SPWeb web = site.OpenWeb();
3: SPList list = web.Lists["Shared Documents"];
4: SPList taskList = web.Lists["Tasks"];
5: SPList historyList = web.Lists["Workflow History"];
6: SPWorkflowTemplate _template = null;
7: foreach (SPWorkflowTemplate template in web.WorkflowTemplates)
8: {
9: if (template.Name == "Approval")
10: {
11: _template = template;
12: break;
13: }
14: }
15: SPWorkflowAssociation asso = SPWorkflowAssociation.CreateListAssociation(_template, _template.Name, taskList, historyList);
16: list.AddWorkflowAssociation(asso);
Starting workflow
1: SPSite site = new SPSite("https://localhost");
2: SPWeb web = site.OpenWeb();
3: SPList list = web.Lists["Shared Documents"];
4: SPWorkflowAssociation association = AddWorkflow(); // Above function to get the SPWorlflowAssociation object
5: SPWorkflowManager manager = site.WorkflowManager;
6: for (int idx = 0; idx < 10 ; idx++) // I'm assuming there would be atleast 10 items within the library
7: {
8: SPListItem item = list.Items[idx];
9: manager.StartWorkflow(item,association, "you can pass any data here",true);
10: }