in

didierdanse.net

Site personnel de Didier Danse
Didier Danse's Personnal Website
Microsoft Most Valuable Professional SharePoint

didierdanse.net - Development News

SharePoint: How to use SPWebConfigModification class

SharePoint provides a API that allows developers to modify web.config on all web front-end servers at the same time. This is really a nice concept as soon as it is used the correct way. All web.config modifications should (I could stay must) be performed through the API. Any direct change to web.config files can result in changes lost as this API will override entries in the config file.

Like for all classes and APIs, developers should have a look to documentation to be able to use the API without bringing any mistakes in their code. Unfortunately, this API is poorly documented. The best documentation is coming from blog posts. There is a lot of posts all over the Internet but you have to read a lot of them if you want a global overview of use of this API. So have a look to this simple feature.

SPWebConfigModification usual members

First of all, a web config modification is described with a name, an owner name, an xpath value to define location of the change and a value.

So if you want to add an entry in the web.config file, you have to know how we can define a unique identifier for the entry. As an example, you want to add <action param1=’value1’ param2=’value2’ param3=’value3’ /> and you know that only param3 should be changed, you have to define Name parameter to action [@param1=’value1’] [@param2=’value2’]. This part is the most obscure part of the SPWebConfigModification class and it is really important to understand why you have to use a correct name so let’s have the explanation: When applying modifications, API will read the web.config file and look for a entry with identifier. If it find such an entry, SPWebConfigModification will replace the current value. If not, it will add an new entry. So, if Name doesn’t fit with config entry, you will have duplicate value in the API.

Owner property is also really useful. We will use it to know which entries we have to delete when deactivating the feature.

Feature sample

In this feature, we will add two entries in the web.config file and remove them when deactivating the feature.If you don’t know how to create a feature, please refer to MSDN Documentation.

Feature.xml

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="1625EAF0-F3EB-4c4a-AB8A-36FDBD878AE8"
          Title="Company_FeatureName"
          Description="Used to add some entries in the web.config"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="WebApplication"
          DefaultResourceFile="core"
          ReceiverAssembly="Company.FeatureName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0a1bc23456d78ef9"
          ReceiverClass="Company.FeatureName.WebConfigModificatorFeatureReceiver"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests />
</Feature>

Feature receiver

    class WebConfigModificatorFeatureReceiver : SPFeatureReceiver
    {
        private const string SPWebConfigModificationOwner = "OwnerName";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            string name, xpath, value;

            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            #region ..: appSettings :..
            name = "add[@key='TrustedGroup']";
            xpath = "configuration/appSettings";
            value = "<add key='TrustedGroup' value='Trusted' />";
            ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);

            name = "add[@key='KeyName']";
            xpath = "configuration/appSettings";
            value = "<add key='KeyName' value='Value' />";
            ModifyWebConfig(webApp, name, xpath, value, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode);
            #endregion
 
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (Exception ex)
            {
                RemoveAllModifications(properties);
                throw ex;
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            RemoveAllModifications(properties);

            try
            {
                SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                eventLog.Source = SPWebConfigModificationOwner;
                eventLog.WriteEntry(ex.Message);
                throw ex;
            }
        }

        private void RemoveAllModifications(SPFeatureReceiverProperties properties)
        { 
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;

            List<SPWebConfigModification> modificationsToRemove = new List<SPWebConfigModification>();

            foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
                if (modification.Owner == SPWebConfigModificationOwner)
                    modificationsToRemove.Add(modification);

            foreach (SPWebConfigModification modification in modificationsToRemove)
                webApp.WebConfigModifications.Remove(modification);

            webApp.Update();
        }

        private void ModifyWebConfig(SPWebApplication webApp, String nameModif, String pathModif, String valueModif, SPWebConfigModification.SPWebConfigModificationType typeModif)
        {
            SPWebConfigModification modification = new SPWebConfigModification(nameModif, pathModif);
            modification.Value = valueModif;
            modification.Sequence = 0;
            modification.Type = typeModif;
            modification.Owner = SPWebConfigModificationOwner;

            try
            {
                webApp.WebConfigModifications.Add(modification);
                webApp.Update();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();
                eventLog.Source = SPWebConfigModificationOwner;
                eventLog.WriteEntry(ex.Message);

                throw ex;
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties) { }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { }
    }

Catching exception during ApplyWebConfigModifications

If you run two ApplyWebConfigModifications simultaneously, an exception will be thrown during the second operation and modifications are not sent (I know, I said  simultaneously, I should say if you execute a ApplyWeConfigModifications before the end of another ApplyWebConfigModifications). Unfortunately, modifications are already in the modifications list but not applied in the web.config files and we will add them again during the next feature activation. Because of this, we will remove all the modifications ourselves before throwing the exception to caller.

Scope of modifications

What about the scope? Web config modifications can be applied by web application. To be more precise, this is a web application and all its extensions. It is not possible to apply modifications to a extended web application without applying these modifications to all the extensions.

Entries conflicts

Unfortunately, SharePoint doesn’t provide a solution for web.config conflict values (when two applications added the same entry) so when deactivating one of the feature, entry is removed and the second application may not work correctly.

Entries modifications through UI

Last but not least, if you want to modify a value without executing any code, you will have to use a page that is able to manage all the entries. You can find such a page here: http://blog.thekid.me.uk/archive/2007/03/24/web-config-modification-manager-for-sharepoint.aspx

Hope this post will help!



Comments

 

didierdanse.net - Les news Developpement said:

Lorsque l’on créée des templates de sites personalisés, on est rapidement tenté d’y attacher par défaut

September 17, 2009 3:45 PM
 

Aaren said:

I am using the SPWebConfigModification object to setup default app settings via a feature receiver. These settings can however be manually modified for each application the feature is installed to. The problem is when a second feature is using the SPWebConfigModification to add unrelated configuration, SharePoint uses the modification list to referesh the config and replaces the manually modified values with those from the first feature.

November 26, 2009 1:53 AM
 

Didier Danse said:

Hello,

Yes it is correct. Each time, everything that is in memory will be written to config file. The best way to do this is to use a web page that will override data in "memory" using the same code that you use in your feature. So you should never do a modification directly to Web.config file.

Hope it helps! Do not hesitate to ask if you don't find such a page on the Internet.

Didier

November 28, 2009 4:56 PM
 

Robert said:

Awesome article. Keep up the good work

pingback from www.nitront.com

December 11, 2009 12:19 PM
 

Sharepoint Web.Config Modifications « Sladescross's Blog said:

Pingback from  Sharepoint Web.Config Modifications &laquo; Sladescross&#039;s Blog

April 7, 2010 11:02 AM
 

Article news online science technology - Science technology - News news technology said:

Pingback from  Article news online science technology - Science technology - News news technology

September 9, 2010 7:54 AM
 

VincenzoS said:

Great post. Most complete.

The best relating to SPWebConfigModification

Works with SP2010.

TY.

Vincenzo

October 26, 2010 2:41 PM
 

Change the SharePoint web.config settings in two ways-ixwebhosting said:

Pingback from  Change the SharePoint web.config settings in two ways-ixwebhosting

September 18, 2011 11:11 AM
 

Nick Markakis Jersey said:

http://www.oriolesfanshop.com/           Orioles Jerseys

http://www.oriolesfanshop.com/nick-markakis-jersey           Nick Markakis Jersey

http://www.oriolesfanshop.com/matt-wieters-jersey           Matt Wieters Jersey

http://www.oriolesfanshop.com/brian-roberts-jersey           Brian Roberts Jersey

http://www.oriolesfanshop.com/adam-jones-jersey           Adam Jones Jersey

http://www.oriolesfanshop.com/vladimir-guerrero-jersey           Vladimir Guerrero Jersey

http://www.oriolesfanshop.com/brooks-robinson-jersey           Brooks Robinson Jersey

http://www.oriolesfanshop.com/eddie-murray-jersey           Eddie Murray Jersey

http://www.oriolesfanshop.com/cal-ripken-jersey           Cal Ripken Jersey

http://www.oriolesfanshop.com/derrek-lee-jersey           Derrek Lee Jersey

http://www.oriolesfanshop.com/jake-arrieta-jersey           Jake Arrieta Jersey

http://www.oriolesfanshop.com/craig-tatum-jersey           Craig Tatum Jersey

http://www.oriolesfanshop.com/jim-johnson-jersey           Jim Johnson Jersey

June 14, 2012 2:01 AM
 

rtyrwey said:

I read your article, I feel that a good!

<a href="www.oaklysunglassesshop.com"">www.oaklysunglassesshop.com" >oakly unglassess </a>

www.oaklysunglassesshop.com

<a href="www.hervelegervipclub.com"">www.hervelegervipclub.com" >herve leger </a>

www.hervelegervipclub.com

<a href="www.redbottomshoescommunity.com" >red bottom shoes </a>

www.redbottomshoescommunity.com

<a href="http://www.hermescolumn.com"">http://www.hermescolumn.com" >hermes bags </a>

http://www.hermescolumn.com

<a href="http://www.karenmillenbox.com"">http://www.karenmillenbox.com" >karen millen</a>

http://www.karenmillenbox.com

<a href="www.cheaplouisvuittonhandbagshop.com">Louis">www.cheaplouisvuittonhandbagshop.com/">Louis Vuitton Handbags</a>

www.cheaplouisvuittonhandbagshop.com

June 27, 2012 7:48 AM
 

hermes birkin replica said:

Keep functioning ,terrific job!

www.hermeshandbagoutlet.com

June 29, 2012 10:50 PM
 

Louis Vuitton Canada said:

For that reason product groups for Classic www.coachfactoryonline2012onsale.com  Coach Factory Online boots for that snow using the styles are very similar Christian Louboutin Flats. www.louisvuittonlcanadav.ca Louis Vuitton Canada  Snowfall in the twenties emerged nationwide, initially ugly as SHOE ugly boots and backare recognized, which http://www.ukggboots.co.uk/ UGG UK  range from an intermittent use every day.

October 23, 2012 11:16 PM
 

North Face Jackets said:

an effective layer as well as hat could work to suit your needs.

www.northfacesuksale.co.uk

November 23, 2012 10:13 PM
 

クリスチャンルブタン said:

ブランドコピー時計,スーパーコピー時計,激安ブランドコピー腕時計人気ランキング

http://www.joustu.net/

April 19, 2013 5:26 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
L'auteur du site ne peut être tenu responsable des dommages que les informations fournies pourraient entraîner. Tout est cependant mis en oeuvre pour éviter tout désagrément.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems