Search code examples
c#app-configconfig

Automatically load config by hostname in c#


We develop a project on different machines. Each of those machines have their own database connections.

Currently we load the database config from within the app.config using an external file

<connectionStrings configSource="DB.config" />

Now I want to be able to save different files like DB.BobsPC.config and DB.JacksPC.config where BobsPC and JacksPC is the host name of the machine the code is debugged. This config of the correct host should be used automatically.

Something like:

<connectionStrings configSource="DB.[hostname].config" />

Is there a smart way to do this?


Solution

  • You can use the "XML-Document-Transform Syntax" Usually, this syntax ist meant for use within web projects but you can tweak it for usage in all kind of projects.

    You have to modify your project file (e.g. .csproj) by adding/updating the TransformXml-Task. In the example below, the transformation is executed during comilation by appliying the transformation on an App.config. As you can see, the task referes to the $(Configuration) variable, so the transformation commands are stored e.g. in an App.DEBUG.config or App.RELEASE.config. You can change this to any msbuild variable you like. If I remember correctly it was $(COMPUTERNAME) so you have to place your transformation into an App.MyMachineName.config.

    <UsingTask TaskName="TransformXml" 
               AssemblyFile="C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
    <Target Name="AfterBuild">
      <!-- use App.$(COMPUTERNAME).config for specific machine configuration -->
      <TransformXml Source="App.config" 
                    Condition="Exists('App.$(Configuration).config')" 
                    Transform="App.$(Configuration).config" 
                    Destination="$(OutDir)$(AssemblyName).dll.config"/>
    </Target>
    

    A full description is available at a german blog.

    An that`s what you machine specific configuration looks like:

    <?xml version="1.0"?>
    <!-- "App.MyMachineName.config" - File name corresponds to the transformation task  -->
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <connectionStrings>
        <add name="MyDbConnection"
             connectionString="Data Source=MyServer;Initial Catalog=MyDb;" 
             providerName="System.Data.SqlClient"
             xdt:Transform="SetAttributes" 
             xdt:Locator="Match(name)"/>
      </connectionStrings>
    </configuration>
    

    Alternatively, you may use an XSL Syntax