Friday, October 8, 2010

List Access Through the WSS Object Model

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}
Note the required call to the Update method on the SPList object at the end of this listing. This is required to save any changes you have made to list properties, such as, in this case, assigning a value of “true” to the OnQuickLaunch property.
Lists can also be accessed by using the GetList methods of the SPWeb class:
SPList announcementsList = web.GetList("/Lists/Announcements");
The GetList method takes a site-relative path to the list folder or a list form page as an argument. If the list instance is not found, the GetList method will throw an exception of type FileNotFoundException. The only way to check if a list exists without throwing an exception is to enumerate the site object’s lists and check for its existence.
Tip GetList is the preferred method to access a list by a URL. GetListFromUrl and GetListFromWebPartPageUrl function the same way as GetList but throw a generic SPException on failure rather than the more descriptive FileNotFoundException.
After you have a reference to an SPList object for the list, you can create a new list item by adding an SPListItem to its Items collection. The SPListItem is a generic item with fields corresponding to the fields in the list. You can create and save a new list item by using the following code:
SPListItem newItem = list.Items.Add();
newItem ["Title"] = "Litware Goes Public!";
newItem ["Body"] = " We all live in exciting times.";
newItem["Expires"] = DateTime.Now + TimeSpan.FromDays(2);
newItem.Update();
The Update method of the SPListItem object commits the changes to the list. If you don’t call the Update method, the list item data will not be saved. The fields (columns) of the list are specified using the display name. They can also be accessed by the GUID identifier of the field or the zero-based index in the Fields collection. If a field is specified that is not in the Fields collection for the list, an ArgumentException will be thrown. In some scenarios, you may want to enumerate through the fields in a list by using a foreach construct to ensure the field you are looking for really exists.
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine(field.Title);
}
Enumerating through the fields also can be useful when enumerating list items. You can use the Fields collection to access data from the list item. To limit the fields displayed, you may want to display only user editable fields as shown in the following code example:
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
Using Queries for List Data
To get back specific results within a list, you can use the SPQuery object. When you use an SPQuery object, you will create CAML statements to select specific data within the target list. To select announcements that have expired, you may want to use a query built with CAML statements, as shown in the following example:
SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"";

SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
You must specify the fields you want returned in the query by using the ViewFields property. Also note that you must specify the fields in terms of the field Name, and not DisplayName. If you attempt to access fields without specifying them in ViewFields, you will experience an exception of type ArgumentException.
The basic syntax for the query is “ ”. Table 6-2, which appears later in this chapter, lists the basic CAML you will use with queries; for a more complete listing see the SDK.
SPQuery is a great way to get back items from a single list. Furthermore, using SPQuery can be significantly faster than enumerating through all the items within a particular list when you are looking only for items that match certain criteria. However, WSS 3.0 introduces a new query mechanism via the SPSiteDataQuery class. A query run with the SPSiteDataQuery class can return items from many different lists through an entire site collection. For this reason, queries run with the SPSiteDataQuery class are sometimes referred to as cross-site queries.
As you saw in the last example, queries run against an SPQuery object return an SPListItemCollection. Queries run with an SPSiteDataQuery object are different, because they return an ADO.NET DataTable object. Just as with SPQuery, columns that are returned in the DataTable are specified as fields. For example, imagine a scenario in which you want to run a single query against every list in the current site collection that has been created from the Announcements list type and return all list items that were created today. The following code sample demonstrates how to do this by creating an SPSiteDataQuery object, initializing it with the necessary CAML statements, and then passing it to the current SPWeb object’s GetSiteData method.
SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";
string queryText = @" ";
query.Query = queryText;

DataTable table = site.GetSiteData(query);

foreach (DataRow row in table.Rows)

{
Console.WriteLine(row["Title"].ToString());
}
This example assigns a CAML statement to the Lists property that specifies the ServerTemplate of 104, which is the list type identifier for the Announcements list. Even though GetSiteData is a method of the SPWeb reference, the query is performed against all sites in the current site collection. The scope of the query is controlled through a CAML statement in the SPSiteDataQuery’s Webs property, which assigns a value of “SiteCollection” to the Scope attribute. You can limit the query to a scope of “Site” to just query the current site or to a scope of “Recursive” to query the current site and all the child sites beneath it.
If you need to get a reference to the actual list item, you can get it by using the columns WebId, ListId, and ID.
SPWeb parentWeb = web.Site.OpenWeb(new Guid(row["WebId"].ToString()));
SPList list = parentWeb.Lists[ new Guid(row["ListId"].ToString()) ];
SPListItem item = list.GetItemById((int.Parse(row["ID"].ToString())));
The SPSiteDataQuery class is perhaps most useful for creating data-aggregation Web Parts, or data-aggregation XML feeds, such as a recently published RSS feed. Listing 6-2 displays sample code for a recently published RSS feed. This same code could be used within a Web Part to create a rollup Web Part for any type of list, or you could use query parameters to vary the scope of the recently published items.
When using the SPSiteDataQuery class, you should note that only items that match the schema of the ViewFields parameter are returned. You also can filter the results by the ContentType field. In this case, we will filter on the Post content type. To use this handler, register it with the following element within the httpHandlers node of web.config:

No comments: