Chapter 3: Programming SharePoint Lists and Libraries

This article is an excerpt from SharePoint 2007 and Office Development Expert Solutions by Randy Holloway, Andrej Kyselica, and Steve Caravajal from Wrox Press (ISBN 978-0-470-09740-3, copyright 2008 Wiley Publishing, all rights reserved). No part of these chapters may be reproduced, stored in a retrieval system, or transmitted in any form or by any means—electronic, electrostatic, mechanical, photocopying, recording, or otherwise—without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

Download the sample code that accompanies the book

Microsoft SharePoint Products and Technologies are designed for users, applications, and systems to create, store, and track data related to various teams, projects, and other business processes or activities. Similarly, there are libraries in Windows SharePoint Services that are a specialized type of list that enable users or applications to manage files. These are the foundational features of a SharePoint site.

The core functionality in Windows SharePoint Services 3.0 and Microsoft Office SharePoint Server are based on these list and library functions and most out-of-the-box user features are based on or rely upon the use of lists and libraries. As you might expect, the programmability of lists and libraries in Windows SharePoint Services is a key part of the functionality that developers need to learn in order to build applications that integrate effectively with SharePoint Products and Technologies.

This chapter covers the programmability features of lists and libraries within Windows SharePoint Services so that as a developer you better understand these features and what is supported for programmatic interaction with SharePoint data. In addition, we'll review some practical examples regarding how to build end-to-end solutions based on list and library data in Windows SharePoint Services.

To understand SharePoint lists and libraries from a developer's perspective, we'll dive into the following topics:

  • Understanding SharePoint lists and libraries

  • Programming SharePoint lists

  • Programming SharePoint libraries

  • Examining web services for list and libraries

  • Using list events

  • Using RSS for list data retrieval

At the end of this chapter, developers should have a good understanding of both how lists and libraries work in Windows SharePoint Services and what developer feature areas and technology components related to lists and libraries can be leveraged in your applications. This chapter also serves as a technical foundation for later examples related to UI development in Windows SharePoint Services, including the creation of new Web Parts and methods to customize list rendering in various SharePoint sites.

Contents

  • Understanding Lists and Libraries

  • Programming SharePoint Lists

  • Programming SharePoint Document Libraries

  • Web Services for Lists and Libraries

  • Using RSS for List Data Retrieval

  • Using List Events

  • Summary

Understanding Lists and Libraries

Lists are a key part of the architecture of Windows SharePoint Services. For a developer, a list is the main mechanism through which data stored in Windows SharePoint Services is presented to a user for data input or retrieval. This means that in many cases customizing a SharePoint site requires some customization to the list data or programmatic access to the data from an application that resides outside of Windows SharePoint Services.

Before getting started with coding against the SharePoint lists and libraries, it's important to understand a little bit more about how lists work, how they're created within the Windows SharePoint Services web interface, and what properties they have that can impact how you write code for a list. To do this, we'll walk through an example involving the creation of a list.

Creating a SharePoint List

As a developer, you'll often need to write code against existing SharePoint lists to extend sites or add new functions to those sites already in place. You create a new list using the Add method of the SPListCollection class, and specify the type of list using the SPListTemplateType enumeration. As a developer using SharePoint lists, you will focus most of your effort on adding, updating, and deleting list items to synchronize your SharePoint content with another data store or to serve as a primary store for application data. Most lists that are used in Windows SharePoint Services either will be default lists or will be deployed as part of a Feature for a site that is configured in advance, as opposed to creating lists on-the-fly for your specific application. For those reasons, this chapter focuses primarily on the manipulation of data for existing lists. A little later in the chapter, we'll revisit creating new lists through the APIs.

To better understand lists and how they're used in Windows SharePoint Services we'll create a sample list using the SharePoint UI that includes part numbers. Once that list is created, we'll focus on the features and functions of that list as defined by the Windows SharePoint Services web interface, and then we'll look at using the SharePoint object model and the web services that can be used to access the list.

Here are the steps to follow to create the parts list:

  1. On a sample server running Windows SharePoint Services, use an existing site or create a new site (for example, standard Team site) on which to add the list. For the example in the book, we have created a new team site named "Parts List Sample."

  2. Using the Site Actions menu, select the Create option to create a new list, library, or web page on the SharePoint site.

  3. As shown in Figure 3-1, select the Custom List option to create a new custom list that doesn't correspond to the existing SharePoint list templates.

    Figure 3-1

  4. Specify the name and description for the new list. For this sample, the name of the list will be "Parts List."

  5. Once the list is created, select Settings to add columns, create new views, or change other list settings.

    To create a new column, select the List Settings item. On the next page, look for the Columns section and select the Create Column link. Once you're at the Create Column page, you can select the type of data the column supports, along with other parameters for configuring this data element. An example showing the creation of the Price column definition is shown in Figure 3-2.

    Figure 3-2

  6. The sample parts list uses the Title field for the part name and includes the additional columns Part Number and Price. The Part Number field is restricted to a number type and the Price field reflects currency. For the example, configure the Price field with a constraint not to exceed $10.00 and set the field to be required as shown in Figure 3-3.

    Figure 3-3

  7. Enter some sample parts, as shown in the completed list in Figure 3-4.

    Figure 3-4

With the completion of these steps you now have a custom list. You can either save this list as a template or you can use content types in Windows SharePoint Services to define lists for your sites. Content types are used to help the users of SharePoint sites better organize their data and essentially capture the requirements for the types of data to be entered. Basically, a content type acts as a form of schema. While a list template enables you to export the definition of a list, a content type enables you to define the elements that are included in a list. There are custom content types and standard content types. In the case of this parts list, we'll add additional content types to the list to demonstrate how this works.

  1. From the Parts List, select Settings and the List Settings option. On the Customize Parts List page, select Advanced Settings.

  2. On the List Advanced Settings: Parts List page, select the Yes radio option for "Allow management of content types?" This will return you to the Customize Parts List page.

  3. The current list definition will be defined under Content Types as Item. This denotes the standard list item that is created when a new item is added to this list. To add a new content type, select the Add from Existing Content Types link in the Content Types section.

  4. On the Add Content Types: Parts List page, choose to select content types from List Content Types in the drop-down list and add the Announcement content type, as shown in Figure 3-5.

    Figure 3-5

  5. Once the Announcement content type is added, you can return to the main parts list and select the option to add a new item to the list. An example of an Announcement content type added to the list in addition to the other list items supporting the Item content type is shown in Figure 3-6.

    Figure 3-6

In this case, the list now supports the custom defined items for the parts list along with the standard Announcements content type. This provides you with the flexibility to maintain a single list with multiple types of list items supported. Content types are designed to support settings for the following types of information:

  • Metadata or properties that you want to assign to the list or document library

  • Custom forms for use within the Windows SharePoint Services interface for the content

  • Workflows available for this type of content, including support to define automated workflow based on event, content, or other conditions

  • For specific document content types, the template associated with this type of document

  • Custom data for applications that can be stored as XML as part of the content type

Content types can be created in several ways. A user can create and deploy a content type through the Windows SharePoint Services user interface. Content types can also be created through the SharePoint object model, or they can be created and deployed as Features in an XML definition file format.

For the purposes of this chapter, we're going to proceed with writing code against our manually created lists. In Chapter 5, we'll dig a little deeper into content types to understand how they fit into a Windows SharePoint Services infrastructure with defined custom templates for sites, custom lists, and custom Web Parts. We'll also look into Features to understand how they can be used to deploy content types, Web Parts, and site templates throughout your Windows SharePoint Services infrastructure.

Now that you have a sample list to work with, we can look into the object model for dealing with lists in Windows SharePoint Services and create some custom applications to modify those lists.

Programming SharePoint Lists

With a new custom list in place for the SharePoint site, you can now dig into the object model and think about what you'd like to do in code with that list. Before getting started, you need to understand a bit more about the features of lists in Windows SharePoint Services 3.0.

As shown in the earlier sample list example, you can create lists to support specific data types with field constraints to ensure data integrity for new data entered into the list. Similar functionality for lists has existed in previous versions of Windows SharePoint Services, including support for out-of-the-box lists and the capability to create custom lists. Windows SharePoint Services 3.0 offers several new list features, including the following:

  • Cross-list queries

  • List indexing

  • Folders in lists

  • List item versions

  • Item-level security

Some of these features speak to performance in Windows SharePoint Services 3.0. For example, the SPSiteDataQuery class enables you to use a SQL-like syntax to query lists across multiple SharePoint sites in a very efficient manner. In addition, list indexing enables you to index specific list columns, making the data store more scalable for querying by third-party applications. Item-level security is a great feature that has long been wished for in Windows SharePoint Services, enabling a site administrator to now provision access to a library or list to a group of individuals but to still maintain security of each item in the list. Moreover, with the security trimming features supported within Windows SharePoint Services, now sites can be configured to allow users to see only content to which they have permissions.

In this chapter we'll take a closer look at folders in lists and the versioning features for lists that enable some new scenarios not previously supported in Windows SharePoint Services 2.0 from a programmer's perspective. In the next section, we'll walk through the basics for creating a program to programmatically access a SharePoint list.

Adding a List Item

To get started with using the SharePoint object model, we use the example of adding an item to a list. To do this, we can create a simple Windows forms application on a test server. We can use the list that we created to track parts as the list to program against in this example.

This example creates a base Windows application with a single form and a tab control. This enables us to maintain one project with a single form and compiled binary to support different list access scenarios. As you follow the examples in the next few sections, note that the screenshots reflect the use of this tab control and tabs that are in place for upcoming samples in the chapter. As you follow along and write your own samples, feel free to ignore the tab control or to use it as part of your solution. The code shown in this chapter is also available as a download at www.wrox.com.

Here are the steps to get started with programmatically adding an item to a list:

  1. Create a Windows application in Microsoft Visual Studio. For the samples in this book, we used Microsoft Visual Studio 2005 Professional Edition.

  2. Add a reference to Microsoft.SharePoint to enable access to this namespace.

  3. Add controls to accept text input for the fields and a button to initiate uploading of the data to the list.

  4. For the button click member function associated with the form, we'll add code to connect to the SharePoint site, retrieve a collection of the list items associated with the parts list, and then update that item in the list. This includes the following steps:

    1. Return a site collection using the SPSite constructor providing the site URL.

    2. Return the target web site based on the SPWeb class based on the site name.

    3. Return a collection of list items (SPListItemCollection) based on the Items property for the specific named list.

    4. Add a list item to the list items collection using the following syntax: SPListItem item = listItems.Add().

    5. Populate the item data using the input values from the form.

    6. Call the Update method of the SPListItem class to update the Windows SharePoint Services content database.

  5. Check the Parts List to see the updated list item.

The sample application to drive the list automation is shown in Figure 3-7. The results of the list update and the Visual Studio project code are shown in Figures 3-8 and 3-9, respectively.

Figure 3-7

Figure 3-8

Figure 3-9

//String parameters to enable site and list access
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";
const string listName = "Parts List";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonAddItem.Enabled = false;

//Return a site collection using the SPSite constructor providing the site URL
SPSite siteCollection = new SPSite(siteUrl);

//Return the target web site based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Return a collection of list items based on the Items property
//for the specific named list
SPListItemCollection listItems = site.Lists[listName].Items;

//Add a list item to the list items collection
SPListItem item = listItems.Add();

//Populate item data via user indexers with form input data
item["Title"] = textBoxPartName.Text;
item["Part Number"] = Convert.ToInt16(textBoxPartNumber.Text);
item["Price"] = Convert.ToInt16(textBoxPrice.Text);

//Update SP database with changes made to this item
item.Update();

//UI clean-up
labelResult.Text = "Done!";
Cursor = Cursors.Default;
buttonAddItem.Enabled = true;

In this sample, we've used a Windows application that runs on the Windows SharePoint Services server to test these functions via the object model. This same functionality can be leveraged from within ASP.NET code running on the server or from a client application that references Windows SharePoint Services binaries on another machine. However, for applications that are not resident on the server, you can look to web services for updating the list data or to other mechanisms such as RSS feeds for data retrieval. (Note that error-handling code has not been added to this function.)

Now that we've accomplished the addition of a list item into an existing SharePoint list, let's take a look at how you can update and delete list items and examine the structure of the list data within exposed by the object model.

Deleting and Updating List Items

Now that you've added an item to a SharePoint list programmatically, it is also important that you understand what is involved in updating and deleting list items. This, along with adding folders and moving data within lists, provides you with much of the functionality that you need to control list functions through external programs or custom extensions to SharePoint web applications, and to synchronize SharePoint list data with third-party data sources.

Similar to the list item add feature in the earlier example in this chapter, we'll use a Windows application to drive the updates and deletes. Remember that in the sample application for this chapter we have used a series of tabs from the standard Visual Studio tab control to demonstrate different functions on the main application form.

Here are the steps to perform a list update from your custom application:

  1. Add the UI elements to the new form tab for deleting a list item. Include a text box for the part number and a button to initiate a delete based on an item match with that part number.

  2. Upon clicking the form button, enter the code to delete an item using the following steps:

    1. Use the SPSite class constructor with the URL for the main site to return a site collection.

    2. Return the target web site based on site name.

    3. Return a collection of list items based on the Items property for the specific named list (for example, "Parts List").

    4. Assign the value of the Count property of the list items collection to counter variable.

    5. Loop through the list items collection and compare the part number entered on the form to the part number associated with the item from the list. Upon a match, delete that item from the list.

  3. Clean up the form and check the corresponding list for a delete.

The form for the delete scenario is shown in Figure 3-10. The corresponding code follows.

Figure 3-10

//String parameters to enable site and list access
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";
const string listName = "Parts List";

//"Freeze" UI
Cursor = Cursors.WaitCursor;
buttonDeleteItem.Enabled = false;

//Use SPSite constructor with URL for main site to return a site collection
SPSite siteCollection = new SPSite(siteUrl);

//Return the target web site based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Return a collection of list items based on the Items property
//for the specific named list
SPListItemCollection listItems = site.Lists[listName].Items;

//Assign the value of the Count property of the list items collection to counter variable
int itemCount = listItems.Count;

//Loop through list items collection and compare the part number entered on form
//to the part number associated with the item from the list. Upon
match, delete.
for (int i = 0; i < itemCount; i++)
{
    SPListItem item = listItems[i];

    if (textBoxPartNumber1.Text == item["Part Number"].ToString())
    {

        //Delete list item and decrement counter variable
        listItems.Delete(i);
        itemCount -- ;
    }
}

//UI clean-up
labelResult1.Text = "Done!";
Cursor = Cursors.Default;
buttonDeleteItem.Enabled = true;

The code for updating an item within a SharePoint list is similar. Here are the steps to update a list item from your application:

  1. Add UI elements for part number matching for the item, a price field for new price input, and a button to initiate the update.

  2. For the form button click function, implement the following steps in your code:

    1. Use the SPSite class constructor with the URL for the main site to return a site collection.

    2. Return the target web site based on site name.

    3. Return a collection of list items based on the Items property for the specific named list (for example, "Parts List").

    4. Assign the value of the Count property of the list items collection to counter variable.

    5. Loop through the list items collection and compare the part number entered on the form to the part number associated with the item from the list. Upon a match, update the price input data for the matching item.

  3. Clean up the form and check the corresponding SharePoint list for the updated data.

The Windows form application for the list update is shown in Figure 3-11, and the corresponding code follows.

Figure 3-11

//String parameters to assign site and list
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";
const string listName = "Parts List";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonUpdateItem.Enabled = false;

//Use SPSite constructor with URL for SP site to access site collection
SPSite siteCollection = new SPSite(siteUrl);

//Return the target web site based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Return collection of list items based on Items property for the specified list
SPListItemCollection listItems = site.Lists[listName].Items;
int itemCount = listItems.Count;

//Loop through list items collection and compare the part number entered on form
//to the part number associated with the item from the list. Upon match, update price.
for (int i = 0; i < itemCount; i++)
{
    SPListItem item = listItems[i];

    if (textBoxPartNumber2.Text == item["Part Number"].ToString())
    {
    //Update price for part number match
        item["Price"] = Convert.ToInt16(textBoxPrice2.Text);
        item.Update();
    }
}

//UI clean-up
labelResult2.Text = "Done!";
Cursor = Cursors.Default;
buttonUpdateItem.Enabled = true;

At this point, we have examined the code and supporting object model to deal with SharePoint lists. We have added data to a list, updated list data, and deleted items from a list.

Another type of list data that is supported in Windows SharePoint Services is a document library. A document library is another form of a list, and while it has many similar properties to a standard list, it also includes additional functions to enable document uploads, retrieval, and other functions to support document management and collaboration. In the next section, we'll look at document libraries and some of the corresponding functionality for developers.

Programming SharePoint Document Libraries

This chapter had an earlier section focused on programming lists in Windows SharePoint Services, and as we just indicated, the document library itself is just another form of a list. There is a default content type associated each type of list available in Windows SharePoint Services, and as a document library is just a form of list, it comes with an associated content type to define the properties of list items in the document library.

Focusing on document libraries separately from lists make sense for a couple of reasons:

  • The way that users and programs will access Windows SharePoint Services to deal with list data versus document data (or document libraries) is different.

  • The document libraries expose features and events that are different from the standard list templates, so they are worth considering as separate functions within the architecture of Windows SharePoint Services.

Uploading a Document to a Library

To upload a document to a library, you need to build a test application that can take the location of a file for upload and use the APIs to add that file to the existing site. For this example, the code to upload the file is designed to run on a file system accessible to the local server that is running Windows SharePoint Services. Remember that this sample code is available for download at www.wrox.com. Other mechanisms to upload remote files or to copy files from another SharePoint URL are also available.

Take a look at the steps to upload a document to an existing library in code:

  1. Create a Windows application with a text box to input the file URL and a button to initiate the upload to the server. The sample form is shown in Figure 3-12.

    Figure 3-12

  2. For the example, create a sample document to upload on the file system. You'll then need to remember the location and name of this file later when running the sample application.

  3. For the button click, add code for the following implementation:

    1. Use the SPSite constructor to create a site collection based on the URL.

    2. Assign a target web site to an instance of SPWeb based on the target site name (for example "/SiteDirectory/Parts List/").

    3. Create an instance of FileStream based on the file location entered in the form's text box.

    4. Create a byte array to correspond to the FileStream instance and write the contents of the file stream into the array.

  4. Add the file to the document library using the SPFileCollectionAdd method.

  5. Check the Parts List document library to ensure file upload.

The code for this sample routine is included in the listing that follows:

//String parameters to assign site and document library destination URL
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";
const string destination = "http://moss2007rtm1/SiteDirectory/PartsList/Shared%20Documents/TestUpload.doc";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonNewFolder.Enabled = false;
buttonUploadDocument.Enabled = false;

//Use SPSite class constructor to create site collection based on URL
SPSite siteCollection = new SPSite(siteUrl);

//Assign target web site based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Assign file stream to file opened based on file location form input
FileStream fStream = File.OpenRead(textBoxFilePath.Text);

//Instantiate byte array to correspond to the file stream object
byte[] contents = new byte[fStream.Length];

//Read data from file stream and write into byte array
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

//Add file to document library based on destination URL and content of byte array
site.Files.Add(destination, contents);

//UI clean-up
Cursor = Cursors.Default;
buttonNewFolder.Enabled = true;
buttonUploadDocument.Enabled = true;

The SPFileCollectionAdd method is overloaded to take various forms of file input (either Stream or Byte arrays) along with metadata for the file and other settings. The date and time for the upload can be specified, and a flag can be set to determine whether or not the file upload can overwrite a file of the same name.

Creating a Document Library Folder

One of the important features of a document library is the folder feature. This enables a user or program to create and organize folders for storing documents. Because list security can be controlled at the item level, a folder can provide a clean way of separating content from a security perspective. In addition, a folder can enable an existing site with a large number of documents to have a simple view of a subset of the documents that corresponds to a static URL based on folder location.

Follow these steps to extend the sample code for creating a folder within a document library:

  1. Create the UI elements on a Windows form to take the folder name to create in the document library and a button to initiate the folder creation.

  2. On the button click, implement the following steps in code:

    1. Use the SPSite constructor to assign a site collection based on the top-level URL for Windows SharePoint Services.

    2. Assign an instance of SPWeb based on the target site name (for example, "/SiteDirectory/PartsList/").

    3. Create an instance of SPDocumentLibrary based on the named instance of the document library (for example, "Shared Documents").

    4. Create an instance of SPFolderCollection based on the folders for this site.

    5. Use the Add method for the folders collection to add the named folder. Concatenate the input folder name value along with the relative path to create the named folder at the document library location.

    6. Call the Update method of the instance of SPDocumentLibrary to update the library with the added folder.

  3. Check the Shared Documents site for the added folder. See Figure 3-13 for an example.

    Figure 3-13

//String parameters for site URL and site name
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonNewFolder.Enabled = false;
buttonUploadDocument.Enabled = false;

//Use SPSite constructor to assign site collection based on top-level URL
SPSite siteCollection = new SPSite(siteUrl);

//Assign target site (SPWeb instance) based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Create an instance of SPDocumentLibrary based on the named doc library list
SPDocumentLibrary docLibrary = (SPDocumentLibrary)site.Lists["Shared Documents"];

//Create instance of SPFolderCollection and add a named folder based on forms input,
//then update library to reflect added folder
SPFolderCollection myFolders = site.Folders;
myFolders.Add("http://moss2007rtm1/SiteDirectory/PartsList/Shared%20Documents/" + textBoxFolderName.Text + "/");
docLibrary.Update();

//UI clean-up
Cursor = Cursors.Default;
buttonNewFolder.Enabled = true;
buttonUploadDocument.Enabled = true;

Based on this code you can then upload documents to the documents library based on folder locations, or move existing content into the library and folder structure. The SPDocumentLibrary class also enables you to set administrative options on this library, including allowing moderation for posted documents, enabling or disabling crawling for Search, and many other options.

One limitation of the code samples shown so far for managing lists and libraries is that the code is designed to run locally to the server. In some cases, this solution will work quite well. In others, it is extremely limiting and not useful for clients that are remote to the infrastructure of Windows SharePoint Services. In the next section, we'll examine the web services support within Windows SharePoint Services for accessing and managing lists and libraries. We'll also walk through an example related to accessing list data via web services.

Web Services for Lists and Libraries

While the SharePoint object model provides a rich set of functionality for accessing lists and document library data from within Windows SharePoint Services, it is often not feasible to use this object model. The object model works very well for SharePoint site extensions and custom ASP.NET applications deployed within the infrastructure of Windows SharePoint Services, but it is not a great solution for third-party systems and client applications that need to abstract the features of Windows SharePoint Services from the end user while creating or updating lists or document data within the infrastructure of Windows SharePoint Services.

Windows SharePoint Services exposes a variety of web services supporting functions for list access and many other application and administrative functionality. This section briefly reviews all of the SharePoint web services provided in the platform and then walks through some specific examples related to SharePoint lists.

Windows SharePoint Services Web Services

A number of web services are supported within Windows SharePoint Services for basic system functions. In addition, Microsoft Office SharePoint Server exposes other web services for specific applications, including Excel Services and Search. The following table lists the core Windows SharePoint Services web services:

Web Service

Web Reference URL

Administration

http://MyServer:Port_Number/_vti_adm/Admin.asmx

Alerts

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/alerts.asmx

Copy

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/copy.asmx

Document Workspace

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/dws.asmx

Forms

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/forms.asmx

Imaging

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/imaging.asmx

List Data Retrieval

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/dspsts.asmx

Lists

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/lists.asmx

Meetings

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/meetings.asmx

People

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/people.asmx

Permissions

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/permissions.asmx

Search

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/search.asmx

Site Data

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/sitedata.asmx

Sites

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/sites.asmx

Users and Groups

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/usergroup.asmx

Versions

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/versions.asmx

Views

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/views.asmx

Web Part Pages

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/webpartpages.asmx

Webs

http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/webs.asmx

Given the large number of web services endpoints exposed by Windows SharePoint Services, it is important to understand what function each of these performs. The following list summarizes the functions of various Windows SharePoint Services web services:

  • Administration: This service provides methods for managing a deployment of Windows SharePoint Services, including creating or deleting sites.

  • Alerts: This service enables you to work with alerts for list items in a SharePoint site.

  • Copy: This service supports copying files from or within a given SharePoint site.

  • Document Workspace: This service exposes methods for managing Document Workspace sites and data.

  • Forms: The Forms service methods return forms used in the Windows SharePoint Services UI when working with list contents.

  • Imaging: This service supports methods for creating and managing picture libraries in Windows SharePoint Services.

  • List Data Retrieval: This service enables you to perform queries against SharePoint lists.

  • List: Use the methods of this service to work with lists and list data, including retrieving all list items in a collection.

  • Meetings: This supports methods to create and manage Meeting Workspace sites.

  • People: This service supports managing information about people.

  • Permissions: Use this service for support when working with permissions for a site or list.

  • Search: This service supports search queries. It was introduced earlier in Chapter 2.

  • Site Data: This service provides methods that return list data and metadata from sites or lists in Windows SharePoint Services.

  • Sites: This service supports returning information about site templates for a given site collection.

  • Users and Groups: This service enables you to work with users, site groups, and cross-site groups.

  • Versions: This service provides methods for working with file versions.

  • Views: This service supports methods for working with views of lists.

  • Web Part Pages: This service provides methods to send and retrieve information from web services.

  • Webs: This service enables you to work with sites and subsites.

Out of this laundry list of services, we'll look specifically at Lists and List Data Retrieval services.

Retrieving List Data via Web Services

To look at how you can leverage web services to work with list data, we'll take a look at an example for retrieving list schema definitions through the Lists web service. In order to retrieve Windows SharePoint Services data using the web services, you must first create a web reference either statically or dynamically within your code to access the service. To perform a list function using web services in this example, follow these steps:

  1. Create a Windows form with a button to call the web services, and a text box to provide the web services output.

  2. Create a web reference for the Lists service in Windows SharePoint Services. Right-click Web References in the Solution Explorer within Visual Studio and follow the prompts. When prompted for a web service reference URL, enter the URL in this format: http://MyServer/[sites/][MySite/][MySubsite/]_vti_bin/lists.asmx. The result should be similar to that shown in Figure 3-14.

    Figure 3-14

  3. Implement the following for the form's button click function:

    1. Create an instance of the Lists web service based on the previously created web reference.

    2. Establish credentials for the web service to use. For the sample, you can use the default credentials for the security context of this application.

    3. Call the GetList method of the web service to return list items based on a named list.

    4. Write the output of the GetList method to the form's text box.

The output from the GetList method of the web service is shown in Figure 3-15. In this case, we have retrieved the list schema for the Tasks list associated with the site's web service. The code is as follows:

Figure 3-15

//String for list name
const string listName = "Tasks";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonRetrieveList.Enabled = false;

//Instance of Lists Web service for Parts List site
moss2007rtm1.Lists listWebService = new moss2007rtm1.Lists();

//Set credentials since Web service doesn't allow anonymous access
listWebService.Credentials = System.Net.CredentialCache.DefaultCredentials;

//Call GetList method of Web service to return list items
System.Xml.XmlNode listItems = listWebService.GetList(listName);

//Write output of GetList method to form
textBoxResults.Text = listItems.OuterXml;

//UI clean-up
Cursor = Cursors.Default;
buttonRetrieveList.Enabled = true;

In this last example, you can see how to retrieve the schema of the Tasks list. This kind of list operation is useful for retrieving schema definitions for a list to render an alternative user interface for list input in an external application. This kind of integration could help you to render a SharePoint list-based application in a PHP web site. A real-world example might include synchronizing SharePoint list data with an open-source issue tracking tool.

Creating a New List via Web Services

At the beginning of this chapter, we started by looking into how lists work and what is involved with creating a new list through the Windows SharePoint Services user interface. Now we'll walk through the use of the Lists web service to create a new list programmatically. To do so, we'll follow these steps:

  1. Create a Windows form with a button to call the web service, and a text box to capture the name and description for a new list.

  2. As in the previous example, create a web reference to the Lists web service in your project.

  3. Implement the following for the form's button click function:

    1. Create an instance of the Lists web service based on the previously created web reference.

    2. Establish credentials for the web service to use. For the sample, you can use the default credentials for the security context of this application.

    3. Call the AddList method of the web service to create a new list. In this sample, we'll create a new Contacts list based on the list template for Contacts.

The code for this list creation example using web services is as follows:

//Constant for list template ID for contacts list
const int templateID = 105;

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonCreateContactList.Enabled = false;

//Instance of Lists Web service for Parts List site
moss2007rtm1.Lists listWebService = new moss2007rtm1.Lists();

//Set credentials since Web service doesn't allow anonymous access
listWebService.Credentials = System.Net.CredentialCache.DefaultCredentials;

//Call AddList method of Web service to create new list
XmlNode result = listWebService.AddList(textBoxListName.Text, textBoxListDescription.Text, templateID);
labelResult3.Text = "Done!";

//UI clean-up
Cursor = Cursors.Default;
buttonCreateContactList.Enabled = true;

With this code for creating a new list, you can use Windows SharePoint Services as a repository for creating new lists automatically based on a trigger from another business process or based on a rule invoked from an external application. As in the previous example, the use of an external issue tracking or project management tool outside of Windows SharePoint Services could present the need for integration or synchronization of a list of project issues or tasks.

Because the web services within Windows SharePoint Services can be targeted at the site level and are fairly granular, you need to investigate the various methods supported by different services to determine the best strategy for creating web references for your applications. In general, you'll look to web services as the preferred integration technique for heterogeneous scenarios and distributed applications that need to support integration across network boundaries. In the next section, we'll look at the use of a more data-centric integration technique that's new within Windows SharePoint Services 3.0.

Using RSS for List Data Retrieval

While a number of different methods have been reviewed in this chapter for retrieving list data, one of the more intriguing new features in Windows SharePoint Services is the capability to generate RSS data for any list. RSS stands for Really Simple Syndication (formerly Rich Site Summary) and is an XML data format designed to enable you to syndicate content and retrieve updates for lists of content and various types of articles and data sources. While generally thought of as a data format to be used to read blogs, RSS can be applied in a number of different application development scenarios and is a good, lightweight protocol for data publishing and syndication.

The sample list that we created earlier in the chapter can be turned into an RSS feed through a single click in the browser, as shown in Figure 3-16. The RSS feed output is shown in Figure 3-17.

Figure 3-16

Figure 3-17

Windows SharePoint Services enables administrators to determine whether or not to publish RSS data for lists, but RSS will be published by default. For applications that simply need to retrieve list data and reformat it or perform some logic against it, RSS is a good alternative.

To better understand how you can use RSS data in applications, the following example walks through a sample to retrieve RSS data. To implement code to grab RSS data, do the following:

  1. Create a Windows form application with a button to retrieve the RSS data feed and a text box to contain the RSS output.

  2. On button click, implement the following logic (shown in the code listing that follows shortly):

    1. Use the SPSite constructor to retrieve the site collection for a specified URL.

    2. Create an instance of the specific site (for example, "PartsList") based on the site name.

    3. Create an instance of the list to retrieve as RSS based on list name.

    4. Create an instance of XmlDocument and a new stream object.

    5. Call the WriteRssFeed method of the list to populate the stream object.

    6. Load the stream data into the instance of XmlDocument.

    7. Use the OuterXml property of XmlDocument to load text into the form's text box.

  3. View form output to verify results.

//String parameters to access site and list data
const string siteUrl = "http://moss2007rtm1/";
const string siteName = "/SiteDirectory/PartsList/";
const string listName = "Parts List";

//Freeze UI
Cursor = Cursors.WaitCursor;
buttonGetRSS.Enabled = false;

//Use SPSite constructor to get site collection
SPSite siteCollection = new SPSite(siteUrl);

//Create instance of site (SPWeb) based on site name
SPWeb site = siteCollection.AllWebs[siteName];

//Create instance of list based on list name
SPList listRSS = site.Lists[listName];

//Create instance of XmlDocument
XmlDocument xmlOutput = new XmlDocument();

//Create new stream
Stream rssStream = new MemoryStream();

//Call WriteRssFeed method of list to populate stream
listRSS.WriteRssFeed(rssStream);
rssStream.Seek(0, SeekOrigin.Begin);

//Load stream data into Xml document instance
xmlOutput.Load(rssStream);

//Use form's text box to render xml document data
textBoxResults2.Text = xmlOutput.OuterXml;

//Clean-up UI
Cursor = Cursors.Default;
buttonGetRSS.Enabled = true;

The RSS output is shown in Figure 3-18.

Figure 3-18

RSS data from Windows SharePoint Services can be consumed through custom applications, rendered through the web browser, or synchronized with the Windows RSS platform components. Because the data is just an XML format, it can be parsed as required or simply transformed and rendered to fit the needs of your particular tool.

For scenarios in which the client application is remote to the server running Windows SharePoint Services, both the web services options and RSS feeds can be useful tools.

  • In the case of web services, the developer has a comparable set of functions to the various classes under the Microsoft.SharePoint namespace and can perform a considerable number of functions within Windows SharePoint Services from both a site administrative and data management perspective.

  • With RSS data, the main advantage for developers is the capability to access list data using a very lightweight protocol that can be easily parsed or rendered as the consuming application requires. In addition, developers can leverage out-of-the-box features in Internet Explorer 7.0, the Windows RSS platform, and applications such as those in the 2007 Microsoft Office system in order to leverage the RSS format. Moreover, there are a significant number of third-party RSS aggregator applications and APIs for integration with various web content management and document publishing tools.

Using List Events

In Windows SharePoint Services 2.0, support for events was limited to document libraries and form libraries. Those events were tied to completed actions, and in some cases were too limiting to support the kinds of behaviors developers would like to implement. Just as databases support triggers for inserts, updates, and deleted data, SharePoint data needed to provide similar events for developers to access when SharePoint list data was updated. In the current SharePoint Products and Technologies, a richer infrastructure for events is supported, enabling developers to build in data validation and business logic to support events associated with lists and sites.

As a developer, you can override methods of the SPItemEventReceiver class to handle specific events. Windows SharePoint Services supports events that fire synchronously during actions such as updates and deletes, and events that occur after actions occur. Here are some of the methods of SPItemEventReceiver that you can override to handle specific events:

  • ItemAdding

  • ItemAdded

  • ItemUpdating

  • ItemUpdated

  • ItemDeleting

  • ItemDeleted

  • ItemCheckingIn

  • ItemCheckedIn

  • ItemCheckingOut

  • ItemCheckedOut

Other methods supporting undoing checkouts, renaming files, and adding or deleting attachments are also supported. Note that the method names denote whether or not the method is executed during an action or after an action. For example, ItemAdding is accessible during the addition of an item to a list, and ItemAdded fires after the item is added to the list. With these methods you have access to the data associated with SPListItem through an object that is provided as an input parameter when the method is called. This object is of type SPItemEventProperties and much like a database trigger, exposes the data associated with the list and the affected list item.

To build an event handler for a list, do the following:

  1. Create a new Visual Studio project for a class library. In this example, we'll name this project (and ultimately the namespace and class), ListEventHandler.

  2. Add a reference to Microsoft.SharePoint to access the SharePoint namespace.

  3. Add the Microsoft.SharePoint directive.

  4. Change the name of the class to ListEventHandler and inherit from SPItemEventReceiver.

  5. Override the ItemAdding method to trap the event that fires while an item is being added to the list but prior to the addition action being completed.

  6. Use the Cancel property of SPItemEventProperties to cancel the event and list item action. This will prevent an item from being added to the list.

The code for this example is shown in the following listing:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace ListEventHandler
{
    //Class inherits from SPItemEventReceiver
    public class ListEventHandler : SPItemEventReceiver
    {
        //Override ItemAdding method, which will wire up the event that fires when adding an item to the list
        public override void ItemAdding(SPItemEventProperties properties)
        {
            //Access SPListItem data exposed through SPItemEventProperties
            //Cancel the list item action
            properties.Cancel = true
            //Write back an error for adding this item to the list- append the list name,
            //list item name and URL
            properties.ErrorMessage = "Adding data disabled for this list: "
                + properties.ListTitle + "; " + properties.ListItem.DisplayName + "; "
                + properties.WebUrl;
        }
    }
}

In this example, we're handling an event that occurs when an item is added to the list, and canceling the event and the list item action. While you could use security features to prevent users from adding items to lists, this event-based technique can be used to drive the user of the site to another behavior, such as going to a different area of the site to add the content. The event handler can also invoke some logic external to Windows SharePoint Services, such as kicking off a workflow that is resident on another platform or synchronously looking up data in an external system to perform a data validation action.

To deploy an event handler such as this one, you need to use Features within Windows SharePoint Services to register the event handler and ensure that it is deployed to the appropriate sites with all of the dependencies that are required to support the desired end user experience. We cover Features in subsequent chapters such as Chapter 5, in the Web Parts examples; Chapter 8, on workflow; and in the content management scenario featured in Chapter 10.

Summary

This chapter has provided an overview of the programmability features for SharePoint lists and document libraries. We looked at the features for document libraries and lists, including requirements to create these lists and the APIs that are available to facilitate access to the data from third-party applications.

In looking at SharePoint lists and libraries for documents, you learned the characteristics of a list and how lists are used throughout the architecture of Windows SharePoint Services. With respect to programming SharePoint lists, you examined the object model and looked at examples for adding, updating, and deleting data from these lists. This involved using the object model to establish a connection to a site collection, an individual site, and a named list or document library within a site. In addition, you looked at the methods used to identify specific list items within a collection, and the techniques used to create new objects, such as folders, in a list. For SharePoint document libraries, you created a sample application to upload a new document to the server and looked at the object model's support for creating new folders within a library.

You also examined the mechanisms for programming against SharePoint lists for clients that do not have direct access to the SharePoint object model and applications running on non-Windows platforms. This included the various SharePoint web services available for list functions and out-of-the-box support for RSS feed generation on a per-list basis. You also learned about the events associated with SharePoint lists.

In the next chapter, you'll take a deeper look at the XML developer features in the 2007 Office system and the document format improvements, including Open XML, along with other programmability features based on XML data and the extensible user interface of the 2007 Office system.