Sunday, January 18, 2009

XLinq To Generate Batch Element For SharePoint ListService

In my article (http://dotnetstep.blogspot.com/2009/01/update-datetime-column-using-webservice.html) i used SharePoint List Service to update SharePoint ListItems. In that article i manually set batchElement.InnerXml property with Xml.

When there is to many row and you want to generate it automatically then you can use XLinq.

In following example first select all items from orders List then use item id and update each item orderdate and orderdatetime column with current date and current datetime respectively.

Lists lst = new Lists();
lst.Url = “http://<your site>/_vti_bin/lists.asmx”;
lst.Credentials = new System.Net.NetworkCredential("test", "test"); // Site Administrator username and password
XmlNode resultNode = lst.GetListItems("Orders", String.Empty, null, null, int.MaxValue.ToString(), null, String.Empty);

// Use XElement To Generate Batch Element Automatically

XElement orders = XElement.Parse(resultNode.OuterXml);
XName name = XName.Get("data","urn:schemas-microsoft-com:rowset");
int methodsequence=1;
XElement updatexml =
new XElement("Batch", new XAttribute("OnError","Continue"),
from order in orders.Element(name).Elements()
// you can also use where condition over here
// for eg. where order.Attribure(“ows_ID”).value = “2”

select new  XElement("Method", 
new XAttribute("ID", (methodsequence++).ToString()), 
new XAttribute("Cmd", "Update"),
new XElement("Field", new XAttribute("Name", "ID"), order.Attribute("ows_ID").Value),
new XElement("Field",new XAttribute("Name","OrderDate"),DateTime.Now.SharepointFormatDate()),
new XElement("Field", new XAttribute("Name", "OrderDateTime"), DateTime.Now.SharepointFormatDateTime())));


Now Convert XElement to XmlNode as UpdateListItems only accept XmlNode as parameter.

XmlDocument doc=  new XmlDocument();
doc.LoadXml(updatexml.ToString());
lst.UpdateListItems("Orders",doc.FirstChild);

No comments: