2013-03-27 84 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任務指定不同選項的詳情。

相關問題