Wednesday, June 3, 2009

Part 1: Get all Lists using Lists.asmx webservice

There are two ways you can reference SharePoint when writing code:
• Reference and use the classes the Microsoft.Sharepoint library
• Make a web reference to the SharePoint services.

While referencing and using the classes in the Microsoft.SharePoint library is the easier coding method of the two, but it requires that you run the program on the same server where SharePoint is installed. You may have a situation where you don’t want to run the code on the same server as SharePoint.

This series will demonstrate how to access SharePoint data “behind the scenes” without having to run the program on the SharePoint server. In Part 1 of this series, I will demonstrate how to access the SharePoint service using a web reference as well as how to access all the lists of a particular site. In Part 2 of this series, I will demonstrate how to get all items in a particular list.

Step 1: First you need to create a Visual Studio Project. You can create a Webpart or Web Control or Console Application as per your requirement.

Step 2: Add the following code at the begenning:
using System.Xml;
using System.Data;
using System.Net;
using Microsoft.SharePoint; /* Optional */

Step 3: Add a Web reference with the following URL:
http://[your site url]/_vti_bin/Lists.asmx and name it as "WS" (or anything else, you just need to update that accordingly in the code block shown below).

Step 4: Add the following code:

private static void GetAllList()
{
WS.Lists listService = new WS.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

XmlNode ndLists = listService.GetListCollection();

/* Here we have used DataSet and Datatable, but you can also parse the returned XML directly */
XmlReader reader = new XmlNodeReader(ndLists);
DataSet ds = new DataSet();
ds.ReadXml(reader);

foreach (DataRow dr in ds.Tables[0].Rows)
{
/* You can replace Console.WriteLine accordingly if you are not using Console Application */
Console.WriteLine(dr["Title"].ToString()); /* dr["Name"].ToString() will return the GUID*/
}
}

The code above will return all the lists and document libraries including galaries like masterpage, webparts, etc. If you need anything specific, you can filter that using other fields available. You can find out the other fields using the following code:

foreach (DataColumn dc in ds.Tables[0].Columns)
{
Console.WriteLine(dc.ColumnName);
}

0 comments: