Wednesday, July 17, 2013

SPWeb and the adventure with the property bag

Sometimes working with SharePoint it feels like you had 10 Jägerbombs in a row last night.
Chronologically speaking the last funny thing was about the SPWeb Property Bag.
First of all in SPWeb object we can find:
properties 

and
allproperties 

According to MSDN the Properties property:
This property returns only a subset of the metadata for a website. To get all the metadata, use the AllProperties property.

Basically this property is still there for backward compatibility, so now it’s better to use the AllProperties property.
That’s ok but let me talk about an issue that I got. If you are working with the property bag and you want to remove a key/value from it an easy and normal way seem to be:
if ( web.AllProperties.ContainsKey ( property.Key.ToString ( ) ) )
{
web.AllProperties.Remove ( property.Key.ToString ( ) );
}
web.Update ( );

but that way doesn’t work and neither does setting the value to null before calling the Remove method (as many suggest around the web).

The only useful way that I've found is to do this:
if ( web.AllProperties.ContainsKey ( property.Key.ToString ( ) ) )
{
web.DeleteProperty ( property.Key.ToString ( ) );
}


From MSDN: This method deletes a property from the AllProperties property that is a key/value pair.

Taking a look inside the Microsoft.Sharepoint.dll about the DeleteProperty method seems it calls the Remove method of the HashTable as I wrote above:
reflector_delete_property 
and that is what is inside that method:


 inside the delete method


Maybe a little bit more scouting would make the idea clearer.
enjoy
.S

No comments:

Post a Comment