Property bag
in SharePoint exist in MOSS version and even continued to be a part of 2010
version. Property bag is nothing but a key value pair stored as hash table that
we can retrieve in object model.
We can add,
edit or remove properties from property bag from SharePoint Designer or through
object model.
So let’s go
ahead and check that out in Designer. Connect with the site.
Check out
site options and click on it.
Here you can
see parameters; these are the properties for this site. Here we can add, edit
and remove. Let’s go ahead and add three properties and values.
Click on Add
give name and value.
In the same
way create two more properties.
Before we
dive into coding part, I would like to bring in some more details.
We can define
properties for several levels in SharePoint. At highest level we can have it
for SPFarm, then SPWebApplication, then for SPSite, for SPWeb and for SPList.
Let’s us
start by adding and retrieving properties that we just defined at web level.
protected void
btnPropertyBag_Click(Object sender, EventArgs e)
{
SPWeb objWeb = SPContext.Current.Web;
objWeb.Properties.Add("CustomKey4AddedFromCode",
"CustomValue4AddedFromCode");
objWeb.Properties.Update();
string strProp =
objWeb.AllProperties["CustomKey1"].ToString();
strProp = objWeb.AllProperties["CustomKey2"].ToString();
strProp = objWeb.AllProperties["CustomKey3"].ToString();
}
Sometime you
can have Properties and not AllProperties like for SPlist, , SP web application
and SP farm.
You can also
remove property that we’ve added.
objWeb.Properties.Remove("CustomKey4AddedFromCode");
If you want
to check if the key exist, use containskey
if(objWeb.Properties.ContainsKey(""))
If you want
to add it to the list or library, then you won’t find properties collection
directly. You need to take rootfolder object and store it there. Like shown
below.
SPWeb objWeb = SPContext.Current.Web;
SPList lstCalendar = objWeb.Lists.TryGetList("Calendar");
lstCalendar.RootFolder.Properties.Add("CustomCalendarKey", "CustomCalendarValue");
For SPSite
there is no as such property bag available, but if you want to store, then use
rootweb for SPSite and then assign properties. Like shown below.
SPWeb objWeb = SPContext.Current.Web;
SPSite objSite = objWeb.Site;
objSite.RootWeb.Properties.Add("SiteLevelKey", "SiteLevelValue");
For Web
Application you can use this
SPWeb objWeb = SPContext.Current.Web;
Microsoft.SharePoint.Administration.SPWebApplication
objWebApp = objWeb.Site.WebApplication;
objWebApp.Properties.Add("WebAppLevelKey",
"WebAppLevelValue");
Hope this
will help to understand property bag.