您如何访问T4文本模板中的发布信息? [英] How do you access publish information in a T4 Text Template?

查看:52
本文介绍了您如何访问T4文本模板中的发布信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何访问要在T4文本模板中使用的发布信息?

How do you access publish information for use in a T4 Text Template?

例如,我想创建一个文本模板,该模板生成一个XML文件,该文件将与ASP.Net Core MVC网站一起发布.生成的文件应该有所不同,具体取决于我在哪里发布网站;生产或测试环境.因此,我在.tt文件中会有这样的内容,以便在生成它时,它会根据所选的发布配置文件或发布路径而有所不同:

For example, I want to create a text template that generates an xml file that will be published with an ASP.Net Core MVC website. The generated file should be different depending on where I publish the website; Production or Test environment. So I would have something like this in the .tt file such that when it is generated it varies depending on the selected publish profile or the publish path:

<#
 if(publishing to A)
{
#>
   text output specific to A
<#
}
else if(publishing to B)
{
#>
   text output specific to B
<#
}
#>

我刚刚发现了这一点,它看起来很有希望: using-msbuild-properties -in-t4-templates

I just found this and it looks promising: using-msbuild-properties-in-t4-templates

推荐答案

MSDN文档帮助它在VS2017中工作.

This MSDN blog by Jeremy Kuhne and this blog by Thomas Levesque and several other links such as this MSDN doc helped get it working in VS2017.

我不必在.csproj文件的开头添加任何内容,因为VS2017默认情况下已包含这些文件.

I did not have to add anything to the beginning of the .csproj file since VS2017 has the files already included by default.

在Visual Studio 2017中,``文本模板转换''组件为 作为Visual Studio扩展的一部分自动安装 开发工作量.您也可以从个人安装 Visual Studio Installer的组件"选项卡,在代码"工具下 类别.从个人安装Modeling SDK组件 组件标签.

In Visual Studio 2017, the Text Template Transformation component is automatically installed as part of the Visual Studio extension devlopment workload. You can also install it from the Individual components tab of Visual Studio Installer, under the Code tools category. Install the Modeling SDK component from the Individual components tab.

我最终在文件末尾进行了以下.csproj更改.这将允许在T4模板中使用所选的构建配置,并导致在每个构建上重新生成所有模板:

I ended up with the following .csproj changes at the end of the file. This will allow the selected build configuration to be availed in the T4 template and cause all templates to be regenerated on each build:

  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <!-- Run the Transform task at the start of every build -->
    <TransformOnBuild>true</TransformOnBuild>
    <!-- -->
    <OverwriteReadOnlyOutputFiles>true</OverwriteReadOnlyOutputFiles>
    <!-- Transform every template every time -->
    <TransformOutOfDateOnly>false</TransformOutOfDateOnly>
  </PropertyGroup>

  <!-- add AFTER import for $(MSBuildToolsPath)\Microsoft.CSharp.targets -->
  <Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

    <ItemGroup>
    <T4ParameterValues Include="BuildConfiguration">
        <Value>$(Configuration)</Value>
        <Visible>False</Visible>
    </T4ParameterValues>
  </ItemGroup>

    <Target Name="CreateT4ItemListsForMSBuildCustomTool" BeforeTargets="CreateT4ItemLists" AfterTargets="SelectItemsForTransform">
    <ItemGroup>
        <T4Transform Include="@(CreateT4ItemListsInputs)" Condition="'%(CreateT4ItemListsInputs.Generator)' == 'MSBuild:TransformAll'" />
    </ItemGroup>
  </Target>

这是csproj文件顶部的内容,但可以通过VS2017进行配置.关键点是名为Development的自定义构建配置和DEVELOPMENT的定义常量:

This is what is at the top of the csproj file but it can be configured through VS2017. The key points are the custom build configuration named Development and the defined constant of DEVELOPMENT:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <Configurations>Debug;Release;Development</Configurations>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Development|AnyCPU'">
    <DebugType>none</DebugType>
    <DefineConstants>TRACE;DEVELOPMENT</DefineConstants>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>full</DebugType>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DebugType>none</DebugType>
    <DefineConstants>TRACE;RELEASE</DefineConstants>
  </PropertyGroup>

这在T4模板中显示了如何访问新的BuildConfiguration参数:

This in the T4 Template to show how to access the new BuildConfiguration parameter:

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ assembly name="EnvDTE" #>
<#  
    //Build time.
    string configName = Host.ResolveParameterValue("-", "-", "BuildConfiguration");
    if (string.IsNullOrWhiteSpace(configName))
    {
        try
        {
            //Design time.
            var serviceProvider = (IServiceProvider)Host;
            EnvDTE.DTE dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
            configName = dte.Solution.SolutionBuild.ActiveConfiguration.Name;
        }
        catch(Exception ex)
        {
            configName = ex.Message;
        }
    }
#>
<#=configName#>

.tt文件上的以下属性设置:

The following property settings on the .tt file:

Build Action: None
Copy to Output Directory: Do Not Copy
Custom Tool: MSBuild:TransformAll

和一个名为"Development"的自定义构建配置. T4模板中的代码将选择调试",发布"和开发".开发构建配置是发行配置的副本.该项目的条件编译符号为"DEVELOPMENT",因此以下代码在Program.cs中起作用,以将环境强制为开发"模式.可以在项目属性">构建">常规"下设置符号.通过开发"构建配置,可以将发布配置文件设置为发布到测试服务器URL.

And a custom build configuration named "Development". The code in the T4 template will pick up "Debug", "Release" and "Development". The Development build configuration is a copy of the Release configuration. The project has a Conditional Compilation Symbol of "DEVELOPMENT" so that the following code works in Program.cs to force the environment into Development mode. The Symbol can be set under Project Properties > Build > General. The publish profile is set to publish to the test server URL with the Development build configuration.

    public static void Main(string[] args)
    {
        //https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
            string mode = "";

#if DEVELOPMENT
            mode  = "DEVELOPMENT";
#elif DEBUG
            mode = "DEBUG";
#elif RELEASE
             mode = "RELEASE";
#endif

            switch (mode.ToUpper())
            {
                case "DEVELOPMENT":
                //Programmatically force the application to use the Development environment.
                    CreateWebHostBuilder(args).UseEnvironment("Development").Build().Run();
                    break;
                default:
                    CreateWebHostBuilder(args).Build().Run();
                    break;
            }
    }

这篇关于您如何访问T4文本模板中的发布信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆