Tuesday, December 27, 2011

Property Bags in SharePoint 2010

What's a Property Bag?

Many SharePoint objects such as Web applications, site collections, web and lists have a property bag associated with them.  What are these things?

The property bag is a key-value dictionary that stores configuration information.  For example, the property bag for a SharePoint Wiki page stores the HTML on the page.

What Good Are They?

A property bag can be used by a SharePoint developer to store configuration information.  It seems best suited to information that doesn't change often and might be a really good alternative to the SharePoint web.config file.

Reading a Property (2010)

Access to the property bag should be dead simple, but there are compatibility issues. For 2010, you should use the case-sensitive "GetProperty" method.  For 2007, you use the all-lower-case Properties collection. The latter will not be able to access 2010 case-sensitive properties:

using (SPSite siteCollection = new SPSite(http://localhost/)
{
    using (SPWeb myWeb = siteCollection.RootWeb)
    {
        lblValueFound.Text = myWeb.GetProperty("mike").ToString();
    }
}

Adding a Property (2010)

Most of the samples I found on the web are SharePoint 2007 and I can't get them to work in 2010. Most of these samples look something like this:

// Doesn't work in 2010.  The property is not persisted
using (SPSite siteCollection = new SPSite(http://localhost/)
{
    using (SPWeb myWeb = siteCollection.RootWeb)
    {
        myWeb.AllowUnsafeUpdates = true;
        // Below doesn't work in 2010
        myWeb.Properties.Add("thenewkey", "The NewValue");
        myWeb.Update();
        myWeb.AllowUnsafeUpdates = false;
    }
}
Instead, You need to use the new AddProperty() method.

using (SPSite siteCollection = new SPSite(http://localhost/)
{
    using (SPWeb myWeb = siteCollection.RootWeb)
    {
        // The key must be lower-case
        myWeb.AddProperty("thenewkey", "The NewValue");
        myWeb.Update();
    }
}

Notes:
 
  1. If you use the "AddProperty()" method, you don't need the AllowUnsafeUpdates shown in many examples on the web.
  2. For backward compatibility, stick to lower case keys. Mixed case keys can be stored and retrieved using the new 2010 methods but are invisibile to older code that uses the Properties collection. (More information: http://trentacular.com/2009/06/sharepoint-the-wicked-spwebproperties-propertybag/)
  3. There are many examples on the internet that don't work. Here are just two:
  4. The clue to all why all the other examples don't work (thanks Nancy): http://sharepoint.mindsharpblogs.com/NancyB/archive/2011/06/29/The-Sandboxed-Solutions-and-SPWeb.AllProperties-Puzzle.aspx