Wednesday, July 15, 2009

Associating workflow with List, SPWorkflowAssociation, CreateListAssociation

The best place to me attach workflow to a list is inside the FeatureReceiver's activated method and to revoke this place remove method inside FeatureReciever's deactivated event
I have already discuss about creating feature receiver, so just focusing here is the SPWorkflowAssociation and CreateListAssociation.
In FeatureActivated method call this method with listInstance, string containig WF GUID, a workfow Association name and the web.

public void AddDFWorkflow(SPList myList, string workflowTemplateGuid, string workflowAssocName, SPWeb web)
{
//myList // List to associate workflow to
SPList historyList = null; // Workflow history list
SPList taskList = null; // Workflow tasks list
//workflowTemplateGuid // Workflow template Guid
SPWorkflowTemplate workflowTemplate = null; // Workflow template
SPWorkflowAssociation workflowAssociation = null; // Workflow association
//workflowAssocName // Workflow association name
workflowTemplate = web.WorkflowTemplates[new Guid(workflowTemplateGuid)];
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();
}
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();
}
web.AllowUnsafeUpdates = true;
try
{
// Create workflow association
workflowAssociation = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, workflowAssocName, taskList, historyList);
// Set workflow parameters
workflowAssociation.AllowManual = false;
workflowAssociation.AutoStartCreate = false;
workflowAssociation.AutoStartChange = false;
// Add workflow association to my list
myList.AddWorkflowAssociation(workflowAssociation);
// Enable workflow
workflowAssociation.Enabled = true;
}
catch (Exception ex)
{ }
finally
{
web.AllowUnsafeUpdates = false;
}
}

In feature deactivated method call this method

public void RemoveDFWorkflow(SPList myList, string workflowAssocName, SPWeb web)
{
try
{
if (myList.WorkflowAssociations.Count > 0)
{
SPWorkflowAssociation _association = null;
foreach (SPWorkflowAssociation association in myList.WorkflowAssociations)
{
if (association.Name.Equals(workflowAssocName))
{
_association = association;
break;
}
}
if (_association != null)
myList.RemoveWorkflowAssociation(_association);
myList.Update();
}
}
catch (Exception ex)
{}
}


Enjoy!!!

No comments:

Post a Comment