通过T4模板生成代码,运行时实现

关键代码段:Host

using Microsoft.VisualStudio.TextTemplating;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CodeGenerate.EngineHost
{
public class TextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
{
public List<string> LocalDlls { get; set; }
public List<string> Namespaces { get; set; }
/// <summary>
/// 模板文件
/// </summary>
public string TemplateFile { get; set; }
/// <summary>
/// 文件扩展名
/// </summary>
public string FileExtension { get; set; }
/// <summary>
/// 文件扩展名
/// </summary>
public Encoding FileEncoding { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public CompilerErrorCollection Errors { get; set; }
public IList<string> StandardAssemblyReferences
{
get
{
LocalDlls.Add(typeof(System.Uri).Assembly.Location);
return LocalDlls;
}
}
public IList<string> StandardImports
{
get
{
Namespaces.Add("System");
return Namespaces;
}
}
/// <summary>
/// 参数传递
/// </summary>
public ITextTemplatingSession Session { get; set; } 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) == )
{
//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)
{
FileExtension = extension;
}
public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
{
FileEncoding = encoding;
}
public void LogErrors(CompilerErrorCollection errors)
{
Errors = errors;
}
public AppDomain ProvideTemplatingAppDomain(string content)
{
return AppDomain.CreateDomain("Generation App Domain");
} public ITextTemplatingSession CreateSession()
{
return this.Session;
}
}
}

Session

using Microsoft.VisualStudio.TextTemplating;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks; namespace CodeGenerate.EngineHost
{
[Serializable]
public class TextTemplatingSession : Dictionary<string, Object>, ITextTemplatingSession, ISerializable
{
public Guid Id { get;private set; } public TextTemplatingSession() : this(Guid.NewGuid())
{
} public TextTemplatingSession(Guid id)
{
this.Id = id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public TextTemplatingSession(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Id = (Guid)info.GetValue("Id", typeof(Guid));
} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Id", Id);
} public override bool Equals(object obj)
{
var o = obj as TextTemplatingSession;
return o != null && o.Equals(this);
} public bool Equals(ITextTemplatingSession other)
{
return other != null && other.Id == this.Id;
} public bool Equals(Guid other)
{
return other.Equals(Id);
}
}
}

入口

  string templateFileName = "Template/test.tt";
TextTemplatingEngineHost host = new TextTemplatingEngineHost();
Engine engine = new Engine();
//引入本地dll
host.LocalDlls = new List<string>() { AppDomain.CurrentDomain.BaseDirectory.ToString() + "Params.dll" };
//引入命名空间
host.Namespaces = new List<string>() { "Params" };
//模板文件
host.TemplateFile = templateFileName;
//设置输出文件的编码格式
host.SetOutputEncoding(System.Text.Encoding.UTF8, false);
//通过Session将参数传递到模板
EngineHost.TextTemplatingSession keyValuePairs = new EngineHost.TextTemplatingSession();
testType t = new testType() { Name = "" };
keyValuePairs.Add("test", t);
host.Session = keyValuePairs;
//模板
string input = File.ReadAllText(templateFileName);
//执行代码生成
string output = engine.ProcessTemplate(input, host);
//设置文件的输出路径和文件扩展名 ,,根据模板中的设置定义
string outputFileName = string.Concat(
AppDomain.CurrentDomain.BaseDirectory.ToString(), "Output/",
Path.GetFileNameWithoutExtension(templateFileName),
host.FileExtension);
//将生成的文件写入到新位置
File.WriteAllText(outputFileName, output, host.FileEncoding);
if (host.Errors.HasErrors)
{
foreach (CompilerError error in host.Errors)
{
MessageBox.Show(error.ToString());
}
}

tt文件

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="Params.dll" #>
<#@ import namespace="Params" #>
<#@ parameter type="Params.testType" name="test" #>
<#@ output extension=".cs" #>
<# if(test!=null&&test.Name!=null){#>
<#=test.Name #>
<# } #>

自定义参数

 [Serializable]
public class testType
{
public string Name { get; set; }
}

C# 通过T4自动生成代码的更多相关文章

  1. mybatis generator maven插件自动生成代码

    如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...

  2. java如何在eclipse编译时自动生成代码

    用eclipse写java代码,自动编译时,如何能够触发一个动作,这个动作是生成本项目的代码,并且编译完成后,自动生成的代码也编译好了, java编辑器中就可以做到对新生成的代码的自动提示? 不生成代 ...

  3. MyBatis自动生成代码示例

    在项目中使用到mybatis时,都会选择自动生成实体类,Mapper,SqlMap这三个东东. 手头上在用的又不方便,找了下网上,其实有很多文章,但有些引用外部文件时不成功,也不方便,所以重新整理了下 ...

  4. MyBatis使用Generator自动生成代码

    MyBatis中,可以使用Generator自动生成代码,包括DAO层. MODEL层 .MAPPING SQL映射文件. 第一步: 配置好自动生成代码所需的XML配置文件,例如(generator. ...

  5. mybatis 自动生成代码(mybatis generator)

    pom.xml 文件配置 引入 mybatis generator <properties> <mysql.connector.version>5.1.44</mysql ...

  6. ButterKnife的使用以及不能自动生成代码问题的解决

    ButterKnife的使用以及不能自动生成代码问题的解决 转载请注明出处:http://www.cnblogs.com/zhengjunfei/p/5910497.html 最近换了个工作刚入职,又 ...

  7. 【MyBatis】MyBatis自动生成代码查询之爬坑记

    前言 项目使用SSM框架搭建Web后台服务,前台后使用restful api,后台使用MyBatisGenerator自动生成代码,在前台使用关键字进行查询时,遇到了一些很宝贵的坑,现记录如下.为展示 ...

  8. mybatis-generator : 自动生成代码

    [参考文章]:mybatis generator自动生成代码时 只生成了insert 而没有其他 [参考文章]:Mybatis Generator最完整配置详解 1. pom <plugin&g ...

  9. mybatis-generator自动生成代码插件

    mybatis自动生成代码(实体类.Dao接口等)是很成熟的了,就是使用mybatis-generator插件. 它是一个开源的插件,使用maven构建最好,可以很方便的执行 插件官方简介: http ...

随机推荐

  1. Azure PowerShell 在ARM环境下使用指定 vhd(本地化后的磁盘) 来创建虚拟机

    #此脚本用于 Azure 存储账户中已有 vhd 镜像文件创建虚拟机,一般用于做好镜像测试 #----------------------------------------------------- ...

  2. (转)IC设计完整流程及工具

    IC的设计过程可分为两个部分,分别为:前端设计(也称逻辑设计)和后端设计(也称物理设计),这两个部分并没有统一严格的界限,凡涉及到与工艺有关的设计可称为后端设计. 前端设计的主要流程: 1.规格制定 ...

  3. codevs 3070 寻找somebody4(水题日常)

     时间限制: 1 s  空间限制: 32000 KB  题目等级 : 黄金 Gold   题目描述 Description 有一天.....sb不见了,有个人要去找他..他发现sb在一个杨辉三角里.. ...

  4. iptables 防火墙

    运行源地址为192.168.10.10-192.168.10.50 这个网段的机器访问本机的20-25还有80.443.6379端口进来的流量 iptables -A INPUT -p tcp -m ...

  5. 命令终端执行python

    windows进入cmd 1.进入cmd窗口,找到存放py文件的地址(如E:\learn_mock) 2.退出python,输入exit() linux下一样

  6. QT_4_QpushButton的简单使用_对象树

    QpushButton的简单使用 1.1 按钮的创建 QPushButton *btn = new QPushButton; 1.2 btn -> setParent(this);设置父窗口 1 ...

  7. 【转】C# WinForm中的Label如何换行

    第一种是把Label的AutoSize属性设为False,手动修改Label的大小.这样的好处是会因内容的长度而自动换行,但是当内容的长度超过所设定的大小时,多出的内容就会无法显示.因此,这种方法适合 ...

  8. Linux下scp报Permission denied错误的解决方法

    sudo vim /etc/ssh/sshd_config 把PermitRootLogin no改成PermitRootLogin yes如果原来没有这行或被注释掉,就直接加上PermitRootL ...

  9. ping ip

    def ip_and_time(): """ get ip to ping from ip.txt then return two list , each ip that ...

  10. nginx 配置虚拟主机访问PHP文件 502错误的解决方法

    最近配置Nginx 服务器虚拟主机 访问目录发现报502错误 百度了很多方法 都不管用  我擦 各种抓狂----- 原本Nginx配置如下: 网上找了很多方法: 查看日志   借助nginx的错误日志 ...