Tuesday, 20 September 2011

Very Quick Guide to the SharePoint Object Model

There are plenty of places to read about this in detail so I will just go through it quickly before getting into Event Handling. SharePoint 2007 deals with the following objects in toto:

Lists (of all kinds)
ListItems (items in the lists)
Fields (fields in the items in the lists in the bog down in the valley-oh. It usually suffices to indicate a field by putting the name in square brackets and quotes after the list item e.g. item["FieldName"] )
Document Libraries (which are really just lists. Everything in SharePoint is a list.)
Sites (except a Site is not a list. Forget what I just said.)

"Sites" is ambiguous because in 2007 They introduced the idea of Site Collections (and junked it in 2010 I think) so you have the site collection and then the actual site. I have only ever created a site collection once and that was using the Central Admin. And it was on a test machine far far away...but still they are important and I will explain why.

When you fire up Visual Studio and get ready to stick in your SharePoint code, bear in mind that the object
means "site collection" and
means "site"

That means in practical terms in order to open up the oyster and get to the meat, you have to crack two shells before slurping the good bit (Apologies to any vegetarians reading this.) First you have to instantiate an SPSite object with your URL e.g. http://mysharepoint/sc/somesite/ and then you have to instantiate the web object using the Site object.

So, always using the using construct (so we never have to worry about calling the Dispose method) one instantiates the site as follows:

string url = " http://mysharepoint/sc/somesite/"
using (SPSite site = new SPSite(url))
using (SPWeb web = site.OpenWeb())
   //now we want a specific list and we can do our work
    SPList list = web.Lists["myList"];
    SPListItem item = list.Items[0];

There is one exception to the using construct. This is when getting data from the current site. That's the one you have open in your browser.
For obvious reasons, you do not want to Dispose() of your open site! Unless you're in bad odour with the Powers that Be and they unwisely made you site admin...

No comments:

Post a Comment