How to associate a worklow to a list programmatically
How to associate a worklow to a list programmatically |
|
Goal of this post Code example We assume that the variable web is a SPWeb object containing the list we want to associate the workflow with. 1. Declare objects we are going to use SPList myList = null; // List to associate workflow to string myListName = null; // My list name SPList historyList = null; // Workflow history list SPList taskList = null; // Workflow tasks list string workflowTemplateGuid = null; // Workflow template Guid SPWorkflowTemplate workflowTemplate = null; // Workflow template SPWorkflowAssociation workflowAssociation = null; // Workflow association string workflowAssocName = null; // Workflow association name 2. Init Be sure to use the internal name of the list. And set the workflow association name, this will appair as workflow name in SharePoint list settings.myListName = "My list name"; workflowAssocName = "My Workflow"; 3. Get Workflow template If you want to use a custom workflow and know its template GUID, use the GUID string.workflowTemplateGuid = "BAD855B1-32CE-4bf1-A29E-463678304E1A";Instead you can get the workflow template GUID by using the GetTemplateByName method. workflowTemplate = web.WorkflowTemplates.GetTemplateByName( 4. Get or create workflow history and tasks lists. The history list is dedicated to workflows and it's based on the WorkflowHistory list template. Most of times you'll have to create it.// Try to get workflow history list try { historyList = web.Lists["Workflow History"]; } catch (ArgumentException exc) { // Create workflow history list Guid listGuid = web.Lists.Add("Workflow History", "", SPListTemplateType.WorkflowHistory); historyList = web.Lists[listGuid]; historyList.Hidden = true; historyList.Update(); }The tasks list is a common tasks list based on Tasks list template. If you want to create a specific tasks list for the workflow, don't use "Tasks" title for it. In the example we want to use a dedicated tasks list and will name it "Workflow Tasks". // Try to get workflow tasks list try { taskList = web.Lists["Workflow Tasks"]; } catch (ArgumentException exc) { // Create workflow tasks list Guid listGuid = web.Lists.Add("Workflow Tasks", "", SPListTemplateType.Tasks); taskList = web.Lists[listGuid]; taskList.Hidden = true; taskList.Update(); } 5. Create workflow association, configure it and associate it to the list. // Allow unsafe updates on web web.AllowUnsafeUpdates = true; |
Powered By D&J (URL:http://www.cnblogs.com/Areas/)