Ads

Saturday, 23 March 2013

C# code to attach a workflow to a sharepoint list programatically

SPWorkflowTemplate workflowTemplate = null;                // Workflow template
SPWorkflowAssociation workflowAssociation = null;         //Workflow association
SPList historyList = null;                                                     // Workflow history list
SPList taskList = null;                                                        // Workflow tasks list
SPList list = null;                                                               //Sharepoint List       
using (SPSite oSPsite = new SPSite("http://MyWebSite_URL/"))
{
    oSPsite.AllowUnsafeUpdates = true;

    using (SPWeb oSPWeb = oSPsite.OpenWeb())
    {                 

         web.AllowUnsafeUpdates = true;
         workflowTemplate = web.WorkflowTemplates.GetTemplateByName( "Template name",  
                                                             System.Globalization.CultureInfo.CurrentCulture);
         list  = oSPWeb.Lists["List Name"];     //List which we is going to associate the workflow           
         historyList = oSPWeb.Lists["Workflow History"];  //The list to which to log workflow history events.

         taskList = oSPWeb.Lists["Workflow Task"];      //The task list on which to create workflow tasks for this workflow
                                                                                                   association.
                  try
                {
                            // Create workflow association
                           workflowAssociation = SPWorkflowAssociation.CreateListAssociation(workflowTemplate,
                                                                 workflowAssocName, taskList, historyList);
                         // Set workflow parameters
                        workflowAssociation.AllowManual = false;
                        workflowAssociation.AutoStartCreate = true;
                        workflowAssociation.AutoStartChange = false;
                        // Add workflow association to my list
                       list.AddWorkflowAssociation(workflowAssociation);
                      // Enable workflow
                      workflowAssociation.Enabled = true;
              }
             finally
             {
                    web.AllowUnsafeUpdates = false;
             }
}

No comments:

Post a Comment

Ads