In a project at work we have some T4 templates running in a Visual Studio (2015) environment. Those templates should run whenever some dependent files have changed. As it’s kind of a compilation step, a best fit, I thought, would be to run the templates on every (re-)build of the project, but how to achieve that?
In a Visual Studio project any file of the project has some properties. T4-Templates are scripts that can be used to transform some resource into a different output format – or generate additional code files. As such they consume some content and produce some more content, usually some other file(s).
For this to happen you usually add a T4-Template (usual file extension is .tt) to the project. The code inside is a mixture of any .NET language with additional tags, similar as how it works in PHP or asp.net templates or JSP (Java Server Pages).
This template script is usually called at design time. In my case it generates a C#-class source code file from a set of Resource files. For this to work the „Custom Tool“ property of the template file is set to „TextTemplatingFilePreprocessor“, as that’s the processing engine that executes the t4-template at design time. As a result the context action „Run custom tool“ of the template procudes the resulting .cs file that appears below the tt-file node in the solution explorer.
Now I would like to make sure this tool runs again on any build, at least whenever the resx file it reads has been changed, but let’s keep it simple: on any build.
My expectation would have been to achieve that by using a proper „Build action“ setting. As T4 templates are a Microsoft technology and as I understand it generating code is one major use case for them I had expected this to be one of the standard use cases of t4 templates in general.
The „Build Action“ property of files can have a lot of different values.
- None: ignores the file in output. It’s not touched by the build project, nor is it contained in the assembly in any form.
- Compile: the default action for source code files. Those files are compiled and the resulting class is part of the assembly (usually in binary form).
- Content: the file is embedded in the output as it is.
- Embedded Resources form their own resource file inside the resulting assembly.
Additional values are available for special kinds of files and/or in special kinds of projects, like
- Resources and Page are means to pre-compile resources like XAML code to some generated classes using predefined tools of the WPF toolchain as far as I know.
- ApplicationDefinition is the single entrypoint of a WPF project, usually that’s the App.xaml file.
- SplashScreen is used for an image to behave like a simple default splash screen
- DesignData contains dummy data that is used for the XAML designer to show sample data in UI mocks at design time.