Programmatically starting a workflow under specific User context

In SharePoint there are many scenarios we have to start workflow programmatically. This is very easy to achieve and there are plenty of blogs and references you will find which will show you how to start workflow programmatically.

There are few cases where you may want to start workflow under specific User context. To achieve that you simply have pass the user token when creating SPSite object.

In the following example we are going to start the workflow from an event receiver when someone adds a new document. We will use Author field to get the Author of the workflow and then pass that user token to the SPSite oject and then start the workflow programmatically.

public override void ItemAdded(SPItemEventPropertiesproperties)

{
SPListItem itemAdded = properties.ListItem;
// Get the Created By field value
String authorUser = itemAdded["Author"].ToString();
// Get the ID of the user.
int userID = Convert.ToInt32(authorUser.Substring(0, authorUser.IndexOf(";#")));
SPUser Author = properties.Web.ParentWeb.AllUsers.GetByID(userID);
SPUserToken authorToken = Author.UserToken;
// Open the SPSite again by passing the user context that we want our workflow to run under
using (SPSite site = newSPSite(properties.Web.Url, authorToken))
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["DOCUMENT LIBRARY"];
SPListItem lstItem = list.GetItemById(itemAdded.ID);
SPWorkflowManager manager = site.WorkflowManager;
SPWorkflowAssociationCollectionassoCollection = lstItem.ContentType.WorkflowAssociations;
// I am assuming that there is only one workflow in workflow association collection
// If you have more workflows then simply use If condition to start specific workflow.
foreach (SPWorkflowAssociationasso in assoCollection)
{
manager.StartWorkflow(lstItem, asso, asso.AssociationData.);
}
}
}