Social Icons

Pages

Monday, May 13, 2013

Creating SharePoint Task using Client Object Model (C#)

In this post I'm going to show how to create new Task using Client Object model.
 

Step: 1 Add the SharePoint Reference
             Refer this article 

Step: 2  Add the SharePoint namespace
 using Microsoft.SharePoint.Client;

Step: 3 Here is the sample code
       public string CreateTask(string Url, string UserName, string Password, string listNAme, string Title, string Body, string Status, string StartDate, string DueDate, string PercentComplete, string AssignedTo, string Priority, string Reference, string ReferenceID, DataTable dtSelectedPredecessors)

       {

           try
           {
               ClientContext context = new ClientContext(Url);
               context.Credentials = new NetworkCredential(UserName, Password);
               context.Load(web);
               List list = web.Lists.GetByTitle(listNAme);
               ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();
               ListItem newItem = list.AddItem(listItemCreationInformation);
               newItem["Title"] = Title;
               newItem["Body"] = Body;
               newItem["ReferenceID"] = ReferenceID;
               newItem["Reference"] = Reference;
               newItem["Status"] = Status;
               if (StartDate != "")
                   newItem["StartDate"] = StartDate;
               if (DueDate != "")
                   newItem["DueDate"] = DueDate;
               newItem["PercentComplete"] = PercentComplete;
               newItem["Priority"] = Priority;
               if (AssignedTo != "")
               {
                   User user = web.EnsureUser(AssignedTo);
                   newItem["AssignedTo"] = user;
               }
               else
               {
                   newItem["AssignedTo"] = AssignedTo;
               }
               if (dtSelectedPredecessors != null && dtSelectedPredecessors.Rows.Count > 0)
               {
                   FieldLookupValue[] LookupValuecoll = new FieldLookupValue[dtSelectedPredecessors.Rows.Count];
                   for (int i = 0; i < dtSelectedPredecessors.Rows.Count; i++)
                   {
                       LookupValuecoll[i] = new FieldLookupValue();
                       LookupValuecoll[i].LookupId = Convert.ToInt32(dtSelectedPredecessors.Rows[i]["itemID"].ToString());
                   }
                   newItem["Predecessors"] = LookupValuecoll;
               }
               newItem.Update();
               context.ExecuteQuery();
               context.Load(newItem);
               return "";
           }
           catch (Exception ex)
           {

               return ex.Message;
           }
       }
Reference :   http://msdn.microsoft.com/en-us/library/ee537013%28v=office.14%29.aspx 

1 comment:

  1. Hello,
    Its a good tutorial.
    I have a problem. I cant add multi user to one tasks.

    ReplyDelete