2

I'm currently authoring a new NuGet package, but I can't get the app.config.install.xdt file right (which is the xml file that transforms app.config to suit the installed package).

The problem is inserting a <configSections> section in app.config as the first child - but only in case it is missing!

It MUST be the first child, or the application will fail with an exception (Microsoft enforcement).

If I just use the regular “InsertIfMissing” transform, the insertion takes place after any existing children, so that seems a no-go.

What can I do to solve my problem?

Martin Christiansen
  • 1,037
  • 3
  • 9
  • 28

3 Answers3

4

I've had exactly the same problem and solved it this way:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />
<configSections xdt:Locator="XPath(/configuration/configSections[last()])">
     do_your_stuff_with_sections_here...
</configSections>
<configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />

The first line unconditionally creates the node as first child:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />

The second line makes sure all your edits are done to the last configSections node, which is de correct node if it already existed…

<configSections xdt:Locator="XPath(/configuration/configSections[last()])">

After the transforms you do in de configSections block, you enter a command that removes all empty configSections nodes… (last line)

<configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />
0

How to insert as first child in app.config

You can utilize the attribute xdt:Transform="InsertBefore" to insert a new element in the section but before the any other element, like:

<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />

Certificate: XDT Transform: InsertBefore - Locator Condition is ignored

And see How to use XDT in NuGet - Examples and Facts for some more details.

Hope this helps.

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
  • Not really. The problem is that the section is inserted unconditionally. This means, if I remove the nuget package and reinstalls it, I am left with *two* -children and not only one. There must be only one, and that one must always be the first child. – Martin Christiansen Aug 14 '18 at 12:20
-1

I was looking for the solution as well...

<configSections xdt:Transform="Remove" />
<configSections xdt:Transform="InsertBefore(/configuration/*[1])">
Zoe
  • 27,060
  • 21
  • 118
  • 148
pkd3vv
  • 1