PANVEGA’s Blog

DotNet Development, SharePoint Customizing, Silverlight, MS Infrastructure and other tips and tricks

Consuming Lists.asmx Webservice from SharePoint

Posted by PANVEGA on September 15, 2007

In this post I wanna shortly describe how to hanlde with SharePoint Webservice in this case I´m gonna show an examole with the lists.asmx Webservice. SharePoint (WSS 2.0) provides several web services that gives you access to different parts of the object model and its data, without the need to use the object model directly and without worrying where the data is stored in a farm deployment.

The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. To access this Web service set a Web reference to http://<site>/_vti_bin/Lists.asmx.

Note:

An important detail when programming against the SharePoint web services is to remember to set the .Url property of your web reference to point to the correct WSS team site. The lists.asmx web service is a virtual service and is by SharePoint magic available in all WSS sites, not only in the IIS virtual directory /_vti_bin/. In addition, remember to apply correct credentials for authentication.

Set the .Url like this http://<site>/_vti_bin/Lists.asmx. (avoid getting //_vti_bin/).

So why would we want to use the SharePoint webservice? All site page data and document data is stored in SQL server and compiled into SharePoint pages/documents upon request. It is not recommended that you tamper with the data directly in SQL server as it’s very easy to break a WSS site altogether very easily. That leaves 2 methods of accessing data from a SharePoint database, the SharePoint object model, or webservice.

A full list of webservice methods for things such as alerts and sites are available in the SharePoint Products and Technologies 2003 SDK. I’ll hopefully cover them all in time, but today we’ll focus on just the list webservice.

Here are the methods and their definitions as taken from the SDK:

AddAttachment – Adds an attachment to the specified list item in the specified list.
AddList – Creates a list in the current site based on the specified name, description, and list template ID.
DeleteAttachment – Removes the attachment from the specified list item.
DeleteList – Deletes the specified list.
GetAttachmentCollection – Returns a list of the URLs for attachments to the specified item.
GetList – Returns a schema for the specified list.
GetListAndView – Returns the list and view schemas for the specified list.
GetListCollection – Returns the names and GUIDs for all the lists in the site.
GetListItemChanges – Returns changes made to the list since the specified date and time.
GetListItems – Returns information about items in the list based on the specified query.
UpdateList – Updates a list based on the specified field definitions and list properties.
UpdateListItems – Adds, deletes, or updates the specified items in a list on the current site.

So lets get using this webservice. It’s worth reminding you that I’m using Visual Studio.Net 2003 for this (not VS 2005!). You can add a SharePoint webservice exactly the same way you’d add any other webservice, just right click on the references folder and then ‘Add Web Reference…”. Plant the url to sites webservice you wish to call in the next box, give it a decent name and click ok.

The first webservice method we’ll use is GetList. We can pass in the name of the list as a string as a parameter and it returns an XmlNode with the schema represented in the InnerXml value of the node. The most important piece of information you’ll get is the list guid as you’ll need this do use some of the various other list webservice methods. Here’s our first bit of code:


Site1.Lists listsWS = new SharePointWebservice1.Site1.Lists();
listsWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode list = listsWS.GetList(“Contacts”)
;

Once it’s completed go back to your contacts list on the SharePoint site and you’ll see a field for filling in the ‘Last Contacted’ date for all your contacts.

Note:

When the UseDefaultCredentials property on an instance of a client proxy class is set to true the client will use the default credentials to authenticate to the Web service. The Web service in this sample must be configured to support integrated Windows authentication in the IIS Configuration Permission to properly demonstrate passing default credentials.

The CredentialCache is used to store system credentials for Internet-based resources. By default, when the System.NET.Credential Cache.GetCredentials method is called this compares the URI authentication type provided with any stored in the cache and returns the first set of matching credentials. The DefaultCredentials property is used to represent the system credentials for the current security context in which the application is running. For client-side applications, these are typically the current users’ Windows credentials.

However, within ASP.NET applications these default credentials are either the logged-in user, or the current user being impersonated. It is also important to remember that this property only applies to NTLM, negotiate, and Kerberos based authentication.

Site1.Lists listsWS = new SharePointWebservice1.Site1.Lists();
listsWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode list = listsWS.GetList(“Contacts”);

XmlDocument doc = new XmlDocument();
XmlNode ndProperties = doc.CreateNode(XmlNode.Element, “List”, “”);
XmlAttribute ndTitleAttrib = (XmlAttribute)doc.CreateNode(XmlNodeType.Attribute, “Title”, “”);
XmlAttribute ndDescription = (XmlAttribute)doc.CreateNode(XmlNodeType.Attribute, “Description”, “”);
XmlNode ndNewFields = doc.CreateNode(XmlNodeType.Element, “Fields”, “”);

string listName = list.Attributes[”ID”].Value;
string listVersion = list.Attributes[”Version”].Value;

ndTitleAttrib.Value = “Contacts”;
ndDescription.Value = “My contacts list”;

ndProperties.Attributes.Append(ndTitleAttrib);
ndProperties.Attributes.Append(ndDescriptionAttrib);

ndNewFields.InnerXml = “<Method ID=’1′><Field Type=’DateTime’ DateOnly=’TRUE’ Required=’TRUE’
DisplayName=’Last Contacted’ FromBaseType=’TRUE’/></Method>
”;

listsWS.UpdateList(listName, ndProperties, ndNewFields, null, null, listVersion);

The two null values that are passed in are for updateFields and deleteFields. Again for these two fields you need to pass in CAML pretty much the same way as you did for adding fields. Check the SharePoint SDK for values you can pass in to accomplish updates and deletes.

This namespace implements the server-side interface for calling SharePoint-based XML Web services. It contains classes that implement the Windows SharePoint Services Web service and Web services for working with Web Part Pages and Web Parts. In addition, most of the methods within the defined classes are not designed to be called directly from the server but remotely from client applications. The Simple Object Access Protocol (SOAP) interfaces used in these services provide .NET developers with object models that are used to create solutions that work with both WSS and SPS.

Parameters for the CAML Method for updateListItems()

listName A string that contains the internal name of the list.

updates A Batch element that contains one or more methods for updating items and that can be assigned to a System.Xml.XmlNode object, as in the following example.

The ID attribute in each Method element uniquely identifies the specific update so that errors and return values can be properly identified. Each method that is posted contains Field elements that specify the ID of the item and the new field value for the item. The field ID does not correspond to the index of the item in the collection of items for the list.

For descriptions of the various formats used for field types that can be passed in this parameter see SPListItem.

One that could actually be useful, is to be able to actually add new list items to our list using the lists webservice. The method we call for inserting items is the same method used to ammend and delete list items. The Guid of the list is passed in as the first parameter, with the second being an XmlNode. The basics of being able to perform operations on list items is done using CAML again. Below is the code and CAML that I’m going to be running to insert a new item into a custom lists:

returnService = new VIEMossService.Lists();
//returnService.Credentials = System.Net.CredentialCache.DefaultCredentials;
string user = System.Configuration.ConfigurationSettings.AppSettings[“User”];
string password = System.Configuration.ConfigurationSettings.AppSettings[“Password”];
string domain = System.Configuration.ConfigurationSettings.AppSettings[“Domain”];
returnService.Credentials = new NetworkCredential(user, password, domain);
string serviceUrl = System.Configuration.ConfigurationSettings.AppSettings[“ServiceUrl”];

……

all the parameters above and below I added to my custom Webservice web.config file:

<appSettings>
<!–add key=….–>
</appSettings>

You can either chosse the list name or the GUID of the list. YOu find the GIUD in the URL when opening the setting of the list or use the SP Designer to access the proper aspx page.

Note:

In the aspx page you also find the list view ID. So if you wanna access a view with a field which is not included in your custom list then you receive an error. I prefer creating my own Webservice View, with all the neccessary fields.

XmlDocument xmlDoc = new XmlDocument();
/*Use the CreateElement method of the document object to create elements for the parameters that use XML.*/
string listName = System.Configuration.ConfigurationSettings.AppSettings[“ListName“];

try
{
string strBatch = “<Method ID=’1′ Cmd=’New’>” +
“<Field Name=’ID’>New</Field>” +
“<Field Name=’Attachments’>1</Field>” +
“<Field Name=’Email’>” + contact.Email + “</Field>” +
“<Field Name=’Message’>” + contact.Nachricht + “</Field>” +
//”<Field ReadOnly=’TRUE’ Name=’Timestamp’ Type=’DateTime’ DateOnly=’FALSE’ FromBaseType=’TRUE’ ></Field>” +
“</Method>”;

XmlElement element = xmlDoc.CreateElement(“Batch”);
element.SetAttribute(“OnError”, “Continue”);
element.SetAttribute(“PreCalc”, “TRUE”);
element.SetAttribute(“ListVersion”, “1”);
element.SetAttribute(“ViewName”, null);

element.InnerXml = strBatch.ToString();
//Parameter 1: Name of the MOSS List
XmlNode return_node = this.ReturnService.UpdateListItems(listName, element);
if (return_node.InnerText == “0x00000000”)
return true;
return false;

}
catch (SoapException sex)
{
throw (sex);
}

Note:

In this example I added a dummy user with contribute permissions to my custom list. If you give him less permission you receive an error when the Method wants to update or insert an item in the list.

I receive an object from a WebFormular called Contact with all the attributes. In the above CAML you see CMD=new this when you wanna create a new item.

Use a System.Xml.XmlElement object to create a Batch element in Collaborative Application Markup Language (CAML) that can contain multiple Method elements, and use the UpdateListItems method to post the methods and update items. The Cmd attribute of each Method element determines the operation that is performed on an item by specifying one of the following values:

  • Delete — Delete an item.
  • New — Create an item.
  • Update — Modify an item.

Most of the methods from the SharePoint Web services return XmlNode objects. An XmlNode object represents a node in an XML file, plus all of its children, but it isn’t a full XML document. You can use various methods to parse information from an XmlNode.

One of the most important pieces of data being returned is the GUID that uniquely identifies each list within SharePoint Services. This GUID represents the unique identity of the SharePoint list. From putting together this quick sample though I’ve found that title should be just title!  I may well update this article with a better explanation! The message box that is displayed at the end of the code should show 0x00000000 if your item has been successfully added to the list, or report the problem if it can’t.
Return Value of the Webservice

An XMLDATA fragment in the following form that shows the status of each method block posted through the updates parameter and that can be assigned to a System.Xml.XmlNode object. For items successfully updated, a row fragment is returned with the updated row values.

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
   <Result ID="1,Update">
      <ErrorCode>0x00000000</ErrorCode>
      <z:row ows_ID="4" ows_Title="Title" ows_Modified="2003-06-19 20:31:21"
         ows_Created="2003-06-18 10:15:58" ows_Author="3;#User1_Display_Name"
         ows_Editor="7;#User2_Display_Name" ows_owshiddenversion="3" ows_Attachments="-1"
         ows__ModerationStatus="0" ows_LinkTitleNoMenu="Title" ows_LinkTitle="Title"
         ows_SelectTitle="4" ows_Order="400.000000000000"
         ows_GUID="{4962F024-BBA5-4A0B-9EC1-641B731ABFED}"
         ows_DateColumn="2003-09-04 00:00:00" ows_NumberColumn="791.00000000000000"
         xmlns:z="#RowsetSchema" />
   </Result>

Other example GetListItems WS Method:

Here you have to parse the received DOM XML structure from the GetListItems(). Very importan is the Namespace, whne retreiving the nodes using XPATH.

try
{
xmlDoc.Load(new XmlNodeReader(this.getService().GetListItems(listName, viewName, null, null, null, null, null)));
XmlNode child_node = xmlDoc.FirstChild.FirstChild;

List<Video> list_Videos = new List<Video>();

foreach (XmlNode row_node in child_node)
{
Video video = new Video();
video.Childname = row_node.SelectSingleNode(“@ows_Childname”) != null ? row_node.SelectSingleNode(“@ows_Childname”).Value.Trim() : “”;
video.Description = row_node.SelectSingleNode(“@ows_Description”).Value.Trim();
video.Topic = row_node.SelectSingleNode(“@ows_Topic”).Value.Trim();

….
XmlNamespaceManager nsmgr = new XmlNamespaceManager(
xmlDoc.NameTable);
nsmgr.AddNamespace(“z”, “#RowsetSchema”);
nsmgr.AddNamespace(“rs”, “urn:schemas-microsoft-com:rowset”);
nsmgr.AddNamespace(“rootNS”, “http://schemas.microsoft.com/sharepoint/soap/&#8221;);
….
list_Videos.Add(video);
}
return list_Videos;
}
catch (Exception ex)
{
throw (ex);
}

The SharePoint Web Services

Windows SharePoint Services was being designed and developed during the time when Microsoft was beginning to heavily push Web services. It should be no surprise, then, to find out that you can get at the data in SharePoint through Web services. In fact, there’s not just one Web service involved; there are 16. Here’s a brief rundown of the Web services that a SharePoint server makes available out of the box:

* http://server:5966/_vti_adm/Admin.asmx – Administrative methods such as creating and deleting sites
* http://server/_vti_bin/Alerts.asmx – Methods for working with alerts
* http://server/_vti_bin/DspSts.asmx – Methods for retrieving schemas and data
* http://server/_vti_bin/DWS.asmx – Methods for working with Document Workspaces
* http://server/_vti_bin/Forms.asmx – Methods for working with user interface forms
* http://server/_vti_bin/Imaging.asmx – Methods for working with picture libraries
* http://server/_vti_bin/Lists.asmx – Methods for working with lists
* http://server/_vti_bin/Meetings.asmx – Methods for working with Meeting Workspaces
* http://server/_vti_bin/Permissions.asmx – Methods for working with SharePoint Services security
* http://server/_vti_bin/SiteData.asmx – Methods used by Windows SharePoint Portal Server
* http://server/_vti_bin/Sites.asmx – Contains a single method to retrieve site templates
* http://server/_vti_bin/UserGroup.asmx – Methods for working with users and groups
* http://server/_vti_bin/versions.asmx – Methods for working with file versions
* http://server/_vti_bin/Views.asmx – Methods for working with views of lists
* http://server/_vti_bin/WebPartPages.asmx – Methods for working with Web Parts
* http://server/_vti_bin/Webs.asmx – Methods for working with sites and subsites

To use any of these Web services, replace server with the name of your SharePoint server. Because they’re implemented using ASP.NET code, you can retrieve the matching WSDL file for any service by appending ?WSDL to the end of the URL. When you do so, you’ll discover that each one supports multiple methods, making this one of the richest sets of Web services of any current product. For full information on the available Web methods, download the SharePoint Products and Technologies 2003 SDK.

More Informations:

Shows all SharePoint Webservices

http://msdn.microsoft.com/en-us/library/lists.lists.updatelist.aspx

http://blogs.msdn.com/harsh/archive/2006/08/03/687759.aspx

Advertisements

One Response to “Consuming Lists.asmx Webservice from SharePoint”

  1. […] https://panvega.wordpress.com/2007/09/15/consuming-listsapsx-webservice-from-sharepoint […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: