[visual-studio] Visual Studio에서 웹 프로젝트가 아닌 프로젝트에 대한 App.Config 변환?

Visual Studio 2010 웹 기반 응용 프로그램에는 다양한 환경에 대해 여러 구성 파일을 유지 관리 할 수있는 구성 변환 기능이 있습니다. 그러나 Windows Services / WinForms 또는 콘솔 응용 프로그램의 App.Config 파일에는 동일한 기능을 사용할 수 없습니다.

여기에 제안 된 해결 방법이 있습니다 : App.Config에 XDT 매직 적용 .

그러나 간단하지 않으며 여러 단계가 필요합니다. app.config 파일에 대해 더 쉬운 방법이 있습니까?



답변

이제이 기사에서 처리 한 Visual Studio AddIn에서 작동합니다. 이제 XML 구성 파일에 대해 일반화 된 SlowCheetah-Web.config 변환 구문이 있습니다 .

web.config를 마우스 오른쪽 단추로 클릭하고 “구성 변환 추가”를 클릭하십시오. 이렇게하면 web.debug.config와 web.release.config가 나타납니다. 이름이 구성 프로파일과 일치하는 한 원하는 경우 web.whatever.config를 만들 수 있습니다. 이러한 파일은 web.config의 전체 사본이 아니라 원하는 변경 사항 일뿐입니다.

XSLT를 사용하여 web.config를 변환하고 싶다고 생각할 수도 있지만, 직관적으로 옳다고 느끼지만 실제로는 매우 장황합니다.

XSLT를 사용하는 것과 XML Document Transform 구문 / 네임 스페이스를 사용하는 것과 같은 두 가지 변환이 있습니다. 모든 작업과 마찬가지로 XSLT에는 여러 가지 방법이 있지만 일반적인 아이디어를 얻습니다. XSLT는 일반화 된 트리 변환 언어이며이 배포 언어는 일반적인 시나리오의 특정 하위 집합에 최적화되어 있습니다. 그러나 멋진 부분은 각 XDT 변환이 .NET 플러그인이므로 자신만의 것을 만들 수 있다는 것입니다.

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/configuration/appSettings">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
    <xsl:element name="add">
      <xsl:attribute name="key">NewSetting</xsl:attribute>
      <xsl:attribute name="value">New Setting Value</xsl:attribute>
    </xsl:element>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

또는 배포 변환을 통해 동일한 내용 :

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
   <appSettings>
      <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
   </appSettings>
</configuration>

답변

나는 여러 가지 해결책을 시도했으며 여기 내가 개인적으로 찾은 가장 간단한 것입니다.
댄은 그 의견에 지적 원래의 게시물 에 속한다 올렉 Sych감사, 올렉!

지침은 다음과 같습니다.

1. 각 구성에 대한 XML 파일을 프로젝트에 추가하십시오.

일반적으로 구성 DebugRelease구성이 가능하므로 파일 이름 App.Debug.configApp.Release.config. 내 프로젝트에서 각 종류의 환경에 대한 구성을 만들었으므로 실험 해 볼 수 있습니다.

2. 프로젝트를 언로드하고 편집을 위해 .csproj 파일을 엽니 다

Visual Studio를 사용하면 편집기에서 .csproj 파일을 바로 편집 할 수 있습니다 . 먼저 프로젝트를 언로드하면됩니다. 그런 다음 마우스 오른쪽 단추로 클릭하고 <ProjectName> .csproj 편집을 선택 하십시오 .

3. App. *. config 파일을 기본 App.config에 바인딩

모두 App.configApp.*.config참조 가 포함 된 프로젝트 파일 섹션을 찾으십시오 . 빌드 작업이 다음과 None같이 설정되어 있습니다 .

<None Include="App.config" />
<None Include="App.Debug.config" />
<None Include="App.Release.config" />

먼저 모든 빌드 작업을로 설정하십시오 Content.
다음으로 모든 구성 관련 파일을 기본 파일에 종속되게 하여 App.configVisual Studio가 디자이너 및 코드 숨김 파일처럼 그룹화합니다.

위의 XML을 아래의 것으로 바꾸십시오.

<Content Include="App.config" />
<Content Include="App.Debug.config" >
  <DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config" >
  <DependentUpon>App.config</DependentUpon>
</Content>

4. 변형 마법 활성화 ( VS2017 이전의 Visual Studio 버전에만 필요 )

파일 끝에서

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

그리고 마지막 전에

</Project>

다음 XML을 삽입하십시오.

  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="CoreCompile" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!-- Force build process to use the transformed configuration file from now on. -->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="app.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>

이제 프로젝트를 다시로드하고 빌드하고 App.config변형을 즐길 수 있습니다 !

참고로

App.*.config파일이 다음과 같이 올바르게 설정되어 있는지 확인하십시오 .

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
     <!--magic transformations here-->
</configuration>


답변

내가 찾은 또 다른 솔루션은 변환을 사용하지 않고 app.Release.config와 같은 별도의 구성 파일 만 갖는 것입니다. 그런 다음이 줄을 csproj 파일에 추가하십시오.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <AppConfig>App.Release.config</AppConfig>
  </PropertyGroup>

이는 올바른 myprogram.exe.config 파일을 생성 할뿐만 아니라 Visual Studio에서 설치 및 배포 프로젝트를 사용하여 MSI를 생성하는 경우 패키징 할 때 배포 프로젝트가 올바른 구성 파일을 사용하도록합니다.


답변

내 경험상 환경에 맞게 만들어야하는 것은 연결 문자열, 설정 및 종종 smpt 설정과 같은 것입니다. 구성 시스템은 이러한 것들을 별도의 파일로 지정할 수 있습니다. 따라서 app.config / web.config에서 이것을 사용할 수 있습니다.

 <appSettings configSource="appsettings.config" />
 <connectionStrings configSource="connection.config" />
 <system.net>
    <mailSettings>
       <smtp configSource="smtp.config"/>
    </mailSettings>
 </system.net>

내가 일반적으로하는 것은 이러한 구성 관련 섹션을 별도의 파일에 ConfigFiles라는 하위 폴더에 넣는 것입니다 (솔루션 루트 또는 프로젝트 수준에 따라 다름). 구성 당 파일 (예 : smtp.config.Debug 및 smtp.config.Release)을 정의합니다.

그런 다음 사전 빌드 이벤트를 다음과 같이 정의 할 수 있습니다.

copy $(ProjectDir)ConfigFiles\smtp.config.$(ConfigurationName) $(TargetDir)smtp.config

팀 개발시 컨벤션에 % COMPUTERNAME % 및 / 또는 % USERNAME %을 (를) 포함하여이 문제를 더 조정할 수 있습니다.

물론 이는 대상 파일 (x.config)이 소스 제어에 생성되지 않아야 함을 의미합니다 (생성되기 때문에). 여전히 프로젝트 파일에 추가하고 출력 유형 속성을 ‘항상 복사’또는 ‘최신 경우 복사’로 설정해야합니다.

간단하고 확장 가능하며 모든 유형의 Visual Studio 프로젝트 (콘솔, winforms, wpf, 웹)에서 작동합니다.


답변

이 질문에서 Oleg 와 다른 사람들에게 영감을 받아 https://stackoverflow.com/a/5109530/2286801 솔루션을 한 단계 더 발전시켜 다음을 가능하게했습니다.

  • ClickOnce와 함께 작동
  • VS 2010의 설치 및 배포 프로젝트와 함께 작동
  • VS2010, 2013, 2015에서 작동합니다 (2012도 테스트하지는 않았지만 작동하지는 않습니다).
  • 팀 빌드와 함께 작동합니다. (A) Visual Studio 또는 B를 설치해야합니다. Microsoft.Web.Publishing.targets 및 Microsoft.Web.Publishing.Tasks.dll)

이 솔루션은 MSBuild 프로세스에서 app.config를 처음 참조하기 전에 app.config 변환을 수행하여 작동합니다. 여러 프로젝트에서보다 쉽게 ​​관리 할 수 ​​있도록 외부 대상 파일을 사용합니다.

명령:

다른 솔루션과 비슷한 단계. 나는 똑같은 것을 인용하고 완벽하고 쉬운 비교를 위해 그것을 포함시켰다.

0. AppConfigTransformation.targets라는 새 파일을 프로젝트에 추가하십시오.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- Transform the app config per project configuration.-->
  <PropertyGroup>
    <!-- This ensures compatibility across multiple versions of Visual Studio when using a solution file.
         However, when using MSBuild directly you may need to override this property to 11.0 or 12.0
         accordingly as part of the MSBuild script, ie /p:VisualStudioVersion=11.0;
         See http://blogs.msdn.com/b/webdev/archive/2012/08/22/visual-studio-project-compatability-and-visualstudioversion.aspx -->
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  </PropertyGroup>

  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.targets" />

  <Target Name="SetTransformAppConfigDestination" BeforeTargets="PrepareForBuild"
          Condition="exists('app.$(Configuration).config')">
    <PropertyGroup>
      <!-- Force build process to use the transformed configuration file from now on. -->
      <AppConfig>$(IntermediateOutputPath)$(TargetFileName).config</AppConfig>
    </PropertyGroup>
    <Message Text="AppConfig transformation destination: = $(AppConfig)" />
  </Target>

  <!-- Transform the app.config after the prepare for build completes. -->
  <Target Name="TransformAppConfig" AfterTargets="PrepareForBuild" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(AppConfig)" Transform="app.$(Configuration).config" />
  </Target>

</Project>

1. 각 구성에 대한 XML 파일을 프로젝트에 추가하십시오.

일반적으로 디버그 및 릴리스 구성이 있으므로 파일 이름을 App.Debug.config 및 App.Release.config로 지정하십시오. 내 프로젝트에서 각 종류의 환경에 대한 구성을 만들었으므로 실험 해 볼 수 있습니다.

2. 프로젝트를 언로드하고 편집을 위해 .csproj 파일을 엽니 다

Visual Studio를 사용하면 편집기에서 바로 .csproj를 편집 할 수 있습니다. 먼저 프로젝트를 언로드하면됩니다. 그런 다음 마우스 오른쪽 버튼으로 클릭하고 .csproj 편집을 선택하십시오.

3. App. *. config 파일을 기본 App.config에 바인딩

모든 App.config 및 App. *. config 참조가 포함 된 프로젝트 파일 섹션을 찾아 다음과 같이 바꾸십시오. 콘텐츠 대신 없음을 사용하는 것을 알 수 있습니다.

<ItemGroup>
  <None Include="app.config"/>
  <None Include="app.Production.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
  <None Include="app.QA.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
  <None Include="app.Development.config">
    <DependentUpon>app.config</DependentUpon>
  </None>
</ItemGroup>

4. 변형 마법 활성화

파일 끝에서

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

그리고 마지막 전에

</Project>

다음 XML을 삽입하십시오.

<Import Project="AppConfigTransformation.targets" />

끝난!


답변

구성마다 별도의 구성 파일 (예 : app.Debug.config, app.Release.config)을 사용한 다음 프로젝트 파일에서 구성 변수를 사용할 수 있습니다.

<PropertyGroup>
    <AppConfig>App.$(Configuration).config</AppConfig>
</PropertyGroup>

그러면 빌드하는 구성에 따라 올바른 ProjectName.exe.config 파일이 생성됩니다.


답변

웹 응용 프로그램 프로젝트 구성 변환 과 같은 app.config 변환을 자동화하는 멋진 확장 기능을 작성했습니다.

이 확장의 가장 큰 장점은 모든 빌드 시스템에 확장을 설치할 필요가 없다는 것입니다