Monday, 7 February 2011

SP2010 Coding Tips

Retrieving a list using the Serve-side Object Model
Problem:  In MOSS we could use CAML queries or the SharePoint API (Server side object model) to retrieve list data.  In SP2010 there are various methods for getting a list however, the Server-side Object Model has been improved/enhanceced.

SPSite site = new SPSite("");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Customers"];

If the list doesn't exist you received a NullReferenceException.  A try catch block is usually wrapped around the list retrieval however, SP2010 has an improved method TryGetList().

SPList list = web.TryGetLists["Customers"];  // if list doesn't exist list will be null.
Other improvements to the API include: TryGetFieldByStaticName,

Disposing Objects
Problem: SPSite and SPWeb objects are not automatically disposed.
Resolution:  Use either using statements or try catch finally statements to dispose of SPWeb and SPSite objects.  Check all code using the SPDisposal tool.

More Info:
Reading this post jogged my thoughts on the 2 topics posted above.  This is useful for SP developers to know.


Anonymous said...

web.Lists isn't a great idea, as it fetches all the lists from the SPWeb (check SPListCollection.GetListByName in Reflector). Instead, SPWeb.GetList("/Lists/Customers") is recommended. Note that the URL needs to be Site-Relative, so something like web.GetList(SPUtility.ConcatUrls(web.Url,"Lists/Customers")) does the trick.

Post a Comment