T4文本模板转换过程将文本模板文件作为输入,生成一个新的文本文件作为输出。 例如,可以使用文本模板生成 Visual Basic 或 C# 代码,还可以生成 HTML 报告。

有三个组件参与这一过程:引擎、宿主和指令处理器。 引擎对该过程进行控制(引擎与宿主和指令处理器交互),以生成输出文件;宿主提供与环境的所有交互(如定位文件和程序集); 指令处理器为文本模板添加功能(如从 XML 文件或数据库读取数据等)。

组件:

组件 说明 可自定义(是/否)
引擎 引擎组件控制文本模板转换过程。
主机 宿主是引擎与用户环境之间的接口。 Visual Studio 是文本转换过程的宿主。 是。 可以编写自定义宿主。
指令处理器 指令处理器是处理文本模板中的指令的类。 可以使用指令从输入源向文本模板提供数据。 是。 可以编写自定义指令处理器。

引擎:

引擎以字符串形式从宿主接收模板,而宿主处理在转换过程中所用的所有文件。 接下来,引擎请求宿主定位所有自定义指令处理器和环境中的其他方面。 然后,引擎编译和运行生成转换类。 引擎将生成的文本返回给宿主,宿主通常将该文本保存到文件中。

宿主:

宿主负责转换过程之外与环境有关的所有操作,包括:

1)查找引擎或指令处理器请求的文本和二进制文件。 宿主可以搜索目录和全局程序集缓存以查找程序集。 宿主可以为引擎查找自定义指令处理器代码。 宿主还可以查找并读取文本文件,然后以字符串形式返回其内容。

2)提供标准程序集和命名空间的列表,供引擎用于创建生成转换类。

3)提供引擎在编译和执行生成转换类时所用的应用程序域。 将使用独立应用程序域,以免宿主应用程序受到模板代码错误的影响。

4)写入生成的输出文件。

5)设置生成的输出文件的默认扩展名。

6)处理文本模板转换错误。 例如,宿主可以将错误显示在用户界面中,也可以将错误写入文件。 (在 Visual Studio 中,错误显示在“错误消息”窗口中。)

7)在用户调用了指令但未提供值时,提供必需的参数值。 指令处理器可以指定指令名称和参数,可以请求宿主提供默认值(如果有)。

指令和指令处理器:

指令是文本模板中的命令。 它向生成过程提供参数。 通常,指令定义模型或其他输入的源和类型,以及输出文件的文件扩展名等。

指令处理器可以处理一个或多个指令。 转换模板之前,必须安装能够处理模板中的指令的指令处理器。


有了基本的概念,我们看下面的Demo(在程序中动态执行T4模板):


在程序中动态执行T4模板:

执行结果:

CustomTextTemplatingEngineHost.cs(自定义文本模板宿主‎)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TextTemplating;
using System.CodeDom.Compiler;
using System.IO;
 
namespace CustomHost
{
    public class CustomTextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
    {
        #region ITextTemplatingEngineHost
        internal string TemplateFileValue;
        public string TemplateFile
        {
            get { return TemplateFileValue; }
        }
       
        private string fileExtensionValue = ".txt";
        public string FileExtension
        {
            get { return fileExtensionValue; }
        }
        
        private Encoding fileEncodingValue = Encoding.UTF8;
        public Encoding FileEncoding
        {
            get { return fileEncodingValue; }
        }
        private CompilerErrorCollection errorsValue;
        public CompilerErrorCollection Errors
        {
            get { return errorsValue; }
        }
        public IList<string> StandardAssemblyReferences
        {
            get
            {
                return new string[]
                {
                    typeof(System.Uri).Assembly.Location
                };
            }
        }
        public IList<string> StandardImports
        {
            get
            {
                return new string[]
                {
                    "System"
                };
            }
        }
        public bool LoadIncludeText(string requestFileName, out string content, out string location)
        {
            content = System.String.Empty;
            location = System.String.Empty;
 
            if (File.Exists(requestFileName))
            {
                content = File.ReadAllText(requestFileName);
                return true;
            }
            else
            {
                return false;
            }
        }
        
        public object GetHostOption(string optionName)
        {
            object returnObject;
            switch (optionName)
            {
                case "CacheAssemblies":
                    returnObject = true;
                    break;
                default:
                    returnObject = null;
                    break;
            }
            return returnObject;
        }
       
        public string ResolveAssemblyReference(string assemblyReference)
        {
            if (File.Exists(assemblyReference))
            {
                return assemblyReference;
            }
           
            string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference);
            if (File.Exists(candidate))
            {
                return candidate;
            }
            return "";
        }
        
        public Type ResolveDirectiveProcessor(string processorName)
        {
            if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
            {
                //return typeof();
            }
            throw new Exception("Directive Processor not found");
        }
       
        public string ResolvePath(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("the file name cannot be null");
            }
            if (File.Exists(fileName))
            {
                return fileName;
            }
            string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
            if (File.Exists(candidate))
            {
                return candidate;
            }
            return fileName;
        }
 
        public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
        {
            if (directiveId == null)
            {
                throw new ArgumentNullException("the directiveId cannot be null");
            }
            if (processorName == null)
            {
                throw new ArgumentNullException("the processorName cannot be null");
            }
            if (parameterName == null)
            {
                throw new ArgumentNullException("the parameterName cannot be null");
            }
            return String.Empty;
        }
 
        public void SetFileExtension(string extension)
        {
            fileExtensionValue = extension;
        }
        
        public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
        {
            fileEncodingValue = encoding;
        }
        
        public void LogErrors(CompilerErrorCollection errors)
        {
            errorsValue = errors;
        }
       
        public AppDomain ProvideTemplatingAppDomain(string content)
        {
            return AppDomain.CreateDomain("Generation App Domain");
        }
 
        #endregion
 
        #region ITextTemplatingSessionHost
        public ITextTemplatingSession CreateSession()
        {
            return Session;
        }
 
        public ITextTemplatingSession Session
        {
            get;
            set;
        }
        #endregion
    }
}

“执行”按钮单击-》(T4文本模板转换过程)

CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost();
host.TemplateFileValue = txtPath.Text;
string input = File.ReadAllText(txtPath.Text);
host.Session = new TextTemplatingSession();
host.Session.Add("hzx", new People("韩兆新", 24, "男"));
 
string output = new Engine().ProcessTemplate(input, host);
 
txtResult.Text = output;
StringBuilder errorWarn = new StringBuilder();
foreach (CompilerError error in host.Errors)
{
    errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText);
}
txtError.Text = errorWarn.ToString();

申明People类可序列化(传递参数的类型)

[Serializable]
public class People
{
    public People(string name, uint age, string sex)
    {
        this.Name = name;
        this.Age = age;
        this.Sex = sex;
    }
    public string Name
    { set; get; }
    public uint Age
    { set; get; }
    public string Sex
    { set; get; }
}

test.tt

<#@template debug="false" hostspecific="false" language="C#"#>
<#@ output extension=".txt" encoding="utf-8" #>
<#@ parameter type="Demo_T4.People" name="hzx" #>
Name:<#= hzx.Name #>  Age:<#= hzx.Age #>   Sex:<#= hzx.Sex #>

T4文本模板转换过程相关推荐

  1. C#代码生成工具:文本模板初体验 使用T4批量修改实体框架(Entity Framework)的类名...

    转自:http://www.cnblogs.com/huangcong/archive/2011/07/20/1931107.html 在之前的文本模板(T4)初体验中我们已经知道了T4的用处,下面就 ...

  2. T4((Text Template Transformation Toolkit))模版引擎之基础入门 C#中文本模板(.tt)的应用...

    1 关于C#中文本模板(.tt)的简单应用 https://blog.csdn.net/zunguitiancheng/article/details/78011145 任何一个傻瓜都能写出计算机能理 ...

  3. 黄聪:C#代码生成工具:文本模板初体验 Hello,World!

    C#代码生成工具:文本模板初体验 Hello World 在VS中的文本模板(也称T4),它给我有点CodeSmith的感觉,也是通过模板加逻辑代码混编批量生成代码的方法,但是关于T4的资料不多,而且 ...

  4. 自己动手实现简易代码生成器、采用文本模板文件生成服务层、服务层接口代码的做法参考...

    为什么80%的码农都做不了架构师?>>>    最近受到 单程列车 http://www.cnblogs.com/zhaojingjing/  的启发,让我做一个模板文件来生成代码, ...

  5. wxWidgets:使用文本模板

    wxWidgets:使用文本模板 wxWidgets:使用文本模板 wxWidgets:使用文本模板 结合 wxHashMap.wxVariant 制作文本模板的例子,尤其是.在 wxHTML 中嵌入 ...

  6. JS(JavaScript) 使用捕获性分组处理文本模板,最终生成完整字符串

    var tmp = "An ${a} a ${b} keeps the ${c} away";// obj 是 json 对象 var obj = {a:"apple&q ...

  7. 自定义tt文本模板实现MySql指数据库中生成实体类

    自定义tt文本模板实现MySql指数据库中生成实体类 1.在项目中依次点击"添加"/"新建项",选择"文本模板",输入名称后点击添加. 2. ...

  8. t4 tornado 模板

    4.1 静态文件 现在有一个预先写好的静态页面文件 (下载静态文件资源), 我们来看下如何用tornado提供静态文件. static_path 我们可以通过向web.Application类的构造函 ...

  9. 你必须懂的 T4 模板:深入浅出

    示例代码:示例代码__你必须懂的T4模板:浅入深出.rar (一)什么是T4模板? T4,即4个T开头的英文字母组合:Text Template Transformation Toolkit. T4文 ...

最新文章

  1. Java 内存 关系_内存一致性 – 发生在Java之前的关系
  2. Qt中的 Size Hints 和 Size Policies
  3. TokuDB · 引擎特性 · HybridDB for MySQL高压缩引擎TokuDB 揭秘
  4. Fast R-CNN《Fast R-CNN》论文笔记
  5. JZOJ__Day 9:【普及模拟】Square
  6. Oracle数据库无法向listener注册的解决一例
  7. ssm使用全注解实现增删改查案例——EmpServiceImpl
  8. java空心正方形代码_从Java中的用户输入绘制空心星号正方形/矩...
  9. android checkbox监听另一个checkbox选中和不选中_一个真正0基础小白学习前端开发的心路历程...
  10. 利用Dockefile将Python的py文件项目代码打包为Docker镜像
  11. Linux7安装gi报错,Redhat 7.6安装11G RAC GI时遇到此类报错
  12. 数据库清空表中的数据
  13. php 获取图片的宽高,JS怎么获取图片当前宽高
  14. 用libconfig读取配置文件
  15. 2019 年 Linux 架构师最新熬夜制作!
  16. 求n的阶乘的算法框图_VB求阶乘1/1!+1/2!+1/3!+.....+1/n!之和问题解决
  17. Apache Impala 3.4.0 —— Admission Control and Query Queuing(动态资源池)实践
  18. GooglePlay商店如何优化
  19. 【实用软件 01期】B站视频下载器(免安装、即点即用)
  20. 驾考科目二倒车入库技巧图解

热门文章

  1. Nginx负载均衡和反向代理
  2. Redis入门第二篇【存储数据结构之string类型】
  3. 灯的开关 Bulb Switcher II
  4. Linux centos 集群下ssh无密码
  5. win 2008R2 域的备份与还原
  6. POJ1849 Two——贪心——Pku1849
  7. 我的MVP,来的那么“糊涂”(2009.4)
  8. Ruby --- gem(RubyGems)安装与使用
  9. 汇编 CALL和RET指令
  10. C语言 将字符串中数字字符全部删除