Monday, April 16, 2012

Managing Key-Value Pair Settings in SharePoint

Recently my team discussed various ways to manage application configuration settings in SharePoint.  We wanted to avoid using Web.Config files for Key-Value Pair data because of the complexity of managing this data in SharePoint.

SharePoint contains a decent API (SPWebConfigModification) for managing web.config settings across the farm.  It works pretty good, but we have had some trouble with it in certain situations.  If you are interested in a good article on SPWebConfigModification check out this one by Mark Wagner

Thankfully the folks on the SharePoint development team delivered just what we needed to have a simple solution for managing key-value pair settings.  It is the SPPropertyBag class.

SharePoint provides a properties collection for SPFarm, SPWebApplication, SPWebService and SPWeb objects (none for SPSite, but site settings can be stored @ SPSite.RootWeb).

The properties collection for SPFarm, SPWebApplication and SPWebService are not really based on the SPPropertyBag class.  The properties collection comes from the derived class SPPersistedObject and is actually a HashTable.  But it works exactly the same as SPPropertyBag.

It is really easy to manage the properties settings.  Here is some sample code to update settings for SPFarm, SPWebApplication or SPWebService.

public static void SetPropertyValue(SPPersistedObject spObject, string name, string value)
{
if (spObject.Properties.ContainsKey(name))
{
spObject.Properties[name] = value;
}
else
{
spObject.Properties.Add(name, value);
}
spObject.Update();
}

The SPWeb class actually uses SPPropertyBag for its properties.  The code to manage SPWeb.Properties is similar.


public static void SetPropertyValue(SPWeb webSite, string name, string value)
{
if (webSite.Properties.ContainsKey(name))
{
webSite.Properties[name] = value;
}
else
{
webSite.Properties.Add(name, value);
}
webSite.Properties.Update();
}

View the original article here

No comments:

Post a Comment