April 02, 2015 | Charlie Turano
Recently, we’ve seen an influx of support tickets around Code Generation and in particular Code Generation of certain T4 templates. We’ve determined that when downloading T4 files directly from GitHub they come with Unix/Linux formatted line endings. These line endings run amuck inside Visual Studio and cause many builds to break. For example, when running code generation, the process might fail with the following error due to improper line endings:
“An error occurred while generating code for item '/sitecore/templates'. T4 Template: <path_to_template>\<template_name>.tt Errors: Compiling transformation: Invalid token 'this' in class, struct, or interface member declaration. Compiling transformation: Method must have a return type. Compiling transformation: Type expected”
Compilers are properly handling both types of line endings, processing the text line by line and not complaining about problems. This does not appear to be true for template transformation operations – the string from the template is returned in such a way that it keeps the wrong line ending formatting, which in turn causes unforeseen behavior when compiled and errors like the one above.
When dealing with a file with these types of line endings there are two fixes:
Make sure you get the file with Microsoft line endings that will not break your build.
When setting up code generation for the first time and get the T4 templates, do not download; using the “Download ZIP” option (), since the text files of the templates will come with Git's F (Unix / line feed) file endings which is something Visual Studio is sensitive about.
Instead, by navigating to the template file in GitHub and opting to view the Raw version of the file and copying the text inside to an empty text file should do the trick.
To do this, one needs to navigate to the location of the .tt T4 template files in GitHub, open one inside a browser and select “Raw”:
This will expose the text for the template, and it can be easily copied from there with the correct CR LF format.
Convert the line endings
Visual Studio supports the detection of line endings that are different from the standard CR LF, but only for code files. Since .tt files are not treated as such, this check is not performed for them.
Instead, Visual Studio has the option to convert these, using its Advanced Save feature. When a text file (such as .tt files) is opened for view inside Visual Studio, the Advanced Save option will appear:
It provides developers with an easy way to convert the line endings – selecting the type of line ending to use for the file and hitting OK will save it – simple as that!
For plug-in fans there’s also an add-in for Visual Studio that deals line endings conversion – it’s called Strip’em. It can be used to convert from one type of line endings to another.