Prevent errors while using SPWebConfigModification

Today I ran into an issue with SPWebConfigModification.

SPWebConfigModification can be used to make changes to SharePoint's web.config. The advantage of using SPWebConfigModification in opposite of applying these changes manually is, that changes are applied to each WFE in the farm.

Internally SharePoint is holding a collection of modifications that should be applied to the web.config file. Once a modification failed, this particular instance of SPWebConfigModification may resist within the collection. Therefore you should always clear the collection directly before staging your modifications on the SPWebApplication instance.

public override void FeatureActivated(SPFeatureReceiverProperties properties)  
{
  var webApp = (SPWebApplication)properties.Feature.Parent;
  webApp.WebConfigModifications.Clear();

  var myModification = new SPWebConfigModification("mode", "system.web/customErrors")
    {
      Owner = properties.Feature.DefinitionId.ToString(),
      Sequence = 0,
      Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute,
      Value = "Off"
    };
  webApp.WebConfigModifications.Add(myModification);
  webApp.Update();
}

Happy SharePoint'ing

Comments

comments powered by Disqus