Responsive Ads Here

Saturday, October 18, 2014

Get the property bag values using object model in SharePoint

Property bag is basically a hash table which will store the data in key value pairs. SharePoint allows us to store the configurations in different hierarchy levels through property bags.
Generally we will add configuration entries in web.config file. But this is not a good coding standard, at the same time we can not maintain configuration entries in hierarchy levels in web.config file.
we can set the property bags in different fashions like SP Designer, through code, using power shell and through third party components. 
Below code snippet will help us how to read the property bag using object model.

/// 
/// Reads the Property Bag value for web application
/// 
/// Web Application Object for the same
/// key for property bag values
/// value for the property Bag
public static string ReadWebApplicationPropertyBag(SPWebApplication webapp, string key)
{
  string value = string.Empty;

  try
  {               
     value = Convert.ToString(webapp.Properties[key], CultureInfo.InvariantCulture);          
  }
  catch (Exception ex)
  {
               
  }

  return value;
}

       
/// 
/// Reads the Property Bag value for  Current Site
/// 
/// Site Collection url for the same
/// key for property bag values
/// value for the property Bag
public static string ReadSiteCollectionPropertyBag(string url, string key)
{
  string value = string.Empty;
  try
  {              
      using (SPSite site = new SPSite(url))
      {
        value = Convert.ToString(site.RootWeb.AllProperties[key], CultureInfo.InvariantCulture);
      }
  }
  catch (Exception ex)
  {
                
  }
  return value;
}

/// 
/// Reads the Property Bag value for  Current Web which is hosting the site/sub site
/// 
/// key for property bag values
/// value for the property Bag
public static string ReadCurrentWebPropertyBag(string key)
{
  string value = string.Empty;
  try
  {               
    value = Convert.ToString(SPContext.Current.Web.AllProperties[key], CultureInfo.InvariantCulture);
                 
  }
  catch (Exception ex)
  {
                
  }
  return value;
}

Stay tuned for how to set the Property bag values and reading through CSOM.
Source:--

No comments:

Post a Comment