Sunday, February 14, 2010

Programming Against the WSS Object Model

 

Another important aspect of WSS development is programming against the WSS object model. The core types provided by the WSS programming model are exposed through a standard WSS assembly named Microsoft.SharePoint.dll.

Let’s look at a simple example. Imagine you have just created a console application, and you have added a reference to Microsoft.SharePoint.dll. The WSS object model exposes an SPSite class that serves as an entry point into the WSS object model at the site collection level. Each site within a site collection is represented as an SPWeb object. Each list within a site is represented as an SPList object. Here’s a simple example using the WSS object model to access the top-level site within a target site collection and discover all its lists.

using Microsoft.SharePoint;
namespace Hello_WSS_OM {
  class Program {
    static void Main() {
      string sitePath = "http://litwareinc.com";
      // enter object model through site collection.
      SPSite siteCollection = new SPSite(sitePath);
      // obtain reference to top-level site.
      SPWeb site = siteCollection.RootWeb;
      // enumerate through lists of site
      foreach (SPList list in site.Lists) {
        Console.WriteLine(list.Title);
      }
      // clean up by calling Dispose.
      site.Dispose();
      siteCollection.Dispose();
    }
  }
}

You should observe the two calls to the Dispose method at the end of this code example. Several object types in the WSS object model, such as SPSite and SPWeb, use unmanaged resources and must be disposed of in a timely manner. If you fail to do this and simply rely on the garbage collector of the .NET Framework to reclaim memory, your code can cause problems by consuming far more memory than it needs. As a rule of thumb, when you create a disposable object, you are also responsible for calling Dispose on it. However, object references obtained through the WSS Web application’s SPContext should not be disposed.

No comments:

Post a Comment