Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Visual Studio 2008 to regenerate code from T4 templates when an XML file changes?

I'm generating quite a bit of code from a single XML file, but the templates are organized in two different T4 templates. Whenever I change the XML file, I have to remember to open the two *.tt files, change them trivially (add / delete a space) and save them again to make sure the code is generated.

This can't be the right way to do it!

Ideally, I would like Visual Studio 2008 to do a text transfor on the T4 files if the XML file has changed. I'm a bit lost since I don't really know how Visual Studio builds C# projects, so pointers in that direction would also be of help (I could then try to figure it out myself).

like image 381
Daren Thomas Avatar asked Oct 14 '22 12:10

Daren Thomas


2 Answers

You can use T4ScriptFileGenerator from T4Toolbox as a custom tool for your XML file. Let's say you have Test.XML file in your project with this custom tool. The first time Test.XML is saved, this custom tool create a new Test.tt file. You can place your code generation logic there (in place, or #include your other .tt files). Next time you save Test.XML it will transform (generate code from) the existing Test.tt.

like image 170
Oleg Sych Avatar answered Oct 18 '22 21:10

Oleg Sych


I think I might finally have found a solution here. I got the idea when browsing how XAML files are mentioned in the project file for c# projects.

Let us assume a file A.tt and B.tt that use data from C.xml and we would like to regenerate the code whenever C.xml changes.

Edit the project file. Your definitions for A.tt and B.tt should look something like this:

<ItemGroup>
    <None Include="A.tt">
      <Generator>TextTemplatingFileGenerator</Generator>
      <LastGenOutput>A.cs</LastGenOutput>
      <DependentUpon>C.xml</DependentUpon>
    </None>
    <None Include="B.tt">
      <Generator>TextTemplatingFileGenerator</Generator>
      <LastGenOutput>B.cs</LastGenOutput>
      <DependentUpon>C.xml</DependentUpon>
    </None>
</ItemGroup>

Further, you will need (of course...)

<ItemGroup>
    <None Include="C.xml" />
</ItemGroup>

And also the instruction to autogenerate A.cs and B.cs:

<Compile Include="A.cs">
      <DependentUpon>A.tt</DependentUpon>
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
</Compile>
<Compile Include="B.cs">
      <DependentUpon>B.tt</DependentUpon>
      <AutoGen>True</AutoGen>
      <DesignTime>True</DesignTime>
</Compile>

I believe most of this will already be done for you when you create the template file, so all you really have to add is the <DependentUpon>C.xml</DependentUpon> parts to the ItemGroups for A.tt and B.tt.

like image 26
Daren Thomas Avatar answered Oct 18 '22 21:10

Daren Thomas