Thursday, November 21, 2013

Farm PropertyBag in SharePoint

Creating and Configuring the Farm level property enable the Farm administrator to control the configuration settings on Site / Web level. He can expose the some of the general values such as variable,connection strings and etc..to all the server available in Farm. To use SPFarm class include the "SharePoint.Administration" namespace in your code. SPFarm class will not work unless you connected to at least one Physical server. In the VM which is cloned or mimic from the actual server,you cannot execute this class based code in your solution. Secondly,your current application pool account and Farm account must be same otherwise you'll get the "Access Denied or Unauthorized exception even though you used "RunWithElevated Privilege" delegation. You can identify what account being used by your Farm,by navigating to your "Central Administration Page",->Security header under,Click on "Configure Service Account". Select the "Farm account from the drop down list->It will shows the account which is used by your Farm.
 protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.CodeToRunElevated code = new SPSecurity.CodeToRunElevated(UpdateMyKey);
            code.Invoke();
            
        }
        public void UpdateMyKey()
        {
            SPWeb web = SPContext.Current.Web;
            web.AllowUnsafeUpdates = true;
            SPFarm farm = SPFarm.Local;
            farm.Properties.Add("MyKey1", "MyValue");
            farm.Update();
            web.AllowUnsafeUpdates = false;
        }

//Retrieve the Farm Value in your Site/Sub Site Level.
        public void GetValue(Object sender,EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            String propertyValue = farm.Properties["MyKey1"].ToString();
            Response.Write(propertyValue);

        }