programing

Microsoft MSBuild 외부에서 Web.Config 변환?

coolbiz 2023. 9. 7. 22:14
반응형

Microsoft MSBuild 외부에서 Web.Config 변환?

마이크로소프트의 XML 문서 변환을 MSBuild 외부에서 web.configs를 준비하는 데 사용할 수 있습니까?저는 MSBuild 엔진을 통해 이를 실행할 필요 없이 PowerShell을 사용하여 이러한 변환을 수행하고자 합니다.Microsoft가 표준 XSLT를 사용했다면 PowerShell에서 쉽게 수행할 수 있을 것입니다.C:\Program Files(x86)를 사용해야 한다고 생각합니다.MSBuild\Microsoft\Visual Studio\v10.0\Web\Microsoft.웹. 퍼블리싱.빌드 엔진이 필요한 tasks.dll.감사해요.

저는 파워쉘에서 마이크로소프트의 XML 문서 변환을 처리하기 위한 작은 기능을 만들었습니다.

마이크로소프트를 복사했습니다.Web.XmlTransform.dll 파일은 Visual Studio 빌드 폴더에서 내 스크립트 경로로 이동하지만 원한다면 원본 폴더에서 참조할 수 있습니다.

function XmlDocTransform($xml, $xdt)
{
    if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
        throw "File not found. $xml";
    }
    if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
        throw "File not found. $xdt";
    }

    $scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
    Add-Type -LiteralPath "$scriptPath\Microsoft.Web.XmlTransform.dll"

    $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
    $xmldoc.PreserveWhitespace = $true
    $xmldoc.Load($xml);

    $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
    if ($transf.Apply($xmldoc) -eq $false)
    {
        throw "Transformation failed."
    }
    $xmldoc.Save($xml);
}

web.release.config를 사용하여 web.config를 변환하는 방법:

XmlDocTransform -xml "Web.config" -xdt "Web.Release.config"

또는 Sayed의 자체 부트스트래핑 Xml Transform 스크립트를 사용할 수 있으며, 이 스크립트를 통해 Microsoft를 가져올 수 있습니다.Xml.Xdt.dll:

https://gist.github.com/sayedihashimi/f1fdc4bfba74d398ec5b

변환 로직은 TransformXml 태스크 자체 내부에 포함되어 있습니다.코드에서 호출하려면 모의 엔진이 있는 MSBuild API를 사용하여 실행해야 합니다.당신이 원한다면 내가 이걸 위한 코드를 좀 가지고 있습니다.

PowerShell을 언급하셨으니 TransformXml 작업을 호출하기 위해 래퍼 MSBuild 파일을 만드는 것이 최선의 방법입니다.PowerShell이 아래에서 실행되도록 구성되어 있기 때문에 이렇게 말합니다.NET 2.0이지만 TransformXml 태스크를 수행하려면 다음이 필요합니다.NET 4.0.더미 MSBuild 파일에서 호출하려면 http://sedodream.com/2010/04/26/ConfigTransformationsOutsideOfWebAppBuilds.aspx, 에서 제 블로그를 확인할 수 있지만 아래 링크에서 샘플도 붙여 넣었습니다.

<Project ToolsVersion="4.0" DefaultTargets="Demo" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <UsingTask TaskName="TransformXml"
             AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>

    <Target Name="Demo">
        <TransformXml Source="app.config"
                      Transform="Transform.xml"
                      Destination="app.prod.config"/>
    </Target>
</Project>

위해서mono 6, 2019에 됨) γ δ (macos, 2019) :, γ δ (macos, 2019) :

<Project DefaultTargets="TransformConfig" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="TransformXml"
    AssemblyFile="$(MSBuildSDKsPath)/Microsoft.NET.Sdk.Publish/tools/net46/Microsoft.NET.Sdk.Publish.Tasks.dll"/>
  <PropertyGroup>
    <TransformSource>Web.config</TransformSource>
    <Transformer>Web.Live.config</Transformer>
    <Destination>Output.Web.config</Destination>
  </PropertyGroup>
  <Target Name="TransformConfig">
    <Message Text="From TransformSource : $(TransformSource)" />
    <Message Text="Using Transform : $(Transformer)" />
    <Message Text="Output : $(Destination)" />
    <Message Text="MSBuildSDKsPath=$(MSBuildSDKsPath)" Condition="'$(MSBuildSDKsPath)' != ''" />
    <TransformXml Source="$(TransformSource)" Transform="$(Transformer)" Destination="$(Destination)"/>
  </Target>
</Project>

당신이 그냥 가지고 뛸 수 있는msbuild또는 공급 매개변수를 다음과 같이 지정합니다.

msbuild /p:TransformSource=... /p:Transformer=...

Michel의 답변을 바탕으로 C# 함수를 작성했는데, 이 함수는 동일합니다.

물론 PowerShell을 사용하여 결과 DLL을 호출할 수도 있지만 실제로는 완전한 프로그램 버전을 찾고 있었습니다. 따라서 다른 사람이 유사한 솔루션을 찾고 있는 경우를 대비하여 여기에 나와 있습니다.

using Microsoft.Web.XmlTransform;

...

public static void TransformConfig(string configFileName, string transformFileName)
{
     var document = new XmlTransformableDocument();
     document.PreserveWhitespace = true;
     document.Load(configFileName);

     var transformation = new XmlTransformation(transformFileName);
     if (!transformation.Apply(document))
     {
         throw new Exception("Transformation Failed");
     }
     document.Save(configFileName);
}

다음 사항을 참조하면 됩니다.

C:\프로그램 파일(x86)\MSBuild\Microsoft\Visual Studio\v11.0\Web\Microsoft.Web.XmlTransform.dll

Microsoft는 XDT를 코드플렉스 http://xdt.codeplex.com 와 NuGet 패키지 https://www.nuget.org/packages/Microsoft.Web.Xdt/ 에 게시했습니다.MSBuild 작업인 TransformXml과 https://www.nuget.org/packages/SlowCheetah.Xdt/1.1.6-beta 을 호출하기 위한 .exe로 NuGet 피그도 만들었습니다.

PowerShell의 경우 https://gist.github.com/sayedihashimi/f1fdc4bfba74d398ec5b 을 사용할 수 있는 자체 부트스트래핑 스크립트를 만들었습니다.

http://sedodream.com/2014/07/22/StopCheckinginBinariesInsteadCreateSelfbootstrappingScripts.aspx 에서 자체 부트스트래핑 스크립트에 대한 자세한 내용을 확인할 수 있습니다.

최신 버전의 파워셸과 함께 작동하고 조금 더 쉽게 하기 위해 스크립트를 업데이트했습니다.

function XmlDocTransform($xml, $xdt)
{
      $scriptpath = $PSScriptRoot + "\"
      $xmlpath = $scriptpath + $xml
      $xdtpath = $scriptpath + $xdt

      if (!($xmlpath) -or !(Test-Path -path ($xmlpath) -PathType Leaf)) {
         throw "Base file not found. $xmlpath";
      }

      if (!($xdtpath) -or !(Test-Path -path ($xdtpath) -PathType Leaf)) {
         throw "Transform file not found. $xdtpath";
      }

      Add-Type -LiteralPath "$PSScriptRoot\Microsoft.Web.XmlTransform.dll"

      $xmldoc = New-Object   Microsoft.Web.XmlTransform.XmlTransformableDocument;
      $xmldoc.PreserveWhitespace = $true
      $xmldoc.Load($xmlpath);

      $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdtpath);
      if ($transf.Apply($xmldoc) -eq $false)
      {
          throw "Transformation failed."
      }
      $xmldoc.Save($xmlpath);

      Write-Host "Transformation succeeded" -ForegroundColor Green
  }

함수를 호출하려면

 XmlDocTransform "App.config" "App.acc.config"

MSDeploy는 패키지를 변환하고 배포할 수 있는 PowerShell 스크립팅 API를 가지고 있으므로 이를 사용해 보십시오.

또한 XML-문서-변환에서 변환을 수행할 코드를 직접 작성할 수 있습니다.

여기 비슷한 일을 한 코드플렉스 프로젝트가 있습니다.XDT 변환 도구

그래서 약간 확장되어 재귀적으로 작동합니다.

    function XmlDocTransform($xml, $xdt)
    {
        if (!$xml -or !(Test-Path -path $xml -PathType Leaf)) {
            throw "File not found. $xml";
        }
        if (!$xdt -or !(Test-Path -path $xdt -PathType Leaf)) {
            throw "File not found. $xdt";
        }
        $scriptPath = (Get-Variable MyInvocation -Scope 1).Value.InvocationName | split-path -parent
        Add-Type -LiteralPath "$scriptPath\Microsoft.Web.XmlTransform.dll"
        $xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
        $xmldoc.PreserveWhitespace = $true
        $xmldoc.Load($xml);
        $transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($xdt);
        if ($transf.Apply($xmldoc) -eq $false)
        {
            throw "Transformation failed."
        }
        $xmldoc.Save($xml);
    }
    function DoConfigTransform($webFolder, $environment)
    {
        $allConfigFiles = Get-ChildItem $webFolder -File -Filter *.config -Recurse
          $transformFiles = $allConfigFiles | Where-Object {$_.Name -like ("*." + $environment + ".config")} | %{$_.fullname}
          ForEach($item in $transformFiles)
          {
            $origFile = $item -replace("$environment.",'')
              XmlDocTransform -xml $origFile -xdt $origFile$item
              #Write-Output ("orig = " + $origFile + ", transform = " + $item)
          }
          cd C:\WebApplications\xxx\xxx\xxx\
          .\PostDeploy.ps1
    }
    DoConfigTransform -webFolder "C:\WebApplications\xxx\xxx\xxx" -environment "xx-xxx-xx"

DoConfigTransform 논리는 다음과 같습니다.

  • 모든 구성 파일을 재귀적으로 찾습니다.
  • 매개 변수로 #전달된 환경의 모든 변환 템플릿 찾기
  • 각 변환 파일에 대해 해당하는 구성을 찾습니다.
  • 그러면 변환을 합니다.
  • 코드는 배포 후 스크립트를 실행하여 원하지 않는 변환 파일을 모두 제거합니다.

저는 원래 게시물을 올린 후에 이 게시물에 왔지만 문제를 해결하는 데 도움이 되었기 때문에 현재 비주얼 스튜디오/msbuild 설치에 동일한 문제가 있는 사람을 위해 솔루션(위 솔루션 기반)을 여기에 넣으려고 생각했습니다.

현재 VS 빌드 시간 변환은 SlowCheetah nugget pkg을 사용하여 수행됩니다.프로젝트에서 이 패키지에 의존할 수 있다면 제가 아래에 설치한 스크립트를 사용하면 설치된 cheetah 버전을 기반으로 필요한 어셈블리를 자동으로 찾고 필요에 따라 변환을 수행할 수 있습니다.

누군가에게 도움이 되길 바랍니다.

param(  
  [ValidateScript({$(Test-Path $_) -eq $true})]
  [string] $NuGetRootPath,

  [ValidateScript({$(Test-Path $_) -eq $true})]
  [string] $BaseFile,

  [ValidateScript({$(Test-Path $_) -eq $true})]
  [string] $TransformFile,

  [string] $TargetPath
)

"[INFO] Creating Custom XML Transform..." | Out-Default   
"[INFO] ==> Source:    $BaseFile" | Out-Default   
"[INFO] ==> Transform: $TransformFile" | Out-Default   
"[INFO] ==> Target:    $TargetPath" | Out-Default   

$cheetahDir = Join-Path $NuGetRootPath *SlowCheetah* | Resolve-Path | Select-Object -Last 1 -ExpandProperty Path
$xformDll = Join-Path $cheetahDir "tools\Microsoft.Web.XmlTransform.dll" | Resolve-Path | Select-Object -ExpandProperty Path
Add-Type -LiteralPath $xformDll

$xmldoc = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
$xmldoc.PreserveWhitespace = $true
$xmldoc.Load($BaseFile);

"[INFO] Running Transform..." | Out-Default
$transf = New-Object Microsoft.Web.XmlTransform.XmlTransformation($TransformFile);
if ($transf.Apply($xmldoc) -eq $false) {
    throw "[ERROR] Transformation failed."
}

$xmldoc.Save($TargetPath);
"[INFO] Transformation Complete..." | Out-Default

언급URL : https://stackoverflow.com/questions/8989737/web-config-transforms-outside-of-microsoft-msbuild

반응형