How To Use Property Bag In SharePoint 2010

Why do we use a property bag?

Property bag is a hash table that can be used to store any metadata Key-Value pairs, such as connection strings, server names, file paths and other settings needed by a SharePoint application.

Most of the time, we store the above settings in a configuration file which is common to the entire web application. So, we need a setting that is specific to each individual site collection in the web application. The answer is property bag. 

Every site collection can have its own property bag.

How to add property to a property bag?

It can be done through PowerShell or via SharePoint Object model.

PowerShell script

  1. $url = “SiteUrl of site”  
  2. $site = New - Object Microsoft.SharePoint.SPSite($url)  
  3. $rootWeb = $site.RootWeb  
  4. $value = ”evs.com”  
  5. $ActiveDirectoryName = ”ActiveDirectoryName”  
  6. If(!$$rootWeb.Properties.ContainsKey($ActiveDirectoryName) {  
  7.             $rootWeb.Properties.Add($ActiveDirectoryName, $value)  
  8.         } else {  
  9.             $rootWeb.Properties[($ActiveDirectoryName] = $value  
  10.             }  
  11.             $rootWeb.Properties.Update()  
  12.             $rootWeb.Update()  
Through Code

If you are doing it via code, then you must have site admin rights to do so, otherwise we have to use SPSecurity.RunWithElevatedPrivileges,
  1. SPSecurity.RunWithElevatedPrivileges(delegate() {  
  2.     try {  
  3.         using(SPSite RootSite = new SPSite(URL)) {  
  4.             using(SPWeb SiteCollection = RootSite.OpenWeb()) {  
  5.                 try {  
  6.                     SiteCollection.AllowUnsafeUpdates = true;  
  7.                     // Get connection string from Property bag  
  8.                     if (!SiteCollection.AllProperties.ContainsKey("ActiveDirectoryName")) {  
  9.                         SiteCollection.Properties.Add("ActiveDirectoryName", ”abc.com”);  
  10.                     } else {  
  11.                         SiteCollection.Properties["ActiveDirectoryName"] = “abc.com”  
  12.                     }  
  13.                     SiteCollection.Properties.Update();  
  14.                     SiteCollection.AllowUnsafeUpdates = false;  
  15.                 } catch (Exception ex) {  
  16.                     //Handle Exception  
  17.                 }  
  18.             }  
  19.         }  
  20.     } catch (Exception ex) {}  
  21. });  
How to get it?
  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     lblADName.Text = Convert.ToString(SPContext.Current.Web.AllProperties["directoryname"]);  
  3. }  
  4. }  
Points to remember about property bags

  • Maximum length of property bag value can be 255 characters.
  • Properties can be added and updated via power shell and there is no need to recycle the pool application.
  • We can only store 4 kb of values in property bag.