C# Code Snippets

Function to fetch value from Property Bag

Many a times there is a requirement to allow some values to be configurable. This can be achieved using custom list and an inbuilt option available for this is the Property Bag.

We need to configure the Property Bag in the central admin and the particular site for using it.

The following is the function that assists us to fetch value from the property bag:


public string getProperty(string propertyName)
{
try
{
SPWeb siteCollectionWeb = SPContext.Current.Site.RootWeb;
SPPropertyBag props = siteCollectionWeb.Properties;
Boolean propertyExist = props.ContainsKey(propertyName);
string value = null;
if (propertyExist)
{
value = siteCollectionWeb.AllProperties[propertyName].ToString();
}
value = siteCollectionWeb.AllProperties[propertyName].ToString();
return value;
}
catch (Exception ex)
{
string msg = ex.Message;//LeaveLogFileLocation
TextWriter tw1 = new StreamWriter(getProperty("LeaveLogFileLocation"), true);
tw1.WriteLine("getPropertyEvent : " + DateTime.Now);
tw1.WriteLine(ex.StackTrace);
tw1.Close();
throw ex;
}
}

In order to fetch the values from the Property Bag we just need to call this function by passing the key as the parameter to the function.

Ex: getProperty(“LeaveLogFileLocation”), true)

Here “LeaveLogFileLocation” is the key.

Leave a comment