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
- $url = “SiteUrl of site”
- $site = New - Object Microsoft.SharePoint.SPSite($url)
- $rootWeb = $site.RootWeb
- $value = ”evs.com”
- $ActiveDirectoryName = ”ActiveDirectoryName”
- If(!$$rootWeb.Properties.ContainsKey($ActiveDirectoryName) {
- $rootWeb.Properties.Add($ActiveDirectoryName, $value)
- } else {
- $rootWeb.Properties[($ActiveDirectoryName] = $value
- }
- $rootWeb.Properties.Update()
- $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,
- SPSecurity.RunWithElevatedPrivileges(delegate() {
- try {
- using(SPSite RootSite = new SPSite(URL)) {
- using(SPWeb SiteCollection = RootSite.OpenWeb()) {
- try {
- SiteCollection.AllowUnsafeUpdates = true;
-
- if (!SiteCollection.AllProperties.ContainsKey("ActiveDirectoryName")) {
- SiteCollection.Properties.Add("ActiveDirectoryName", ”abc.com”);
- } else {
- SiteCollection.Properties["ActiveDirectoryName"] = “abc.com”
- }
- SiteCollection.Properties.Update();
- SiteCollection.AllowUnsafeUpdates = false;
- } catch (Exception ex) {
-
- }
- }
- }
- } catch (Exception ex) {}
- });
How to get it?
- protected void Page_Load(object sender, EventArgs e) {
- lblADName.Text = Convert.ToString(SPContext.Current.Web.AllProperties["directoryname"]);
- }
- }
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.