Tuesday, December 10, 2013

Create web properties in SharePoint using C#

Introduction

Most of the people use web.config to store values and use those values across multiple web parts. Sometimes editing web.config become mess and some teams don't want to do so. In a situation like this we can use web properties.

Solution

Here is the code and also you can download the .sln file from my drive by clicking below URL.
https://drive.google.com/file/d/0ByEnOE8DAdvhbVozSURYZU9naWM/edit?usp=sharing

     
namespace WebProperty.WebProperty
{
    [ToolboxItemAttribute(false)]
    public class WebProperty : WebPart
    {
        protected override void CreateChildControls()
        {
            Label label = new Label();


            SetWebProperty("NoOfLabels", "10");//Set the property. If the property exists it set and if not create and sets. 

            int maximumNo = Convert.ToInt32(GetWebProperty("NoOfLabels"));//Get the web property value
            for (int i = 0; i < maximumNo; i++)
            {
                label.Text = string.Format("{0}{1}", label.Text, i);
            }
            this.Controls.Add(label);
        }

        void SetWebProperty(string Name, string Value)
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
                {
                    GetWebProperty(Name); //ensure the property exists
                    spWeb.AllowUnsafeUpdates = true;
                    spWeb.AllProperties[Name] = Value;//Set the value for the property 
                    spWeb.Update();
                    spWeb.AllowUnsafeUpdates = false;
                }
            }
        }
        static string GetWebProperty(string Name)
        {
            using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = spSite.OpenWeb(SPContext.Current.Web.ID))
                {
                    //Check whether property exists
                    if (web.AllProperties[Name] == null)
                    {
                        web.AllowUnsafeUpdates = true;
                        web.AllProperties.Add(Name, "");//Creates a new web property
                        web.Update();
                        web.AllowUnsafeUpdates = false;
                        return string.Empty;
                    }
                    else
                    {
                        return web.AllProperties[Name].ToString();
                    }
                }
            }
        }
    }
} 

Conclusion

You may store values in web property instead of web.config whenever you need.

No comments:

Post a Comment