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

Posts Tagged ‘CAML’

Attachements to a list item using SharePoint Webservices

Posted by PANVEGA on December 16, 2007

In this short post I wanna describe how to add files as an Attachment to a SharePoint list item.

In my previous post Consuming lists.aspx Webservice from SharePoint I showed you how to manage a SharePoint List Webservice. Now I´m gonna add a little bit more tricky thing to the custom cosuming WS method.

Adding an Attachment you need the Add Attchment(..) Method in the lists.asmx Webservice.

public string AddAttachment (
    string listName,
    string listItemID,
    string fileName,
    byte[] attachment


A string that contains either the title or the GUID for the list.
A string that contains the ID of the item to which attachments are added. This value does not correspond to the index of the item within the collection of list items.
A string that contains the name of the file to add as an attachment.
A byte array that contains the file to attach by using base-64 encoding.

Return Value

A string that contains the URL for the attachment, which can subsequently be used to reference the attachment.

Here is an example where I developed a custom ASP.Net Webservice which consumes the Sharepoint lists.aspx Webservice:

[WebMethod(Description = “Set the job appliaction object”)]
public string setApplication(Applicant applicant, string comment, string attache_name, byte[] content)

//here follows the CAML XMLElement method, see my previous post for detailed information


XmlNode return_node = setservice.UpdateListItems(listname, element);

if (return_node.InnerText == “0×00000000″)

if (attache_name != null && content != null)
string return_value = setservice.AddAttachment(listname, return_node.SelectSingleNode(“//@ows_ID”).Value, attache_name, content);



the setApplication(..) function receives an object with all necessary attributes for a job applicant from a ASP.Net Website formular. After adding the job application object successfully to the custom list, go ahead and check the return message. In the return_node you fin the following XML structure:

<Results xmlns="">
   <Result ID="1,Update">
      <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_DateColumn="2003-09-04 00:00:00" ows_NumberColumn="791.00000000000000"
         xmlns:z="#RowsetSchema" />

Check the response ErrorCode message. If you receive this 0x00000000 everything was without any errors.

In the next step choose the setservice.AddAttachment(listname, return_node.SelectSingleNode(“//@ows_ID”).Value, attache_name, content); Method. You need the name or GUID from your SharePointlist.

Now comes the tricky thing, in the return node you see the ows_id attribute with the ID =4. This is the new Item ID you created in the previous step. The ID is important to identify the appopriate item in the list.

Using XPATH to catch the item id from the return node. Then you only need the name and the byte code of the file. Thats all you need to add a file to a Sharepoint item.

ASP.NET Web formular example:

Read the rest of this entry »


Posted in ASP.NET, C#, MOSS, WebServices, XML, XPath | Tagged: , , , , , , , | 2 Comments »

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.


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.


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”;


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:

<!–add key=….–>

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.


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“];

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>” +

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);


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="">
   <Result ID="1,Update">
      <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_DateColumn="2003-09-04 00:00:00" ows_NumberColumn="791.00000000000000"
         xmlns:z="#RowsetSchema" />

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.

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(
nsmgr.AddNamespace(“z”, “#RowsetSchema”);
nsmgr.AddNamespace(“rs”, “urn:schemas-microsoft-com:rowset”);
nsmgr.AddNamespace(“rootNS”, “;);
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

Posted in ASP.NET, CAML, DotNet, MOSS, SOAP, WebServices, XPath | Tagged: , , , , , , | 1 Comment »

Developing Custom Field Types

Posted by PANVEGA on February 18, 2007

In this post i am going to introduce how to develope a custom field type in 6 steps with the Sharepoint People Picker. Search the name you want, push the button in order to resolve the user enitities in the code behind class. Finnaly return the parsed values to a simple multiline text box. You can also create a datagrid or just a table to format the values.

First of all we are going to create the visual user interface. As the custom field will be deployed as an feature assembly, it is a good idea to create a class library project in Visual Studio 2005 or Visual Studio 2008. Prepare also the folder structure that is required for a feature. Read the rest of this entry »

Posted in ASP.NET, Deployment, DotNet, JavaScript, UserControls, WebParts | Tagged: , , , , , , | Leave a Comment »