Archive

Posts Tagged ‘Workflow’

SharePoint – Programatically Starting a Workflow

Here is a code snippet I recently developed for starting a sharepoint workflow from code behind.

public void StartWorkFlow(string listName, int itemID, string workflowName)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
        {
            using (SPWeb oWeb = oSite.OpenWeb())
            {
                oWeb.AllowUnsafeUpdates = true;
                SPList oList = oWeb.Lists[listName];
                SPListItem oItem = list.GetItemById(itemID);
                SPWorkflowManager wfManager = oSite.WorkflowManager;

                foreach (SPWorkflowAssociation association in oList.WorkflowAssociations)
                {
                    if (association.Name == workflowName)
                    {
                        string associationData = association.AssociationData;
                        wfManager.StartWorkflow(oItem, association, associationData);                                
                        break;
                    }
                }
                oWeb.AllowUnsafeUpdates = false;
            }
        }
    });
}
Advertisements
Categories: SharePoint, SharePoint 2010 Tags:

SharePoint – Using C# change workflow task owner

February 13, 2013 2 comments

Assume we have a workflow task as below

sc1

Currently its assigned to “Amal Hashim”. We can change this to another user say, “Administrator” using following snippet

using (SPSite site = new SPSite("http://myteamsite:2012/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPUser user = web.SiteUsers["myad\\administrator"];
        SPListItem taskItem = web.Lists["Shared Documents"].Items[0];

        SPWorkflowTaskCollection taskCollection = new 
SPWorkflowTaskCollection(taskItem, new SPWorkflowFilter());

        foreach (SPWorkflowTask task in taskCollection)
        {
            Hashtable ht = new Hashtable();
            ht[SPBuiltInFieldId.AssignedTo] = user;
            SPWorkflowTask.AlterTask((task as SPListItem), ht, true);
        }
    }
}

After executing this, we will get

sc2

Categories: C#, SharePoint, SharePoint 2010 Tags: