16

我在 Windows 7 上使用 VisualStudio Ultimate 2012(更新 1)。我可以让我的 T4 模板通过以下方式生成文件: 右键单击 [tt 文件] | 运行自定义工具。效果很好!(对我来说是的)。如果我运行菜单命令,它也可以工作:Build | 转换所有 T4 模板。但我想要自动化!当我尝试在每次构建时生成生成的代码文件时遇到问题——这是我的目标。
我看了这个: Visual Studio 中的 T4 转换和构建顺序

这不是我想要的。它讨论了使用预构建构建事件。我希望它成为构建的一部分。

还有这个: 有没有办法让 Visual Studio 在成功构建时运行“转换所有模板”?

这也不是我想要的。它讨论了使用构建后事件。

然后我发现了这个: 了解 T4:MSBuild 集成

来自Oleg Sych 的博客

完美的!这就是我要的。尽管他的博客讨论了 VS2010,但我已在适用的情况下将其应用于 VS2012。

我浏览了他实现这一点的每一个步骤。我安装了Visual Studio SDK 2012 & Visual Studio Visualization and Modeling SDK (2012)

我开始使用 Tangible T4 插件,但认为有问题,我使用了 Oleg 的 T4 Toolbox Beta。可悲的是,我似乎得到了相同的结果:构建错误。

我按照他在他的网站上的指示重新阅读了所有步骤和部分。我已经研究了几天,现在我在这里的第一篇文章。我被困住了。谢谢你看...

回顾一下:当我在 Visual Studio 2012 中构建或从命令行运行 msbuild 时出现错误(但当我运行自定义工具或使用手动转换所有 T4 模板时再次出现错误- 两者都可以正常工作)。

这是我的 t4template 调用s_code.tt

<#@ template  debug="true" hostSpecific="true" language="C#" #>
<#@ output extension=".js" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="EnvDTE80" #>
<#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="Microsoft.VisualStudio.Shell.Interop" #>


<#
    IServiceProvider serviceProvider = (IServiceProvider)Host;
    EnvDTE.DTE dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
    var configName = dte.Solution.SolutionBuild.ActiveConfiguration.Name;
    string filename = this.Host.ResolvePath("s_code_source.txt");
    string[] lines = File.ReadAllLines(filename);
    bool isAccountFound = false;
    int linecount = lines.Length;
    int currentline = 0;
    for (int i=0;i<linecount;i++)
    {
        if (Contains_S_Account(lines[i]))
        {
            if (configName.ToUpper() == "DEBUG")
            {
                    WriteLine("var s_account = \"macudev2\"");
            }
            else if (configName.ToUpper() == "RELEASE")
             {
                   WriteLine("var s_account = \"macudev\"");
             }
            
            currentline = i;
            isAccountFound = true;
        }
        else
        {
            WriteLine(lines[i]);
        }
    }
    for (int i=currentline;i<linecount;i++)
    {
        WriteLine(lines[i]);
    }


#>

<#+
private bool Contains_S_Account(string line)
{
    if (line.ToLower().Contains("var s_account"))
    {
        return true;
    }
    else
    {
        return false;
    }
}
#>

这是我的.csproj文件:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{0A44E136-F4A4-4B31-95DD-2C8A79FDFAF4}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Macu.Content</RootNamespace>
    <AssemblyName>Macu.Content</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <UseIISExpress>true</UseIISExpress>
    <IISExpressSSLPort />
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <TargetFrameworkProfile />
    <TransformOnBuild>True</TransformOnBuild>
    <IncludeFolders>$(MSBuildProjectDirectory)\Include</IncludeFolders>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="EnvDTE, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      <EmbedInteropTypes>True</EmbedInteropTypes>
    </Reference>
    <Reference Include="envdte80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      <EmbedInteropTypes>True</EmbedInteropTypes>
    </Reference>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="Microsoft.VisualStudio.Shell.Interop.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <EmbedInteropTypes>True</EmbedInteropTypes>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.TextTemplating.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
    <Reference Include="System" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="shared\script\s_code.js">
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
      <DependentUpon>s_code.tt</DependentUpon>
    </Content>
    <Content Include="shared\script\s_code_source.txt" />
    <Content Include="Web.config" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="shared\script\s_code.tt">
      <Generator>TextTemplatingFileGenerator</Generator>
      <LastGenOutput>s_code.js</LastGenOutput>
      <Parameters>
        &lt;%3fxml version="1.0" encoding="utf-16"%3f&gt;
        &lt;ArrayOfParameterStorage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" /&gt;
      </Parameters>
    </Content>
    <None Include="Properties\PublishProfiles\Local.pubxml" />
    <None Include="Web.Debug.config">
      <DependentUpon>Web.config</DependentUpon>
    </None>
    <None Include="Web.Release.config">
      <DependentUpon>Web.config</DependentUpon>
    </None>
  </ItemGroup>
  <ItemGroup>
    <T4ReferencePath Include="$(VsInstallDir)PublicAssemblies\" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="shared\images\" />
  </ItemGroup>
  <ItemGroup />
  <ItemGroup>
    <Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" />
  </ItemGroup>
  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\TextTemplating\Microsoft.TextTemplating.targets" />
  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>True</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>30698</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl>http://localhost:50012/</IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>False</UseCustomServer>
          <CustomServerUrl>
          </CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
  <PropertyGroup>
    <PreBuildEvent>
    </PreBuildEvent>
  </PropertyGroup>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

MSBuild这是我从命令行运行后看到的错误:

C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Conten
t>msbuild macu.content.csproj /t:TransformAll
Microsoft (R) Build Engine version 4.0.30319.17929
[Microsoft .NET Framework, version 4.0.30319.17929]
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 1/17/2013 2:16:59 PM.
Project "C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\M
acu.Content\macu.content.csproj" on node 1 (TransformAll target(s)).
ExecuteTransformations:
  Performing incremental T4 transformation
  Calculating whether transformed output is out of date...
  Transforming template shared\script\s_code.tt...
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Micr
osoft.TextTemplating.targets(396,5): warning : Compiling transformation: The va
riable 'isAccountFound' is assigned but its value is never used. Line=24, Colum
n=7 [C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.
Content\macu.content.csproj]
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Micr
osoft.TextTemplating.targets(396,5): error : Running transformation: System.Nul
lReferenceException: Object reference not set to an instance of an object.\r [C
:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Conten
t\macu.content.csproj]
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Micr
osoft.TextTemplating.targets(396,5): error :    at Microsoft.VisualStudio.TextT
emplating7D294BC599798219F70D124BB1976BCDFB50B07280E2004F9365EC71A617D68D059E43
6CBD1AD344727611A619EE41F939B60372B3E16565CA2D4E4B40FBC5C7.GeneratedTextTransfo
rmation.TransformText() in c:\Users\[myUserName]\Documents\Visual Studio 2012\Proje
cts\Macu.Content\Macu.Content\shared\script\s_code.tt:line 21. Line=21, Column=
0 [C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Co
ntent\macu.content.csproj]
Done Building Project "C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\
Macu.Content\Macu.Content\macu.content.csproj" (TransformAll target(s)) -- FAIL
ED.


Build FAILED.

"C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Cont
ent\macu.content.csproj" (TransformAll target) (1) ->
(ExecuteTransformations target) ->
  C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Mi
crosoft.TextTemplating.targets(396,5): warning : Compiling transformation: The
variable 'isAccountFound' is assigned but its value is never used. Line=24, Col
umn=7 [C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Mac
u.Content\macu.content.csproj]


"C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Cont
ent\macu.content.csproj" (TransformAll target) (1) ->
(ExecuteTransformations target) ->
  C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Mi
crosoft.TextTemplating.targets(396,5): error : Running transformation: System.N
ullReferenceException: Object reference not set to an instance of an object.\r
[C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Cont
ent\macu.content.csproj]
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\TextTemplating\Micr
osoft.TextTemplating.targets(396,5): error :    at Microsoft.VisualStudio.TextT
emplating7D294BC599798219F70D124BB1976BCDFB50B07280E2004F9365EC71A617D68D059E43
6CBD1AD344727611A619EE41F939B60372B3E16565CA2D4E4B40FBC5C7.GeneratedTextTransfo
rmation.TransformText() in c:\Users\[myUserName]\Documents\Visual Studio 2012\Proje
cts\Macu.Content\Macu.Content\shared\script\s_code.tt:line 21. Line=21, Column=
0 [C:\Users\[myUserName]\Documents\Visual Studio 2012\Projects\Macu.Content\Macu.Co
ntent\macu.content.csproj]

    1 Warning(s)
    1 Error(s)

Time Elapsed 00:00:01.04

你能看到我正在做的任何导致错误的事情吗?你知道如何修复它,以便我可以使用 msbuild 而不会遇到这个错误吗?

4

4 回答 4

22

恐怕您无法在构建时成功运行模板,这些模板利用 Host 变量来获取像 DTE 这样的 IDE 服务,因为 msbuild T4 主机被设计为既可以从命令行工作,也可以在内置IDE,因此,不会将全局服务提供者或 DTE 暴露给模板。简单的命令行主机 texttransform.exe 也是如此。

于 2013-01-19T00:39:45.517 回答
3

我们的一位客户遇到了完全相同的问题,GarethJ 是正确的,这不能开箱即用。

但是,您可以编写自己的“TextTransform.exe”工具,该工具很容易为模板提供 Visual Studio 自动化 API。您需要做的就是实现ITextTemplatingEngineHostIServiceProvider接口,并在请求时返回DTE接口的实例。

也就是说:我们写了一篇关于这个场景的博客文章,并发布了工具 = 源代码

不过请注意:您需要在构建服务器上安装正确许可的 Visual Studio 才能使其正常工作。

马蒂德@AIT

于 2015-08-11T06:11:50.267 回答
2

有形 T4 编辑器中有一个名为“构建时转换”的专业功能,它允许您在解决方案资源管理器属性网格中将模板标记为“构建时转换”。这将在您每次在 Visual Studio(而不是构建服务器)中构建时转换模板。在那里,您的模板还可以访问 EnvDTE 和其他 Visual Studio 变量。请参阅:http ://t4-editor.tangible-engineering.com/blog/transforming-t4-templates-on-build.html

于 2013-03-13T10:43:54.777 回答
1

我最近在构建过程中遇到了这个问题(不使用DTE)。我通过确保我的 PC 上只有 1 个 texttransform.exe 来解决它。出于某种原因,IDE 使用的是最新版本texttransform.exemsbuild旧版本。

于 2015-01-06T08:26:13.540 回答