Visual studio 2010 如何将命令行代码生成器添加到Visual Studio?

Visual studio 2010 如何将命令行代码生成器添加到Visual Studio?,visual-studio-2010,command-line,msbuild,code-generation,Visual Studio 2010,Command Line,Msbuild,Code Generation,我正在从事一个项目,该项目使用基于文本的描述,使用命令行工具生成代码生成C#类。我们也将开始对javascript使用这些描述 目前,这些类是生成的,然后签入,但是,我希望能够使代码自动生成,以便将任何更改传播到两个版本 手动运行的步骤是: servicegen.exe -i:MyService.txt -o:MyService.cs 生成时,我希望MSBuild/VS首先生成CS文件,然后编译它。通过修改csproj,或者使用带有Exec,dependentupen和AutoGen的MSBu

我正在从事一个项目,该项目使用基于文本的描述,使用命令行工具生成代码生成C#类。我们也将开始对javascript使用这些描述

目前,这些类是生成的,然后签入,但是,我希望能够使代码自动生成,以便将任何更改传播到两个版本

手动运行的步骤是:

servicegen.exe -i:MyService.txt -o:MyService.cs

生成时,我希望MSBuild/VS首先生成CS文件,然后编译它。通过修改
csproj
,或者使用带有
Exec
dependentupen
AutoGen
的MSBuild任务,可以实现这一点

通常我建议在预构建事件中放置一个预构建命令,但由于您的命令行工具将创建编译所需的C#类,因此这应该在.csproj文件中完成。这是因为MSBuild在整个进程中调用Prebuild之前和调用PreBuildEvent之间查找需要编译的文件(您可以在MSBuild使用的Microsoft.Common.targets文件中看到此流)

从BeforeBuild目标中调用Exec任务以生成文件:

<Target Name="BeforeBuild">
  <Exec Command="servicegen.exe -i:MyService.txt -o:MyService.cs" />
</Target>

有关为Exec任务指定不同选项的更多详细信息,请参阅MSDN文档。

Antlr有一个可用于将生成的代码添加到项目中的。这样做的优点是显示嵌套在源文件下生成的文件,尽管添加起来比较复杂

您需要添加一个包含要从中生成的文件的项目组,例如:

<ItemGroup>
  <ServiceDescription Include="MyService.txt"/>
</ItemGroup>

然后将要生成的cs文件添加到包含其余源代码的ItemGroup中

<ItemGroup>
  ...
  <Compile Include="Program.cs" />
  <Compile Include="Properties\AssemblyInfo.cs" />
  ...etc..
  <Compile Include="MyService.txt.cs">
    <AutoGen>True</AutoGen>
    <DesignTime>True</DesignTime>
    <DependentUpon>MyService.txt</DependentUpon>  <!--note: this should be the file name of the source file, not the path-->      
  </Compile>
</ItemGroup>      

...
等
真的
真的
MyService.txt
然后最后添加构建目标以执行代码生成(使用%为ItemGroup中的每个项执行命令)。这可以放在一个单独的文件中,以便可以从许多项目中包括它

<Target Name="GenerateService">
  <Exec Command="servicegen.exe -i:%(ServiceDescription.Identity) -o:%(ServiceDescription.Identity).cs" />
</Target>
<PropertyGroup>
  <BuildDependsOn>GenerateService;$(BuildDependsOn)</BuildDependsOn>
</PropertyGroup>

发电服务$(BuildDependsOn)