February 26, 2009

How to add or remove appsettings key/value pair in the web.config of a SharePoint web application programmatically

To add or remove an appsettings key/value pair in the web.config of a SharePoint web application, you have use the Add or Remove methods of the WebConfigModifications property of an instance of the SPWebApplication class. These two methods take a SPWebConfigModification object as parameter.

I build a class (WebConfigManagement) containing static methods to help you to add or remove appsettings key/value pair:


using System;
using System.Reflection;
using Microsoft.SharePoint.Administration;
 
namespace SharePointLiveForMe.SharePoint.Administration
{
    /// <summary>
    /// This class allows to add or remove entries in web.config.
    /// </summary>
    public class WebConfigManagement
    {
        /// <summary>
        /// This methods allows to add a key/value pair in the AppSettings section.
        /// </summary>
        /// <param name="Key">Name of the key</param>
        /// <param name="Value">Value</param>
        /// <param name="webApp">Web application</param>
        public static void AddAppSettingsKeyValue(string key, string value, SPWebApplication webApp)
        {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value) && webApp != null)
            {
                SPWebConfigModification modification = GetModification(key, value);
                if (!webApp.WebConfigModifications.Contains(modification))
                {
                    webApp.WebConfigModifications.Add(modification);
                    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    webApp.Update();
                }
            }
            else
                throw new ArgumentNullException();
        }
 
        /// <summary>
        /// This methods allows to remove a key/value pair in the AppSettings section.
        /// </summary>
        /// <param name="key">Name of the key</param>
        /// <param name="value">Value</param>
        /// <param name="webApp">Web application</param>
        public static void RemoveAppSettingsKeyValue(string key, string value, SPWebApplication webApp)
        {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value) && webApp != null)
            {
                SPWebConfigModification modification = GetModification(key, value);
                if(webApp.WebConfigModifications.Contains(modification))
                {
                    webApp.WebConfigModifications.Remove(modification);
                    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    webApp.Update();
                }
            }
            else
                throw new ArgumentNullException();
        }
 
        /// <summary>
        /// This method allows to build an SPWebConfigModification object.
        /// </summary>
        /// <param name="key">Name of the key</param>
        /// <param name="value">Value</param>
        /// <returns></returns>
        private static SPWebConfigModification GetModification(string key, string value)
        {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                SPWebConfigModification modification = new SPWebConfigModification();
                modification.Name = string.Format(@"add[@key=""{0}""]", key);
                modification.Path = "configuration/appSettings";
                modification.Value = string.Format(@"<add key=""{0}"" value=""{1}"" />", key, value);
                modification.Owner = Assembly.GetExecutingAssembly().FullName;
                modification.Sequence = 0;
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                return modification;
            }
            else
                throw new ArgumentNullException();
        }
    }
}

Hereunder is a little console application to show how to use the WebConfigManagement class:

using System;
using Microsoft.SharePoint.Administration;
using SharePointLiveForMe.SharePoint.Administration;
 
namespace Test.SharePointLiveForMe.SharePoint.Administration
{
    class Program
    {
        static void Main(string[] args)
        {
            SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>("");
            SPWebApplication myWebApplication = null;
            foreach (SPWebApplication webApplication in service.WebApplications)
            {
                if (webApplication.DisplayName == "My Web Application")
                    myWebApplication = webApplication;
            }
 
            Console.WriteLine("Write AppSettings Key/Value");
            WebConfigManagement.AddAppSettingsKeyValue("IsCool", "true", myWebApplication);
            Console.ReadLine();
 
            Console.WriteLine("Remove AppSettings Key/Value");
            WebConfigManagement.RemoveAppSettingsKeyValue("IsCool", "true", myWebApplication);
            Console.ReadLine();
        }
    }

1 comment:

Unknown said...

Nice post, really helped :)