Wednesday, April 8, 2009

Store Metadata in Property Bag for SPWEB

Property bags are a new feature of Windows SharePoint Services 3.0. A property bag enables you, as a developer, to add properties to objects in a Windows SharePoint Services site. Property bags are implemented by Windows SharePoint Services as a simple hash table of property names and values.

Many Windows SharePoint Services objects expose property bags, including:

SPWeb
SPFolder
SPFile
SPListItem

You can create and remove properties in a property bag programmatically, and you can modify the values assigned to properties. After updating a property in a property bag, you must invoke the Update() method so that the property value is persisted in the site database.

The following example shows code for adding a property to the property bag of an SPWeb object. The code also shows how to iterate through the property bag to retrieve key names and values.
Visual C# Code Example

// Obtain a reference to the current Web
SPWeb list = SPControl.GetContextWeb(Context);
// Enable updates to be made to the SPWeb object
list .AllowUnsafeUpdates = true;
// Add a property and update the property bag
list .Properties.Add("Project", "Development");
list .Properties.Update();
// Disable updates for the SPWeb object
list .AllowUnsafeUpdates = false;
// Iterate through the properties in the property bag
for each(System.Collections.DictionaryEntry webProperty
in
list .Properties)
{
this.Page.Response.Write(webProperty.Key.ToString()
+ " : "
+ webProperty.Value.ToString()
+ "
");
}


Once my metadata are added to my SPWeb properties, it's impossible to remove them.

Here is my code to delete :

site.Properties.Remove("mykey");

site.Properties.Update();

site.Update();