program story

여러 빌드 구성에 대해 다른 app.config를 선택하는 방법

inputbox 2020. 7. 25. 10:53
반응형

여러 빌드 구성에 대해 다른 app.config를 선택하는 방법


MSTest 통합 테스트가 포함 dll 형식 프로젝트 가 있습니다. 내 컴퓨터에서 테스트가 통과하고 CI 서버에서 동일한 결과를 원합니다 (TeamCity 사용). 그러나 app.config의 일부 설정을 조정해야하기 때문에 테스트가 실패합니다. 이것이 CI 서버에 대한 설정을 보유 할 별도의 두 번째 app.config 파일을 갖고 자하는 이유입니다.

그래서 갖고 싶습니다

/ Sln
 / Proj
  app.config (VS에서 필요하다고 생각합니다)
  app.Release.config (독립형 독립 구성 파일 임)

따라서 CI의 빌드 구성에서 릴리스 구성을 선택하면 app.config 대신 app.Release.config 파일을 사용하고 싶습니다.

문제
간단한 .dll 형식 프로젝트에서는 간단하지 않은 것 같습니다. 웹 프로젝트의 경우 웹 구성 변환을 수행 할 수 있습니다. dll 유형 프로젝트에서 이러한 변환을 수행하는 방법을 찾았지만 큰 팬이 아닙니다.

질문
.NET 프로젝트의 빌드 구성 (예 : 디버그, 릴리스 등)에 따라 app.config 파일을 조정하는 표준 방법은 무엇입니까?


SlowCheetah 플러그인을 사용하십시오 . SlowCheetah 사용 방법에 대한 자세한 옵션과 세부 정보는 계속 읽으십시오.

이미 알고 있듯이 라이브러리 유형 (.dll) 프로젝트에 다른 구성 파일을 사용하는 기본적이고 쉬운 방법은 없습니다 . 그 이유는 현재 생각이 "필요하지 않다"는 것입니다! 프레임 워크 개발자는 콘솔, 데스크탑, 웹, 모바일 앱 또는 다른 것 등 실행 파일에 대한 구성이 필요하다고 생각합니다. dll에 대한 구성을 제공하기 시작 하면 구성 지옥 이라고 부를 수 있습니다 . 왜이 변수와 변수에 이상한 값이 나타나는지 더 이상 (쉽게) 이해할 수 없을 것입니다.

"잠깐만"는 - 당신은 말할 수 있습니다 "하지만 난 내 통합 / 단위 테스트이 필요하고, 그것이 도서관!". 그리고 그것은 사실이며 이것이 당신이 할 수있는 일입니다 (하나만 골라 섞지 마십시오) :

1. SlowCheetah-현재 구성 파일을 변환합니다

모든 저수준 XML 파킹 (또는 변환)을 수행하는 Visual Studio 플러그인 인 SlowCheetah 를 설치할 수 있습니다 . 작동 방식 : 간단히

  • SlowCheetah를 설치하고 Visual Studio를 다시 시작하십시오 (Visual Studio> 도구> 확장 및 업데이트 ...> 온라인> Visual Studio Gallery> "Slow Cheetah"검색)
  • 솔루션 구성을 정의하십시오 ( 디버그릴리스 가 기본적으로 있음). 추가 할 수 있습니다 ( 솔루션 탐색기 > 구성 관리자 ... > 활성 솔루션 구성 > 새로 작성 ... 에서 솔루션을 마우스 오른쪽 단추로 클릭) .
  • 필요한 경우 구성 파일 추가
  • 구성 파일을 마우스 오른쪽 버튼으로 클릭하고 변환 추가
    • 그러면 구성 당 하나씩 변환 파일이 생성됩니다.
    • 변환 파일은 인젝터 / 뮤 테이터로 작동하며, 원본 구성 파일에서 필요한 XML 코드를 찾은 다음 줄을 바꾸거나 필요한 값을 변경합니다.

2. .proj 파일로 바이올린-완전히 새로운 구성 파일을 복사 이름 변경

원래 여기 에서 가져 왔습니다 . Visual Studio .proj 파일에 포함 할 수있는 사용자 지정 MSBuild 작업입니다 . 다음 코드를 복사하여 프로젝트 파일에 붙여 넣습니다.

<Target Name="AfterBuild">
    <Delete Files="$(TargetDir)$(TargetFileName).config" />
    <Copy SourceFiles="$(ProjectDir)\Config\App.$(Configuration).config"
          DestinationFiles="$(TargetDir)$(TargetFileName).config" />
</Target>

이제 프로젝트에서 폴더를 만들고 App.Debug.config , App.Release.config 등과 같은 Config새 파일을 추가하십시오 . 이제 구성에 따라 Visual Studio는 폴더 에서 구성 파일을 선택 하여 출력 디렉토리로 복사 이름을 바꿉니다. 따라서 PatternPA.Test.Integration 프로젝트와 디버그 구성을 선택한 경우 빌드 후 출력 폴더에 PatternPA.Test.Integration.dll.config 파일이 있으며 이후 에 복사되어 이름이 변경됩니다.ConfigConfig\App.Debug.config

구성 파일에 남겨 둘 수있는 참고 사항입니다.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

    <!-- This file is copied and renamed by the 'AfterBuild' MSBuild task -->

    <!-- Depending on the configuration the content of projectName.dll.config 
        is fully substituted by the correspondent to build configuration file 
        from the 'Config' directory. -->

</configuration>

Visual Studio에서는 다음과 같은 것을 가질 수 있습니다

프로젝트 구조

3. Visual Studio 외부에서 스크립팅 파일 사용

각 빌드 도구 (예 : NAnt , MSBuild )는 구성에 따라 구성 파일을 변환하는 기능을 제공합니다. 제품을 출시하기 위해 준비하는 방법과 방법에 대해 더 많은 제어가 필요한 빌드 머신에서 솔루션을 빌드 할 때 유용합니다.

예를 들어 웹 게시 dll의 작업을 사용하여 구성 파일을 변환 할 수 있습니다

<UsingTask AssemblyFile="..\tools\build\Microsoft.Web.Publishing.Tasks.dll"
    TaskName="TransformXml"/>

<PropertyGroup>
    <!-- Path to input config file -->  
    <TransformInputFile>path to app.config</TransformInputFile>
    <!-- Path to the transformation file -->    
    <TransformFile>path to app.$(Configuration).config</TransformFile>
    <!-- Path to outptu web config file --> 
    <TransformOutputFile>path to output project.dll.config</TransformOutputFile>
</PropertyGroup>

<Target Name="transform">
    <TransformXml Source="$(TransformInputFile)"
                  Transform="$(TransformFile)"
                  Destination="$(TransformOutputFile)" />
</Target>

다음과 같은 접근법을 시도 할 수 있습니다.

  1. 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 단추로 클릭하고 프로젝트 언로드를 선택하십시오 .
  2. 프로젝트가 언로드됩니다. 프로젝트를 다시 마우스 오른쪽 단추로 클릭하고 <YourProjectName> .csproj 편집을 선택 하십시오 .
  3. Now you can edit the project file inside Visual Studio.
  4. Locate the place in *.csproj file where your application configuration file is included. It will look like:
    <ItemGroup>
        <None Include="App.config"/>
    </ItemGroup>
  1. Replace this lines with following:
    <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
        <None Include="App.Debug.config"/>
    </ItemGroup>

    <ItemGroup Condition=" '$(Configuration)' == 'Release' ">
        <None Include="App.Release.config"/>
    </ItemGroup>

I have not tried this approach to app.config files, but it worked fine with other items of Visual Studio projects. You can customize the build process in almost any way you like. Anyway, let me know the result.


You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.

So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.

An example of usage might be...

<Target Name="BeforeBuild">
    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t       
        $(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />

    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
        $(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>

If you place this in your .csproj file, and you have the following files...

$(ProjectDir)App.Config.Settings.xls

MachineName        ConfigFilePath   SQLServer        

default             App.config      DEVSQL005
Test                App.config      TESTSQL005
UAT                 App.config      UATSQL005
Production          App.config      PRODSQL005
YourLocalMachine    App.config      ./SQLEXPRESS


$(ProjectDir)App.config.template.xml 

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=[%SQLServer%]; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

... then this will be the result...

From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen

.../solutiondir/ConfigGen/Production/App.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=PRODSQL005; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.


Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!


I'm using XmlPreprocess tool for config files manipulation. It is using one mapping file for multiple environments(or multiple build targets in your case). You can edit mapping file by Excel. It is very easy to use.


SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.

However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.

Note: this is more or less a rework of the No. 2 of @oleksii's answer.

This works for .exe and .dll projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
  </Target>

This works for web projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
  </Target>

Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).

Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.

This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:

<Project>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
    <TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>


See if the XDT (web.config) transform engine can help you. Currently it's only natively supported for web projects, but technically there is nothing stopping you from using it in other application types. There are many guides on how to use XDT by manually editing the project files, but I found a plugin that works great: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.


I have solved this topic with the solution I have found here: http://www.blackwasp.co.uk/SwitchConfig.aspx

In short what they state there is: "by adding a post-build event.[...] We need to add the following:

if "Debug"=="$(ConfigurationName)" goto :nocopy
del "$(TargetPath).config"
copy "$(ProjectDir)\Release.config" "$(TargetPath).config"
:nocopy

I have heard good things about SlowCheetah, but was unable to get it to work. I did the following: add am tag to each for a specific configuration.

Ex:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'UAT|AnyCPU'">
    <OutputPath>bin\UAT\</OutputPath>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AppConfig>App.UAT.config</AppConfig>
  </PropertyGroup>

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

참고 URL : https://stackoverflow.com/questions/8082662/how-to-select-different-app-config-for-several-build-configurations

반응형