Preaching SharePoint

Batch Updaing list items using SharePoint Web Services


I was desperately looking for an example where I can update several SharePoint list items with a condition using Web Services. Found the perfect solution from MSDN. 
You use ProcessBatchData command of an SPWeb object to update multiple items that is a resultset of a CAML query.

Here is code for a console application that you can use -

// Set up the variables to be used.
StringBuilder methodBuilder = new StringBuilder();
string batch = string.Empty;
DateTime currentDate = DateTime.Now;
string formattedDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(currentDate);

string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
  "<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

string methodFormat = "<Method ID=\"{0}\">" +
"<SetList>{1}</SetList>" +
"<SetVar Name=\"Cmd\">Save</SetVar>" +
"<SetVar Name=\"ID\">{2}</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#Processed\">{3}</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#Processed_x0020_Date\">{4}</SetVar>" +
"</Method>";

using (SPSite site = new SPSite("http://localhost"))
{
   using (SPWeb web = site.OpenWeb())
   {

      // Get the list containing the items to update.
      SPList list = web.Lists["Processed Documents"];
      string listGuid = list.ID.ToString();

      // Query to get the unprocessed items.
      SPQuery query = new SPQuery();
      query.Query = "<Where><Neq><FieldRef Name='Processed'/>
        <Value Type='Choice'>1</Value></Neq></Where>";
      query.ViewAttributes = "Scope='Recursive'";
      SPListItemCollection unprocessedItems = list.GetItems(query);

      // Build the CAML update commands.
      for (int i = 0; i < unprocessedItems.Count; i++)
      {
         int itemID = unprocessedItems[i].ID;
         methodBuilder.AppendFormat(methodFormat, itemID, listGuid, itemID, 1, formattedDate);
      }

      // Put the pieces together.
      batch = string.Format(batchFormat, methodBuilder.ToString());

      // Process the batch of commands.
      string batchReturn = web.ProcessBatchData(batch);
   }
}
}





Responses

0 Respones to "Batch Updaing list items using SharePoint Web Services"

Post a Comment

 

Do you want SharePoint 2013 to inherit Metro Style design?

Search This Blog

Return to top of page Copyright © 2010 | Platinum Theme Converted into Blogger Template by HackTutors