2013-03-27 77 views
3

我正在使用代码生成来使用基于文本的描述中的命令行工具生成C#类的项目。我们也将开始使用JavaScript的这些描述。如何将命令行代码生成器添加到Visual Studio?

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

是手动运行的步骤是:

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

当我建我想的MSBuild/VS首先生成的CS文件,然后编译。可以这样做,通过修改csproj,可能使用MSBuild任务ExecDependentUpon & AutoGen

回答

3

Antlr有一个example of a process可用于将生成的代码添加到项目。这具有显示嵌套在源文件下的文件的优点,尽管添加起来更复杂。

需要添加的项目组与待从所生成的文件,例如:

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

然后添加要产生包含源代码的其余部分的的ItemGroup的CS文件。

<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>  

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

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

通常我会建议预生成命令放置在预生成事件中,但由于命令行工具将创建编译所需的C#类,因此应在.csproj文件中执行in the BeforeBuild target。原因是因为MSBuild在调用BeforeBuild之前查找需要编译的文件,以及在整个过程中调用PreBuildEvent的时间(可以在MSBuild使用的Microsoft.Common.targets文件中看到此流程) 。

呼叫Exec任务从BeforeBuild目标内生成的文件:

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

Exec task MSDN文档有关Exec任务指定不同选项的详情。

相关问题