Sunday, April 20, 2008

Using Property Bag of SPWeb to store Metadata

On an SPWeb there is no out-of-the-box solution to store custom metadata, you only have the name (URL), the title and the description. If you need more (e.g. status (active/inactive) or location) you have to implement a custom solution.

A possible way is to create a list (with the fields you need) that has only one list entry: the metadata of the parent SPWeb. With versioning enabled you also versioned metadata for your SPWeb. But if you have many sites of this type this may be some overkill to have an extra list for the metadata in each site.
Another solution is to use the property bag of the SPWeb and store the additional metadata directly in the SPWeb. This needs some coding of course (Web Part or Layouts application) and you have to integrate it into your sites. But the code is very simple:

Writing values:

string strKey = "MyKey";
string strValue = "MyValue";
if (webCurrent.Properties.ContainsKey(strKey)) // property exists already -> update it

webCurrent.Properties[strKey] = strValue;
else
if (strValue.Length > 0) // property doesn't exist -> add it if there is value to set
webCurrent.Properties.Add(strKey, strValue);
webCurrent.Properties.Update();

Reading values:

string strKey = "MyKey";
string strValue = string.Empty;
if (webCurrent.Properties.ContainsKey(strKey))
strValue = webCurrent.Properties[strKey];

If you want to save some metadata about the lists in the current SPWeb you can also use the property bag of your SPWeb. Just add the Guid of the list to each name of the property:

string strKey = "MyKey_" + listCurrent.ID.ToString();

To remove a property use the following lines:

// attention: SPWeb.Properties.Remove(string pKey) doesn't work to remove
// a property. To remove a property clear the content.
webCurrent.Properties[strKey] = null;
webCurrent.Properties.Update();
webCurrent.Update();

1 comment:

Sal Carl said...

Very Simple and effective post