The following code sample illustrates how to associate a workflow to a list based on the workflow name.
public static void CreateListAssociation(SPWeb web, string listName,
string templateName, SPList historyList,
SPList taskList, string workflowName,
AssociationType associationType, bool enabled,
bool contentTypePushDown, bool allowAsyncManualStart,
string description, bool allowManual,
string associationData, bool autoStartChange,
int autoCleanupDays, bool autoStartCreate,
bool lockItem, bool markedForDelete,
bool removeIfExist, string contentTypeName)
{ LogHelper.LogMethodStart(logger, "SPListHelper", "AssociateWorkFlow");
SPList list = GetList(web, listName);
SPWorkflowTemplate workflowTemplate = SPWorkFlowHelper.GetWorkFlowTemplate(templateName, web);
ValidationHelper.VerifyObjectArgument(workflowTemplate, "workflowTemplate");
if (string.IsNullOrEmpty(workflowName))
workflowName = workflowTemplate.Name;
SPWorkflowAssociation association;
if (associationType == AssociationType.ContentType)
{ association = SPWorkflowAssociation.CreateListContentTypeAssociation(workflowTemplate, workflowName,
taskList, historyList);
}
else
association = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, workflowName,
taskList, historyList);
association.ContentTypePushDown = contentTypePushDown;
association.AllowAsyncManualStart = allowAsyncManualStart;
association.Description = description;
association.AllowManual = allowManual;
association.AssociationData = associationData;
association.AutoCleanupDays = autoCleanupDays;
association.AutoStartChange = autoStartChange;
association.AutoStartCreate = autoStartCreate;
association.LockItem = lockItem;
association.MarkedForDelete = markedForDelete;
foreach (SPWorkflowAssociation workflowAssociation in list.WorkflowAssociations)
{ if (workflowAssociation.Name == workflowName)
{ if (removeIfExist)
{ list.WorkflowAssociations.Remove(workflowAssociation);
}
else
{ LogHelper.LogWarning(logger, "SPListHelper",
"Unable to associate workflow as it's already " +
"associated and RemoveIfExist is false");
return;
}
break;
}
}
if (associationType == AssociationType.List)
{ list.WorkflowAssociations.Add(association);
association.Enabled = enabled;
}
else
{ ValidationHelper.VerifyStringArgument(contentTypeName, "contentTypeName");
bool contentTypeFound = false;
foreach (SPContentType contentType in list.ContentTypes)
{ if (contentType.Name.ToLower() == contentTypeName.ToLower())
{ contentType.WorkflowAssociations.Add(association);
association.Enabled = enabled;
contentTypeFound = true;
break;
}
}
if (! contentTypeFound)
LogHelper.LogWarning(logger,
"Cannot find this content type '" + contentTypeName +
"' on this list : '" + list.Title + "'");
}
LogHelper.LogMethodEnd(logger, "SPListHelper", "AssociateWorkFlow");
}