Wednesday, January 11, 2012

Properties or AllProperties of SPWeb / SPWebApplication

Properties and Properties Bag may be differently if you are working on SharePoint. Especially for to update and remove data from their collection.



If you want to add

webApp.Properties.Add(p1);

That means you just add a propery to Web Application's properties and SPWeb's properties bag. However, if you remove this key out properties list, like following the code:

webApp.Properties.Remove(p1);

That means you just remove p1 out from SPWeb's properties bag, and in Web Application's properties is still existed. So, at the next time, you will never add or after sucessfull adding, nothing is added into SPWeb.

So, the best practice is always update or remove from both properties to be sured the system works correctly.


Add Properties


web.AllowUnsafeUpdates = true;


//Add property if not exist

if (web.AllProperties[strPropertyKey] == null)
{
       web.AllProperties.Add(strPropertyKey, strPropertyValue);
}




if (web.Properties[strPropertyKey] == null)
{
       web.Properties.Add(strPropertyKey, strPropertyValue);
}



web.Update();
web.Properties.Update();
web.AllowUnsafeUpdates = false;

Update properties



web.AllowUnsafeUpdates = true;


web.AllProperties[strPropertyKey] =  strPropertyValue;


web.Properties[strPropertyKey] = strPropertyValue;



web.Update();
web.Properties.Update();
web.AllowUnsafeUpdates = false;

Delete Properties


web.AllowUnsafeUpdates = true;


web.Properties.Remove(strPropertyKey);


web.AllProperties[strPropertyKey] =  null;


web.Update();
web.Properties.Update();
web.AllowUnsafeUpdates = false;

Hope this help.

No comments: