Sunday, July 5, 2009

SharePoint 2003 Object Model - contacts list again

After doing the first two posts on getting started with SharePoint Webservices (post 1 + post 2), I didn’t mean for it to take so long to do the next one. Mix 06 and other various bits of work got in the way though, so this weekend was the first chance I had to sit down for a couple of hours and work on something. After the first two posts were looking at the using the SharePoint webservices I thought it would be a good idea to take a look at the alternative, the SharePoint Object Model. As we looked at the contact list before I thought it was best to do the same for the object model. What we are looking to do is bring back a list of contacts to view, edit these contacts, and add completely new ones.

First thing to do is create a new VS.NET 2003 application (or 2005, the choice is up to you really). Once you are there with your blank form you need to add a reference to Microsoft.SharePoint.dll. If you’re developing in a Windows 2003 development environment then it should just be in the list of .NET libraries, but if not you’ll need to go to a server with SharePoint installed on, and put a copy on the machine you are working on. You can find the dll at:

local_drive:\Program Files\Common Files\Microsoft Shared\Web server extensions\60\ISAPI

Now you’re ready to go! First thing to remember about this code is that I developed it on a Windows 2003 installation which had SP 2003 and VS.NET installed and so I was therefore running as administrator. This meant I had access to all the sites and all the lists. If you’ve not got access to a site or list you try to access with the object model you’ll get a url not found exception. I’ll add an update to the code soon so that if this does happen you’ll have a chance to enter a username and password, ran out of time this weekend though.

Now lets get on with some code, add:

using Microsoft.SharePoint

to the top of your form so you don’t have to keep typing the same namespace out everytime. Unlike the SharePoint webservices where you have to work directly with XML (CAML), unsurprisingly with the SharePoint Object Model everything has it’s own object, from sites to list items. So pressuming we have a SharePoint site at http://localhost and it has a contacts list we can use the following code to get these back:

SPSite siteCollection = new SPSite(“http://localhost”);
SPWeb s = siteCollection.AllWebs[””];
SPList contacts = s.Lists["contacts"];

The second line is there incase you wanted to get the contact list from a subsite. If you do just put the name of the subsite in between the blank quotes ie SPWeb s = siteCollection.AllWebs[”site1”];
Finally the third line gets the actual SharePoint List called contacts out of the selected SharePoint site.

Now we have our list we can iterate though it and pull back each contact list item. Unfortunately SPList does not implement IEnumurable so we have to do a standard ‘for’ loop. For the time being we’ll just get the firstname and surname (which gets saved as Title!)

for(int i = 0; i < contacts.ItemCount; i++)
{
bool add = false;
StringBuilder sb = new StringBuilder();

if(contacts.Items[i]["FirstName"] != null)
{
add = true;
sb.Append(contacts.Items[i]["FirstName"].ToString());
}

if(contacts.Items[i]["Title"] != null)
{
if(add)
sb.Append(" ");
sb.Append(contacts.Items[i]["Title"].ToString());
else
sb.Append(contacts.Items[i]["Title"].ToString());

}
       MessageBox.Show(sb.ToString());
}

The code above will pop up a messagebox for every contact that is in your list. It’s worth noting that you need to check for a fields existence before accessing it. If the ListItem does not have a value, then it will not be returned at all, resulting in a ‘Value does not fall within the expected range’ error. Remember the best place to get all the names of fields available for a lists is wwsdemo.

So now we can get values back, how about editing them and adding? Well it’s not that difficult! Each list object has an add method that returns an actual new list item. Then once you’ve finished adding your new field values, you call the actual items update method. For updating you have two options. You can either update the list values straight from the list object, or set the value of a list item to the one you want and set the values there. For the update example I’ll be doing the second. So check out the code below for doing additions and edits:

SPSite siteCollection = new SPSite(“http://localhost”);
SPWeb s = siteCollection.AllWebs[””];
SPList contacts = s.Lists["contacts"];

// add a new item…
SPListItem contact = contacts.Lists["contacts"].Items.Add();
contact["FirstName"] = “Nick”;
contact["Title"] = “Swan”;

contact.Update();

// update an item…
SPListItem contact = contacts.GetItemById(1);
contact["FirstName"] = “Nick”;
contact["Title"] = “Swan”;

contact.Update();

As you can see it’s all pretty easy. The thing to be careful with is that the field name properties are case sensitive! The most annoying thing about this is that when you are running the code, the error won’t generate on the property that you have wrong, it will happen on the row afterwards again with the message of ‘Value does not fall within the expected range’. Most confusing as you think you have an error on one line, when really it’s on the previous one. Ho hum! Just something to remember!

So that’s about it. A very basic example, but it should get you started (and from the search results that get to the first webservice posts there are a lot of people looking to get started). I’ve created a demonstration application with full source code for you to give a try. Simply put the site name (and subsite if you so with), and it will bring back the names and details from the contact list. You can edit existing contacts, and also add new ones. It’s not ground breaking work, but hopefully it will help some of you out! Click here to download the VS.NET 2003 project.

(it is worth remembering that I run this application on a dev server where I have admin rights to the SharePoint sites. Your user account will need the correct SharePoint permissions to be able read/write/update the contacts list.)

If you’ve got any questions or feedback please use the comments. I’m considering when it’s best to use the object model or webservices so if you all have any thoughts on that I’m all ears (I have my own thoughts, but am keen to hear what others think).

No comments:

Post a Comment