This blog is moved to
http://amalhashim.wordpress.com

Saturday, October 31, 2009

Using Sharepoint List Webservice

Sharepoint exposes some really useful webservices. One among the most useful is the List Webservices.

We can take the webreference from the following location

http://mossserver/_vti_bin/lists.asmx

Once we have added the webservice, we can use following generic method to call webservice

XmlNode CallWebService(bool isRecursive, ListsService listService,
string listName, string queryObj, string viewID, string viewFieldsInnerXml)
{
try
{
NetworkCredential credential = new NetworkCredential();
credential.UserName = "UserName";
credential.Password = "Password";
credential.Domain = "Domain";
listService.Credentials = credential;

// Instantiate an XmlDocument object
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

string viewName = string.Empty;
if (string.Empty != viewID)
{
viewName = viewID;
}
string rowLimit = "150";

System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");

if (isRecursive)
queryOptions.InnerXml = "<ViewAttributes Scope=\"Recursive\" />";
else
queryOptions.InnerXml = "";

if (string.Empty == queryObj)
{
query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
"<Value Type=\"Counter\">0</Value></Gt></Where>";
}
else
{
query.InnerXml = queryObj;
}

// Assign View fields
if (string.Empty != viewFieldsInnerXml)
{
viewFields.InnerXml = viewFieldsInnerXml;
}
else
{
viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
}
System.Xml.XmlNode nodeListItems =
listService.GetListItems(listName, viewName, query,
viewFields, rowLimit, queryOptions, null);

return nodeListItems;
}
catch (Exception ex)
{
throw ex;
}
}

You can use this generic method for getting the list items.

Pass true to “IsRecursive” if you want to get items inside folder.

Example:
string fields = "<FieldRef Name=\"FieldName1\" />
<FieldRef Name=\"FieldName2\" />";
XmlNode nodeListItems = CallWebService(true, l, "Answer Choices",
string.Empty, string.Empty, fields);
foreach (System.Xml.XmlNode listItem in nodeListItems)
{
if (listItem.ChildNodes.Count > 0)
{
foreach (XmlNode node in listItem.ChildNodes)
{
string choice = node.Attributes["ows_Title"]
.Value;
}
}
}

No comments: