本文转自:http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy

One of the things I wanted my LINQ to SQL T4 templates to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set of templates with duplicate code or intrusive handling code throughout the template. Here’s my helper class to abstract the problem away from what is already complicated enough template code.

Using the Manager class

Setup

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.

<#@ template language="C#v3.5" hostspecific="True"
#><#@ include file="Manager.ttinclude"
#><# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile) }; #>

Define a block

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.

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

Headers and 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/EndHeader and StartFooter/EndFooter. The resulting blocks will be emitted into all split files and left in the original output too.

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

Process

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

<# manager.Process(true); #>

When processing each block name in the Output path will either be overwritten or deleted to enable proper clean-up. It will also add and remove the files from Visual Studio somake sure your generated names aren’t going to collide with hand-written ones!

Manager classes

Here is the Manger class itself as well as the small ManagementStrategy classes that determines what to do with the files within Visual Studio (add/remove project items) and outside of Visual Studio (create/delete files).

Download Manager.ttinclude (4KB)

<#@ assembly name="System.Core"
#><#@ assembly name="EnvDTE"
#><#@ import namespace="System.Collections.Generic"
#><#@ import namespace="System.IO"
#><#@ import namespace="System.Text"
#><#@ import namespace="Microsoft.VisualStudio.TextTemplating"
#><#+ // T4 Template Block manager for handling multiple file outputs more easily.
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL) // Manager class records the various blocks so it can split them up
class Manager
{
private struct Block {
public String Name;
public int Start, Length;
} private List<Block> blocks = new List<Block>();
private Block currentBlock;
private Block footerBlock = new Block();
private Block headerBlock = new Block();
private ITextTemplatingEngineHost host;
private ManagementStrategy strategy;
private StringBuilder template;
public String OutputPath { get; set; } public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) {
this.host = host;
this.template = template;
OutputPath = String.Empty;
strategy = ManagementStrategy.Create(host);
} public void StartBlock(String name) {
currentBlock = new Block { Name = name, Start = template.Length };
} public void StartFooter() {
footerBlock.Start = template.Length;
} public void EndFooter() {
footerBlock.Length = template.Length - footerBlock.Start;
} public void StartHeader() {
headerBlock.Start = template.Length;
} public void EndHeader() {
headerBlock.Length = template.Length - headerBlock.Start;
} public void EndBlock() {
currentBlock.Length = template.Length - currentBlock.Start;
blocks.Add(currentBlock);
} public void Process(bool split) {
String header = template.ToString(headerBlock.Start, headerBlock.Length);
String footer = template.ToString(footerBlock.Start, footerBlock.Length);
blocks.Reverse();
foreach(Block block in blocks) {
String fileName = Path.Combine(OutputPath, block.Name);
if (split) {
String content = header + template.ToString(block.Start, block.Length) + footer;
strategy.CreateFile(fileName, content);
template.Remove(block.Start, block.Length);
} else {
strategy.DeleteFile(fileName);
}
}
}
} class ManagementStrategy
{
internal static ManagementStrategy Create(ITextTemplatingEngineHost host) {
return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host);
} internal ManagementStrategy(ITextTemplatingEngineHost host) { } internal virtual void CreateFile(String fileName, String content) {
File.WriteAllText(fileName, content);
} internal virtual void DeleteFile(String fileName) {
if (File.Exists(fileName))
File.Delete(fileName);
}
} class VSManagementStrategy : ManagementStrategy
{
private EnvDTE.ProjectItem templateProjectItem; internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) {
IServiceProvider hostServiceProvider = (IServiceProvider)host;
if (hostServiceProvider == null)
throw new ArgumentNullException("Could not obtain hostServiceProvider"); EnvDTE.DTE 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);
} internal override void CreateFile(String fileName, String content) {
base.CreateFile(fileName, content);
((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null);
} internal override void DeleteFile(String fileName) {
((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null);
} private void FindAndDeleteFile(String fileName) {
foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) {
if (projectItem.get_FileNames(0) == fileName) {
projectItem.Delete();
return;
}
}
}
}#>

[转]Multiple outputs from T4 made easy的更多相关文章

  1. Multiple outputs from T4 made easy – revisited » DamienG

    Multiple outputs from T4 made easy – revisited » DamienG Multiple outputs from T4 made easy – revisi ...

  2. 转 Multiple outputs from T4 made easy t4生成多文件

    原文:http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited Usage Initializat ...

  3. [转] How to generate multiple outputs from single T4 template (T4 输出多个文件)

    本文转自:http://www.olegsych.com/2008/03/how-to-generate-multiple-outputs-from-single-t4-template/ Updat ...

  4. t4-editor使用方法 Visual T4

    原文发布时间为:2011-05-17 -- 来源于本人的百度文章 [由搬家工具导入] http://visualstudiogallery.msdn.microsoft.com/40a887aa-f3 ...

  5. (转)Let’s make a DQN 系列

    Let's make a DQN 系列 Let's make a DQN: Theory September 27, 2016DQN This article is part of series Le ...

  6. Automake

    Automake是用来根据Makefile.am生成Makefile.in的工具 标准Makefile目标 'make all' Build programs, libraries, document ...

  7. C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\11.0

    Generating Files with the TextTransform Utility \Program Files\Common Files\Microsoft Shared\TextTem ...

  8. LEK-Introduction-Installation-Usage-new

    LEK is a set of tools which can take data from any source and search, analyze, and visualize it in r ...

  9. filebeat.yml(中文配置详解)

    ################### Filebeat Configuration Example ######################### ####################### ...

随机推荐

  1. Java for LeetCode 141 Linked List Cycle

    Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...

  2. 膜拜(codevs 3369)

    3369 膜拜  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 神牛有很多…当然…每个同学都有自己衷心膜拜的 ...

  3. HTTP协议的几个概念

    http://www.rupeng.com/favicon.ico 可获取当前图标favicon.ico服务器是指定文件名,不能更改一.HTTP协议的几个概念1.连接(Connection):浏览器和 ...

  4. LeetCode - 413. Arithmetic Slices - 含中文题意解释 - O(n) - ( C++ ) - 解题报告

    1.题目大意 A sequence of number is called arithmetic if it consists of at least three elements and if th ...

  5. Linux下创建ftp用户并锁定根目录

    [root@d vsftpd]# vi /etc/vsftpd/chroot_list 加入要锁定根目录的ftp用户名(一行只能一个用户) [root@ vsftpd]# vi /etc/vsftpd ...

  6. Linux查看硬件配置信息

    转自:http://blog.163.com/yang_jianli/blog/static/1619900062010391127338/ 一:查看cpu more /proc/cpuinfo | ...

  7. 使用asp.net从零开始制作设计网站---转载

    首先感谢提供此教程的朋友,可以给大家学习的机会,很有用,留着好好学.如下正文: 1. 申请域名 2. 购买空间 3. 备案 4. 使用photoshop完成设计与切图  5. 使用dreamweave ...

  8. 《数学之美》(吴军 著)读书笔记:第1章 文字和语言 vs 数字和信息

    第1章有4个小节,以及前言. 前言 1.信息 2.文字和数字 3.文字和语言背后的数学 4.小结 下面我一一展开,让我们看看每一节都说了什么. 前言 语言和数字都是信息传播的载体,他们之间其实存在着天 ...

  9. Java中比较不同的MD5计算方式

    在项目中经常需要使用计算文件的md5,用作一些用途,md5计算算法,通常在网络上查询时,一般给的算法是读取整个文件的字节流,然后计算文件的md5,这种方式当文件较大,且有很大并发量时,则可能导致内存打 ...

  10. Rational Software Architect V8.5.1安装

    转自:http://blog.sina.com.cn/s/blog_4a0238270101bupg.html IBM Rational Software Architect (RSA) 是 IBM ...