Multiple outputs from T4 made easy – revisited

My multiple outputs from t4 made easy post contained a class making it easy to produce multiple files from Visual Studio’s text templating engine (T4).

While useful it had a few issues:

  • Getting start/end blocks mixed up resulted in unpredictable behaviour
  • Files were rewritten even when content did not change
  • Did not play well with source control
  • Files not always deleted in VS
  • Failed in Visual Studio’s project-less Web Sites

This helper class forms the basis of multiple file output for Entity Framework templates in .NET 4.0 and the LINQ to SQL templates on CodePlex so we (Jeff Reed, Andrew Peters and myself) made the following changes.

Improvements

Simpler block handling

The header, footer and file blocks can now be completed with EndBlock (EndHeader and EndFooter are gone), although it will automatically end the previous block when it hits a new one or the final Process method.

Skip unchanged files

Files are now only written to disk if the contents are different with the exception of the original T4 output file (we can’t stop that, sorry).

There is additional overhead reading and comparing files we believe unmodified files keeping their dates and source control status are worth it.

Automatic checkout

When the template detects it is running in Visual Studio and that the file it needs to write to is currently in source control but not checked out it will check the file out for you.

Predictable clean-up

All files that were not part of the generation process but are nested under the project item will now be deleted when running inside Visual Studio.

Outside of Visual Studio files are no longer deleted – this was destructive and it couldn’t know which files it generated on a previous run to clean-up correctly anyway.

Website projects fall back to single file generation

Visual Studio has both web sites and web applications with the former being project-less leading to very messy multi-file generation so it forces single file generation.

Internal improvements

Source is now simpler to read and understand with less public visibility and faster and more robust VS interop by batching the files & deletes to a single invoke at the end to avoid conflicts with other add-ins that might be triggered by the changes.

Usage

Initialization

You’ll need to get the code into your template – either copy the code in or reference it with an include directive. Then declare an instance of the Manager class passing in some environmental options such as the desired default output path. (For Visual Studio 2010 remove the #v3.5 portion from the language attribute)

<#@ template language="C#v3.5" hostspecific="True"
#><#@include file="Manager.ttinclude"
#><# var manager = Manager.Create(Host, GenerationEnvironment); #>

File blocks

Then add one line before and one line after each block which could be split out into it’s own file passing in what the filename would be if split. The EndBlock is optional if you want it to carry through to the next one :)

<# manager.StartNewFile("Employee.generated.cs"); #>
public class Employee { … }
<# manager.EndBlock(); #>

Headers & footers

Many templates need to share a common header/footer for such things as comments or using/import statements or turning on/off warnings. Simply use StartHeader and StartFooter and the blocks will be emitted to the start and end of all split files as well as being left in the original output file.

<# manager.StartHeader(); #>
// Code generated by a template
using System;

<# manager.EndBlock(); #>

Process

At the end of the template call Process to handle splitting the files (true) or not (false). Anything not included in a specific StartNewFile block will remain in the original output file.

<# manager.Process(true); #>

Revised Manager class

Latest source available at GitHub
<#@ assembly name="System.Core"
#><#@ assembly name="System.Data.Linq"
#><#@ assembly name="EnvDTE"
#><#@ assembly name="System.Xml"
#><#@ assembly name="System.Xml.Linq"
#><#@ import namespace="System"
#><#@ import namespace="System.CodeDom"
#><#@ import namespace="System.CodeDom.Compiler"
#><#@ import namespace="System.Collections.Generic"
#><#@ import namespace="System.Data.Linq"
#><#@ import namespace="System.Data.Linq.Mapping"
#><#@ import namespace="System.IO"
#><#@ import namespace="System.Linq"
#><#@ import namespace="System.Reflection"
#><#@ import namespace="System.Text"
#><#@ import namespace="System.Xml.Linq"
#><#@ import namespace="Microsoft.VisualStudio.TextTemplating"
#><#+

// Manager class records the various blocks so it can split them up
class Manager {
    private class Block {
        public String Name;
        public int Start, Length;
    }

    private Block currentBlock;
    private List<Block> files = new List<Block>();
    private Block footer = new Block();
    private Block header = new Block();
    private ITextTemplatingEngineHost host;
    private StringBuilder template;
    protected List<String> generatedFileNames = new List<String>();

    public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template) {
        return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template);
    }

    public void StartNewFile(String name) {
        if (name == null)
            throw new ArgumentNullException("name");
        CurrentBlock = new Block { Name = name };
    }

    public void StartFooter() {
        CurrentBlock = footer;
    }

    public void StartHeader() {
        CurrentBlock = header;
    }

    public void EndBlock() {
        if (CurrentBlock == null)
            return;
        CurrentBlock.Length = template.Length - CurrentBlock.Start;
        if (CurrentBlock != header && CurrentBlock != footer)
            files.Add(CurrentBlock);
        currentBlock = null;
    }

    public virtual void Process(bool split) {
        if (split) {
            EndBlock();
            String headerText = template.ToString(header.Start, header.Length);
            String footerText = template.ToString(footer.Start, footer.Length);
            String outputPath = Path.GetDirectoryName(host.TemplateFile);
            files.Reverse();
            foreach(Block block in files) {
                String fileName = Path.Combine(outputPath, block.Name);
                String content = headerText + template.ToString(block.Start, block.Length) + footerText;
                generatedFileNames.Add(fileName);
                CreateFile(fileName, content);
                template.Remove(block.Start, block.Length);
            }
        }
    }

    protected virtual void CreateFile(String fileName, String content) {
        if (IsFileContentDifferent(fileName, content))
            File.WriteAllText(fileName, content);
    }

    public virtual String GetCustomToolNamespace(String fileName) {
        return null;
    }

    public virtual String DefaultProjectNamespace {
        get { return null; }
    }

    protected bool IsFileContentDifferent(String fileName, String newContent) {
        return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
    }

    private Manager(ITextTemplatingEngineHost host, StringBuilder template) {
        this.host = host;
        this.template = template;
    }

    private Block CurrentBlock {
        get { return currentBlock; }
        set {
            if (CurrentBlock != null)
                EndBlock();
            if (value != null)
                value.Start = template.Length;
            currentBlock = value;
        }
    }

    private class VSManager: Manager {
        private EnvDTE.ProjectItem templateProjectItem;
        private EnvDTE.DTE dte;
        private Action<String> checkOutAction;
        private Action<IEnumerable<String>> projectSyncAction;

        public override String DefaultProjectNamespace {
            get {
                return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString();
            }
        }

        public override String GetCustomToolNamespace(string fileName) {
            return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
        }

        public override void Process(bool split) {
            if (templateProjectItem.ProjectItems == null)
                return;
            base.Process(split);
            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null));
        }

        protected override void CreateFile(String fileName, String content) {
            if (IsFileContentDifferent(fileName, content)) {
                CheckoutFileIfRequired(fileName);
                File.WriteAllText(fileName, content);
            }
        }

        internal VSManager(ITextTemplatingEngineHost host, StringBuilder template)
            : base(host, template) {
            var hostServiceProvider = (IServiceProvider) host;
            if (hostServiceProvider == null)
                throw new ArgumentNullException("Could not obtain IServiceProvider");
            dte = (EnvDTE.DTE) hostServiceProvider.GetService(typeof(EnvDTE.DTE));
            if (dte == null)
                throw new ArgumentNullException("Could not obtain DTE from host");
            templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
            checkOutAction = (String fileName) => dte.SourceControl.CheckOutItem(fileName);
            projectSyncAction = (IEnumerable<String> keepFileNames) => ProjectSync(templateProjectItem, keepFileNames);
        }

        private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<String> keepFileNames) {
            var keepFileNameSet = new HashSet<String>(keepFileNames);
            var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>();
            var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames(0)) + ".";
            foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
                projectFiles.Add(projectItem.get_FileNames(0), projectItem);

            // Remove unused items from the project
            foreach(var pair in projectFiles)
                if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix))
                    pair.Value.Delete();

            // Add missing files to the project
            foreach(String fileName in keepFileNameSet)
                if (!projectFiles.ContainsKey(fileName))
                    templateProjectItem.ProjectItems.AddFromFile(fileName);
        }

        private void CheckoutFileIfRequired(String fileName) {
            var sc = dte.SourceControl;
            if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName))
                checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
        }
    }
} #>

[)amien

31 responses  

  1. Have tried this now and it is so much easier than I thought. Thanks

    Johnk – November 25th, 2009
  2. uff!
    Differences Between Project and Item Templates…

    public class Class1(){}

    public class Class1(){}

    Somehow an overload or set that do not depend(too much) on ProjectItems

    // :(
    maybe next version(s)

    I like to load an xml file with XElement then iterate the nodes and attributes and generate a slim model for whatever… but, i like a xsd to check the xml file at the moment somebody writes some funny business. However i also like to asure that the schema is placed somewhere expected but the xx.cs files all together in the xx.tt tree…

    hmm!….
    and by the way!… if i choose split, and i do, why is a xx.cs from xx.tt still there and how can i prevent it. Even if the xx.cs is an empty file

    Those are just some loosy brainwaves…

    I DO LIKE THE MANAGER CLASS

    ! THANK YOU !

    marius – December 27th, 2009
  3. Hi Damien,

    great thank you very much for this update. I do use your class a lot and it works like a breeze!

    Tim

    Tim Fischer (tangible)January 3rd, 2010
  4. Hi There,

    This works great!

    As per other Marius’ question. How do i prevent the xx.cs file to be generated?

    Marius van BelkumFebruary 22nd, 2010
  5. You can’t – VS’s SingleFileGenerator that T4 is based on insists on creating the original file.

    The best you could hope to do would be to turn this into a .log or something by changing the file extension and outputting some unimportant information.

    [)amien

    Damien GuardFebruary 22nd, 2010
  6. Hey D,
    Thanks for the code. Your listing is missing an end tag. Might confuse/frustrate some….

    SkyFebruary 27th, 2010
  7. pingback

    […] out that bit and it worked like a charm. For a full description of that part of the script go to http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited and read Damiens excellent […]

    Using T4 to manage config files for complex deployment scenarios « Andreas’ code blogAugust 1st, 2010
  8. pingback

    […] files from T4, something it doesn’t do normally. Again, someone has been here before, this time Damien Guard with his excellent T4 Manager class. Now, armed with all this I could put the template together, […]

    Auto-generating XML serialization classes from BizTalk schemas | phazed.comOctober 4th, 2010
  9. Hi Damien, thanks a lot for providing this template!!

    I’ve been using your template since the first version, and now I started using it for the Chinook Database to generate multiple sql and batch files. I noticed that the Manager class generates all files with UTF-8 encoding only. In my case, I need to created sql files with Unicode encoding, and batch files with ASCII encoding.

    I changed your original template and added an Encoding attribute to the Block class, and overloaded the StartNewFile method:

    public void StartNewFile(String name) {
    	StartNewFile(name, Encoding.UTF8);
    }
    	
    public void StartNewFile(String name, Encoding encoding) {
    	if (name == null)
    		throw new ArgumentNullException("name");
    	CurrentBlock = new Block { Name = name, Encoding = encoding };
    }

    Then, I used the block encoding in all calls to File.WriteAllText and to File.ReadAllText (to regenerate a file if its encoding has changed). This way we can control the encoding of the generated files. The modified version I am using is located here, just in case you want to integrate it.

    Thanks again for this template!

    Cheers,
    Luis

    Luis RochaNovember 16th, 2010
  10. Damien,
    Thanks for the help! Big time saver, but I have a really gnawing issue with it.
    How come when I add to the header AFTER adding a normal block, the header information appears inline and not with the rest of the header? It would make better sense (to me), to output all header information inside the header, and not piecewise, throughout the file (this is only an issue when outputting a single file). Is this by design? From my app’s POV its a bug.
    Thoughts?

    Tim – December 7th, 2010
  11. Are you building the header in a single go after a normal block or attempting to build the header in several different blocks?

    [)amien

    Damien GuardDecember 7th, 2010
  12. …Attempting to build the header in several different blocks…

    Tim – December 7th, 2010
  13. Yes, this template does not supports building one block in multiple places and I think it would add complexity to it that most people don’t need.

    [)amien

    Damien GuardDecember 9th, 2010
  14. Cool. Thanks for the feedback.. My code just has an extra section that preprocesses the header now. A little less efficient — but its an offline process anyway :)
    The mileage we get from the outputted code is immense. Thanks!

    Tim – December 14th, 2010
  15. Hi Damien, you seem to know your T4 stuff – very handy include.

    A quick question; I’m generating a WCF service (the .svc and .cs file) via T4, everything works fine but for some reason Visual Studio separates the .svc and the .cs file – is there a way to make the .cs file be a shadow of the .svc as it usually does if you create the service manually?

    Regards, Paul.

    PaulSeptember 8th, 2011
  16. There’s nothing the template can do automatically as far as I know but you can manually edit the .csproj file and make one DependentUpon the other which will visually stack them in the Project Explorer.

    [)amien

    Damien GuardSeptember 8th, 2011
  17. Just an FYI,

    If the T4Toolbox is included ( ), the Manager produces no files. I think it is in the dispose method of the surrounding class…but I could not track it down.

    Bill

    Bill Huth – November 3rd, 2011
  18. pingback

    […] of different types in a single file might be a tad unmanageable in some circumstances, I discovered a rather handy T4 mix-in that permits me to output multiple files from a single template using a simple […]

    Versioning with T4 templates | somewhat abstractMarch 10th, 2012
  19. How can I delete the original generation?
    Say that I keep all my output within StartNewFile and EndBlock and I don’t want the default file generated? only my blocks.
    For intance, example.tt would generate example_model.cs and example_viewmodel.cs, but NOT example.cs

    Thanks a lot!

    Nestor – July 6th, 2012
  20. There’s no way to suppress the default output or reliably delete it (it is often locked).

    I find the best option is to just have it list all the outputs it created and set the output extension to .log

    [)amien

    Damien GuardJuly 6th, 2012
  21. I have just used your approach in order to achieve full class conditional generation. Your class Manager is a really neat and usefull piece of code.

    Thanks a lot for sharing it!

    Júlio Nobre – August 11th, 2012
  22. pingback

    […] with the help of this script by Damien Guard you can define blocks that get generated in different files. You can also define common blocks, […]

    T4 Lessons Learned | Marius Bancila's BlogSeptember 3rd, 2012
  23. Thanks for sharing this really neat piece of code. With t4toolbox seemingly unsupported, this is a nice way to get no-hassle multifile t4 support in VS2012.

    Lars Ole – November 16th, 2012
  24. .. And also: I can’t believe three years on from the posting of this article, it remains relevant ..

    Lars Ole – November 17th, 2012
  25. Hi Damien,
    Thx for this nice and clean solution (IMHO this should be part of the VS t4 out of the box experience).
    I used it in VS 2012. After enabling build support (with this guideline http://www.olegsych.com/2010/04/understanding-t4-msbuild-integration/ ) I found that the line in the factory method:

    return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template);

    does not detect the host being MSBuild. It creates a VSManager and there it gets a NPE when trying to obtain the DTE.
    So I changed this code to:

    if ((host != null) && (host is IServiceProvider)){
      var dte = ((IServiceProvider)host).GetService(typeof(EnvDTE.DTE));
      if (dte != null) return new VSManager(host, template);
    }
    return new FileManager(host, template);

    and everything works as expected.

    Thx again and regards
    Robert

    Robert – December 17th, 2012
  26. Having problem with multi-file updates… for some reason the source control IsItemUnderSCC returns false when should be true. I’m using the Perforce V11 PlugIn for source control.

    John – March 15th, 2013
  27. Hmm, isItemUnderSCC is a function of the DTE object (Visual Studio) that goes down into the source provider. It sounds like the Perforce plug-in isn’t implementing it. You might be able to work around it by having it always try and check the file out.

    [)amien

    Damien GuardMarch 15th, 2013
  28. var manager = Manager.Create(Host, GenerationEnvironment);
    There is no name of the current context “Host”
    why?

    leconehu – July 8th, 2013
  29. I believe a bug exists in IsFileContentDifferent. Shouldn’t the code be?

    protected bool IsFileContentDifferent(string fileName, string newContent)
    {
      return !File.Exists(fileName) || File.ReadAllText(fileName) != newContent ;
    }

    It would be a nice feature if the code would remove files that are no longer generated by the template.

    Richard Collette – July 29th, 2013
  30. You have !a || !b which is logically the same as what is there of !(a && b)

    To be able to delete files that are no longer there it would need to record a list of them…

    Damien GuardJuly 29th, 2013
  31. I read many solutions/documentation to generate multiple outputs from a single T4 template (including in-depth Oleg Sych’s articles). Regarding multiple outputs file generation I truly love your solution.

    Easy to use with neat/lightweighted code in the background (very easy to understand and extend).

    Thanks a lot.

    Stephane Issartel – December 6th, 2013

Respond to this