Thursday, July 16, 2009

Code Snippets : SharePoint SOAP Services

SharePoint SOAP Services are great. Easy to use, integrate with other system and access from client side. Most of the time developer do not have access to SharePoint server or have limited access to server. Many time writing simple C# code on server and running console application saves time.

Automating preparative copy, move, setting content etc. can be done fast by using services.

So, without having full access to server such task can be performed by using SharePoint SOAP based web services. 

Code Assumes that SharePoint Services references are added to your project. e.g. Copy Service is at http://server/_vti_bin/Copy.asmx and namespace for Services is SharePointList.SPServices. Same for Lists.asmx.

1) Copy Document Library Item
Below code copies List Item from one library to other library on same server.
SharePointList.SPServices.Copy CopyService = new SharePointList.SPServices.Copy();
SharePointList.SPServices.CopyResult CopyResult = new SharePointList.SPServices.CopyResult();
SharePointList.SPServices.CopyResult[] CopyResultArray = { CopyResult };

string []destURL = new string[] { "http://server/destDocLib/test.doc"};// Multiple destination
string sourceURL = "http://server/SourceDocLib/test.doc";
uint result = CopyService.CopyIntoItemsLocal(sourceURL, destURL, out CopyResultArray);
if (result == 0)
{
foreach (SharePointList.SPServices.CopyResult copyResult in CopyResultArray)
{
if (copyResult.ErrorMessage == null)
{
//Log success message here
}
else
{
//Log exception here
}
}
}
2) Set Document Library/List Column Value
Below code sets column value in specific list item

void setColumnValue(string listName, string ID, string columnName, string columnValue)
{
Lists wList = new Lists();
XmlDocument doc = new XmlDocument();
XmlElement newColumnValue = doc.CreateElement("Batch");
newColumnValue.SetAttribute("OnError", "Return");
newColumnValue.InnerXml = "" +
"" + ID + "" + columnValue + "" +
"
";
try
{
XmlNode returnValue = wList.UpdateListItems(listName, newColumnValue);
Console.WriteLine(returnValue.OuterXml);

}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine("Message:\n" + ex.Message + "\nDetail:\n" + ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace);
}
catch (Exception ex)
{
Console.WriteLine("Message:\n" + ex.Message + "\nDetail:\n" + ex.ToString() + "\nStackTrace:\n" + ex.StackTrace);
}
}

More code sample are in pipeline.