views:

297

answers:

1

Is there a way to read a System.Config connection string in an MSBuild task?

Basically I have my connection string setup in a config file

<add name="MyApp.MyConnectionString" connectionString="..." />

And I would like to reference it in an MSBuild task like so ...

<Target Name="Migrate" DependsOnTargets="Build">
    ...
    <Migrate Connectionstring="$(MyApp.MyConnectionString)" ... />
</Target>
A: 

There's an XMLRead task in the MSBuild Community Tasks Project, that uses xpath to pull out a value.

<XmlRead 
  XPath="/add/@connectionString"
  XmlFileName="app.config">
    <Output TaskParameter="Value" PropertyName="MyConnectionString" />
</XmlRead>
<Message Text="MyConnectionString: $(MyConnectionString)"/>

(note: totally untested)

gregmac
This is no good as it requires me to know what my config file is. I want to read the setting itself so it can be completely agnostic. Users can set their connection strings in a local config file or machine.config. However, I am fairly new to MSBuild. Can I take this to mean I can populate a property from inside a task? So I could write a task that uses System.Configuration to grab the config value and put it in an msbuild property?
jcm
Not really sure what you mean -- why don't you know the name of the file? You can use an ItemGroup to search for files, and then specify that for the XmlFileName property, and it will run on any files it finds (I think there may be a different way to specify the propertyName in this case so it goes into a group instead of a single property value). But yes, you can populate a property, and then use it elsewhere in the build file.
gregmac
I don't know the name of the file name because configuration is being handled properly by System.Configuration. Users may set values in Machine.config, app.config, some file included by app.config, it doesn't matter. All I know is the name of the property.
jcm
Sorry I didn't make the connection that you're talking about a live environment. So long as you can somehow execute, from msbuild, within that context, you should be able to use System.Configuration and read the value. For example, you could have a small app as part of your program, that msbuild can execute, which outputs the config value (or writes it to a temp file). It seems a bit strange to me to need to do this in a build environment, but I'm guessing you need this for running tests or something (I would personally probably use a test config file that is checked into SCM).
gregmac
Yea I think I'm just going to end up writing my own simple task in C# that pulls a value from System.Configuration and populates a property to be used in another task.
jcm