Adding bindingredirects through SPWebConfigModification

SPWebConfigModification works very well when you want to add or change something in web.config on your MOSS site. This is done in a consistent way and you are ensured that it is applied to both extended web application and also when bringing in a new frontend server in the farm. I will not go into details of how to use SPWebConfigModifications as there at numerous blog entries out there describing this.

However when you want to add an assemblybinding to your web.config file to handle versioning of your assemblies you might run into a problem as the runtime element of the web.config file is placed in another xml-namespace.

Before you go out and do something drastic like adding it manual, it is possible to do it through SPWebConfigModifications, but it requires some special XPath expressions.

Let’s say you wanted to add this entry:

<dependentAssembly>

  <assemblyIdentity name="CustomerAssembly" publicKeyToken="71e9bce111e9429c" culture="neutral" />

  <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />

</dependentAssembly>

You would then need these lines to add the above

SPWebConfigModification mod = new SPWebConfigModification();

mod.Path = "configuration/runtime/*[local-name()='assemblyBinding' and namespace-uri()='urn:schemas-microsoft-com:asm.v1']"; // filtering using the tag local name and namespace-uri

mod.Name = "*[local-name()='dependentAssembly'][*/@name='CustomerAssembly'][*/@publicKeyToken='71e9bce111e9429c'][*/@culture='neutral']";

mod.Value = "<dependentAssembly><assemblyIdentity name='CustomerAssembly' publicKeyToken='71e9bce111e9429c' culture='neutral' /><bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' /></dependentAssembly>";

mod.Owner = "My Owner";

mod.Sequence = 0;

mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

 

webApp.WebConfigModifications.Add(mod);

webApp.Update();

           

SPWebService.ContentService.ApplyWebConfigModifications();

This will also make it possible to remove the configuration again. Happy coding!