Thursday 17 July 2008

Master the order of WebConfigModifications

There are plenty of blogs describing WebConfigModifications so I'm just going to stress what I feel are the two most important properties on the WebConfigModifications class.

The name and the path.

There are plenty of descriptions of these properties but the most important thing to note is that when combined they form the xpath used to locate the node on which to operate.

Therefore, the following 2 examples have the same effect.



This is because when the name and path attributes are combined they result in the same xpath.

configuration/system.web/httpHandlers/add[@verb='*' and @path='*.asmx']

The reason I am stressing this so much is that I've noticed lots of complaints about how the sequence attribute does not appear to affect the order in which the modifications are applied. This is because the sequence attribute is only taken into account when the names of the modfications are the same. This isn't much use. This means that if I try to insert the following lines into the web.config

<clear />
<add verb="*" path="*.asmx" />
it would always appear

<add verb="*" path="*.asmx" />
<clear />
because alphabetically the names are

add[verb='*' and path='*.asmx']
clear
Because the names are different the sequence would be ignored and the modifications would be applied alphabetically. Therefore adds would come before clears and removes would be last.

That sucks!! But help is at hand. Now that we now the name attribute just forms part of the xpath to locate the element in the web.config file we can use this to our advantage.

The earlier examples formed the xpath

configuration/system.web/httpHandlers/add[@verb='*' and @path='*.asmx']

Well lets alter this example (or will we). If we add a condition to httpHandlers but make sure it always equates to true, the xpath would return the same node but the name used in the WebConfigModification construct would be slightly different.

configuration/system.web/httpHandlers[1=1]/add[@verb='*' and @path='*.asmx']

The condition always returns true and will be ignored but lets look at how this changes the code.



The names are now (in alphabetic order)

httpHandlers[1=1]/clear
httpHandlers[2=2]/add[@verb='*' and @path='*.asmx']

and a therefore will be applied as wanted/expected.

<clear />
<add verb="*" path="*.asmx" />