I have the following code running in a Visual Studio workflow. I am trying to specify the user who is adding list items in the code because I guess the system account (default for VS) will not allow declarative workflows to start. The declarative WF's are not started from this code but from "item updated" on the list. The WF errors out in SP with the following error:
Error in workflow! Object reference not set to an instance of an object.
SPUser user = SPContext.Current.Web.AllUsers["wgl\\username"];
SPUserToken token = user.UserToken;
using (SPSite site = new SPSite(workflowProperties.SiteId, token))
{
using (SPWeb web = site.OpenWeb(workflowProperties.WebId))
{
SPList list = web.Lists["Approvals"];
SPListItem item = list.Items.Add();
item["Title"] = "ECO Approval";
item["Approval Type"] = approvalType;
item["Approver"] = workflowProperties.Item[approverColumn];
item["ECO ID"] = workflowProperties.Item["ID"];
item["ECO Number"] = web.Url + "/Lists/ECO/DispForm.aspx?ID=" + workflowProperties.ItemId + ", " + workflowProperties.ItemId;
item.Update();
SPWorkflowManager objWorkflowManager = null;
SPWorkflowAssociationCollection objWorkflowAssociationCollection = null;
objWorkflowManager = item.Web.Site.WorkflowManager;
objWorkflowAssociationCollection = item.ParentList.WorkflowAssociations;
foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection)
{
SPWorkflow.CreateHistoryEvent(this.workflowProperties.List.ParentWeb, workflowId, 0, workflowProperties.OriginatorUser, TimeSpan.MinValue, "WorkFlow " + objWorkflowAssociation.Name, "WorkFlow " + objWorkflowAssociation.Name, "WorkFlow " + objWorkflowAssociation.Name);
if (objWorkflowAssociation.Name == "Approval Workflow")
{
site.WorkflowManager.StartWorkflow(item, objWorkflowAssociation, objWorkflowAssociation.AssociationData);
}
}
}
}
The only thing that was changed was adding:
SPUser user = SPContext.Current.Web.AllUsers["wgl\\switter"];
SPUserToken token = user.UserToken;
using (SPSite site = new SPSite(workflowProperties.SiteId, token))