Getting T4 templates to work with Silverlight
In a previous blog post I mentioned that T4 templates didn’t quite work with Silverlight development. The reason being that Visual Studio decides to load the Silverlight version of System.dll which doesn’t contain all the required classes. Fortunately I was not the first person to run into this limitation, Jason Jarrett did as well and he described the solution in a blog post here.
The solution turns out to be surprisingly simple, just not very obvious. All you need to do is include the following line at the top of the T4 template.
1: <#@ assembly name="C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll" #>
This way the T4 template engine loads the regular System.dll instead of the CoreCLR version and all is well.
So now the complete template looks like:
1: <#@ Template language="C#" #>
2: <#@ assembly name="C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll" #>
3: <#@ import namespace="System.Collections.Generic" #>
4: <#
5: Dictionary<string, string> props = new Dictionary<string, string>();
6: props.Add("FirstName", "string");
7: props.Add("LastName", "string");
8: props.Add("Age", "int");
9: #>
10: namespace T4Test
11: {
12: public class Demo
13: {
14: <#
15:
16: foreach (KeyValuePair<string, string> prop in props)
17: {
18: #>
19: /// <summary>
20: /// Get or set the <#= prop.Key #> property.
21: /// </summary>
22: public <#= prop.Value #> <#= prop.Key #> { get; set; }
23:
24: <#
25: }
26: #>
27: }
28: }
and the generated output looks like:
1: namespace T4Test
2: {
3: public class Demo
4: {
5: /// <summary>
6: /// Get or set the FirstName property.
7: /// </summary>
8: public string FirstName { get; set; }
9:
10: /// <summary>
11: /// Get or set the LastName property.
12: /// </summary>
13: public string LastName { get; set; }
14:
15: /// <summary>
16: /// Get or set the Age property.
17: /// </summary>
18: public int Age { get; set; }
19:
20: }
21: }
Pretty nice, something I will be using a lot more often when developing all those repetitive DTO classes.
A T4 template editor
By default Visual Studio allows you to create T4 templates by renaming a text files extension from TXT to TT but that is about it. No IntelliSense, no keyword highlighting or any of the other things we are used to.
Fortunately Clarius has developed a T4 editor that plug into Visual Studio and makes live a bit easier when developing T4 templates. There are several editions and they even have a free community edition, which I am using now. The free edition might not have all the features of the professional edition that ships for just $ 99.99 but its a big improvement over the default Visual Studio experience and for a price that is hard to beat. Below is a screen shot of the Clarius T4 editor with the same template.
Very useful and a great addition to my Visual Studio toolkit!
Enjoy!