Saturday, July 13, 2013

Programmatically Approve/Reject Task in SharePoint 2010

Hi Guys, 
Hope all of you doing well.

As you know, sometimes we do not use out of the box features of SharePoint because sometimes we need to achieve it through programmatically. So, Today here I am posting a article for Approve or Reject workflow task programmatically using c#. 

Use below C# code to Approve Task Item programmatically 

int _itemId = 1;

            using (SPSite _siite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        _site.AllowUnsafeUpdates = true;
                        SPList _taskList = _web.Lists["Tasks"];
                        SPListItem _taskItem = _taskList.GetItemById(_itemId);

                        if (_taskItem != null)
                        {
                            Hashtable ht = new Hashtable();
                            ht[SPBuiltInFieldId.Completed] = "TRUE";
                            ht["Completed"] = "TRUE";
                            ht[SPBuiltInFieldId.PercentComplete] = 1.0f;
                            ht["PercentComplete"] = 1.0f;
                            ht["Status"] = "Completed";
                            ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)_taskItem.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
                      
                            ht[SPBuiltInFieldId.WorkflowOutcome] = "Approved";
                            ht["TaskStatus"] = "Approved";             
                            ht["FormData"] = SPWorkflowStatus.Completed;
                            ht["ows_FieldName_Comments"] = "Approver comments will be here";

                            _web.AllowUnsafeUpdates = true;
                            bool alterstatus = true;
                            while (!(alterstatus = SPWorkflowTask.AlterTask(_taskItem, ht, true)))
                            {
                                System.Threading.Thread.Sleep(1000);
                                alterstatus = SPWorkflowTask.AlterTask(_taskItem, ht, true);
                            }
                           
                            _web.AllowUnsafeUpdates = false;
                        }
                    });
                }
            }







To Reject Task Item Replace below lines in above code.....

          ht[SPBuiltInFieldId.WorkflowOutcome] = "Rejected";
          ht["TaskStatus"] = "Rejected";


Thats' it.

If you find this article suitable, please do not forgot to share this !!
  

13 comments:

  1. Hi Mohit,
    I came across your blog and the i'm using the same code in one of my InfoPath forms.
    However, I would like to know how to Reassign a task using code C#.
    Can you please let me know what fields do I have to populate/use in order to accomplish Reassign.

    Your help is greatly appreciated.

    Bill

    ReplyDelete
  2. Hi Bill,

    If you do not want to remove your previous task than I suggest you to create new task. Use below code to create new task...

    SPList _taskList = _web.Lists["Tasks"];

    SPListItem _taskItem = _taskList.Items.Add();
    _taskItem["Title"] = "Your task item Title";
    _taskItem["Description"] = "Your task Description";

    SPUser _assignToUser= _web.EnsureUser(@"domainName\userName");

    SPFieldUserValue assignToValue = new SPFieldUserValue(_web, _assignToUser.ID, _assignToUser.Name);
    _taskItem["AssignedTo"] = assignToValue;
    _taskItem.Update();


    Hope this will help you.


    Mohit

    ReplyDelete
  3. Ok thanks ,
    I will give that a try.
    Bill

    ReplyDelete
  4. Hey Mohit,

    I tried your suggestion regarding task reassign . I was able to change the status, and task version for user A so if you edit the form the buttons (approve, reject Reassign) are hidden. I was able to create a new task for User B however, this new task is not associated with the workflow which User A had a task assigned to.
    Basically, it looks like I disabled the task for user A and a record was entered into the Task list ,however this new record is not related to the currently running workflow. the new record has the same title as the pervious tasks but when I open the current running workflow the task is not there, it is just a record with no workflow association.
    Your helps is greatly appreciated.

    ReplyDelete
  5. Hi Mohit
    Thanks for your post,,
    i'm trying to run this code on inforpath button to approve task , but when I clicked button I get this error
    (System.IO.FileNotFoundException
    Could not load file or assembly 'Microsoft.SharePoint.Library, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified)

    do you have any idea?
    I'm working on default SharePoint task list with approval process and I need to approve tasks from InfoPath from ,,
    thank you again

    ReplyDelete
  6. After trying and trying , i'm published the form and it's work perfectly ,,, thank you Mohit and all

    ReplyDelete
  7. Hi Ammar,
    I never used this code in Info path Form but I am using it in Visual Webparts and It is working fine for me. I do not have idea what different we need to do in InfoPath. Please share if you found the solution.

    Thank you !
    Mohit

    ReplyDelete
    Replies
    1. Hi Mohit
      I was used the same code that you are mentioned above for approve and reject on InfoPath form button event also I add (using System.Security.Permissions;
      [assembly: FileIOPermission(SecurityAction.RequestMinimum, Unrestricted = true)]) ,
      by the way I passed task id from InfoPath field that is prompt task id from task list .
      thank you for your helpful post
      Ammar

      Delete
  8. i have used same code but task is getting completed but it is not getting approved

    ReplyDelete
  9. I tried to put it in my infopath form button, and it got lots of errors when I build it.

    The name 'SPSecurity' does not exist in the current context
    The type or namespace name 'Hashtable' could not be found (are you missing a using directive or an assembly reference?)
    The type or namespace name 'Hashtable' could not be found (are you missing a using directive or an assembly reference?)
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    The type or namespace name 'CultureInfo' could not be found (are you missing a using directive or an assembly reference?)
    The best overloaded method match for 'Microsoft.SharePoint.SPResource.GetString(string, params object[])' has some invalid arguments
    Argument '1': cannot convert from 'CultureInfo' to 'string'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    The name 'SPWorkflowStatus' does not exist in the current context
    Cannot apply indexing with [] to an expression of type 'Hashtable'
    The name 'SPWorkflowTask' does not exist in the current context
    The name 'SPWorkflowTask' does not exist in the current context


    May I know what should I do to solve the above? I'm not familiar with VS and C# Many thanks in advance.

    ReplyDelete
  10. turns out it doesn't work with SPD 2010 which come with VS 2005, what should I do if I wanna use the code with SPD 2010? Your help would greatly be appreciated. Thank you.

    ReplyDelete
  11. how to update workflow outcome column value..

    ReplyDelete
  12. my column outcome also not ubpdated

    ReplyDelete