Search code examples
asp.net-coretfstfsbuildmsdeploy

How to transform connection strings in app.config


I am working on the CI/CD pipeline for a quite big project that was created 3 years ago and it is a asp.net core 2.1 (.NET Framework) project. This project store the connection strings in app.config file for EF 6. I was trying to create Web Deploy Package for this project, but VS cannot detect the connection string in app.config, I have tried to create custom Parameters.xml file

<parameter name="OptagEntities-app.config Connection String" description="doesn't matter" defaultvalue="__OptagEntities__" tags="">
      <parameterentry kind="XmlFile" scope="\\app.config$" match="/configuration/connectionStrings/add[@name='OptagEntities']/@connectionString">
</parameterentry>

I have tried to deploy this project to local IIS and I can see that connection string is not updated from the value in SetParameters.xml file. We have on premise TFS server and same flow works for webform project. The different is Web config and this project is using app.config, because asp.net core .NET framework only create web.config when publish. I know I can use appsetting.json to transform the different the ENV, but it require code changes and worsting thing is that this project is referencing another project via nuget that also using a connection string in app.config. Any work around for this?


Solution

  • I use the code blow to change the EF6 connectionstring at runtime, "myConnectionStrings" can load from appsettings.json

    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings["Entities"].ConnectionString = "myConnectionStrings";
    config.Save();
    ConfigurationManager.RefreshSection("connectionStrings");