MOSS provides a couple of ways for you to designate how a workflow should start at association time. You can have the users start it manually, or you can have it start automatically when a new item is created or updated. You may find a need at some point to programmatically start a workflow, like from another application, or from some custom code running in MOSS. Thankfully, it’s a fairly straightforward process.
To start a workflow, you’ll use the StartWorkflow() method.
spSite.WorkflowManager.StartWorkflow(SPListItem spListItem, SPWorkflowAssociation associationTemplate, string initiationData);
As you can see, you’ll need a few parameters – the only tricky parameter is the initiation data XML string. To build the string, it’s easiest to first create a class that has all of the properties needed for initiation, and then serialize that class. The initiation data would mirror whatever data you are normally collecting in the workflow’s initiation form.
CREATE THE CLASS:
[Serializable()]
public class InitData
{
private string _field1 = default(string);
public string Field1
{
get
{
return this._field1;
}
set
{
this._field1 = value;
}
}
private string _field2 = default(string);
public string Field2
{
get
{
return this._field2;
}
set
{
this._field2 = value;
}
}
}
START WF CODE:
The example assumes you have an SPSite object spSite, an SPList object spList, and an SPListItem object spListItem.
First get the SPWorkflowAssociation object for the workflow on the current list:
const string WF_GUID_STRING = "DC904E02-BEBE-4581-AA4F-AE4E843D1111"; //GUID for the workflow (from workflow.xml definition file)
SPWorkflowAssociation associationTemplate= spList.WorkflowAssociations.GetAssociationByBaseID(new Guid(WF_GUID_STRING));
Now we’ll define the initiationData parameter. Note the private string method below.
string initiationData = getInitXmlString();
OK- we’re all set to start the workflow.
SPWorkflow myWorkflow = spSite.WorkflowManager.StartWorkflow(spListItem, associationTemplate, initiationData);
This method first creates and populates an InitData object with initiation data, and then serializes the object to an XML string that can be passed into the StartWorkflow method.
private string getInitXmlString ()
{
InitData data = new InitData();
data.Field1 = <some value>;
data.Field2 = <some value>;
//etc…
using (MemoryStream stream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(typeof(InitData));
serializer.Serialize(stream, data);
stream.Position = 0;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Encoding.UTF8.GetString(bytes);
}
}