t4 template multi file output

1.Manager.ttinclude

<#@ 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));
        }
    }
} #>

2.connect db to bulk generate model

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>

<#@include file="$(SolutionDir)\Manager.ttinclude"#>
<# var manager = Manager.Create(Host, GenerationEnvironment); #>

<# manager.StartHeader(); #>
using System;
using System.Collections.Generic;
namespace My.Model
{
<# manager.EndBlock(); #>

<#
    string connectionString= "server=localhost;database=UserRight;uid=sa;[email protected];";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();

    string selectQuery ="SET FMTONLY ON; select * from @tableName; SET FMTONLY OFF;";
    SqlCommand command = new SqlCommand(selectQuery,conn);
    SqlDataAdapter ad = new SqlDataAdapter(command);
    System.Data.DataSet ds = new DataSet();
    System.Data.DataTable schema = conn.GetSchema("Tables");

    foreach(System.Data.DataRow row in schema.Rows)
    {
        ds.Tables.Clear();
        string tb_name = row["TABLE_NAME"].ToString();
        command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString());
        ad.FillSchema(ds,SchemaType.Mapped,tb_name);
        manager.StartNewFile(tb_name+".cs");
#>
    /// <summary>
    /// 实体-<#=tb_name#>
    /// </summary>
    public partial class <#=tb_name#>
    {
        <#
        PushIndent("          ");
        foreach (DataColumn dc in ds.Tables[0].Columns)
        {
            WriteLine("public " + dc.DataType.Name + (dc.AllowDBNull && dc.DataType.Name.ToLower() != "string" ? "? ": " ") + dc.ColumnName + " { get; set; }");
        }
        PopIndent();
        #>
    }
<#
        manager.EndBlock();
    }
    conn.Close();
#>

<# manager.StartFooter(); #>
}
<# manager.EndBlock(); #>

<# manager.Process(true); #>

3.generate dao classes

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.xml" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Linq" #>
<#@ output extension=".cs" #>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JiaHe.Entities
{
<#
    string connectionString= "server=localhost;database=JiaHe;uid=sa;[email protected];";
    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();

    System.Data.DataTable schema = conn.GetSchema("Tables");

    foreach(System.Data.DataRow row in schema.Rows)
    {
        string tb_name= row["TABLE_NAME"].ToString();

        string selectQuery =
            @"
            SELECT (case when a.colorder=1 then d.name else null end) 表名, a.colorder 字段序号,a.name 字段名,
            (case when COLUMNPROPERTY( a.id,a.name,‘IsIdentity‘)=1 then ‘√‘else ‘‘ end) 标识,
            (case when (SELECT count(*) FROM sysobjects  WHERE (name in (
            SELECT name FROM sysindexes  WHERE (id = a.id) AND (indid in
            (SELECT indid FROM sysindexkeys  WHERE (id = a.id) AND (colid in
            (SELECT colid FROM syscolumns WHERE (id = a.id) AND (name = a.name)))))))
            AND (xtype = ‘PK‘))>0 then ‘√‘ else ‘‘ end) 主键,b.name 类型,a.length 占用字节数,
            COLUMNPROPERTY(a.id,a.name,‘PRECISION‘) as 长度,
            isnull(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0) as 小数位数,(case when a.isnullable=1 then ‘√‘else ‘‘ end) 允许空,
            isnull(e.text,‘‘) 默认值,isnull(g.[value], ‘ ‘) AS [说明]
            FROM  syscolumns a
            left join systypes b on a.xtype=b.xusertype
            inner join sysobjects d on a.id=d.id and d.xtype=‘U‘ and d.name<>‘dtproperties‘
            left join syscomments e on a.cdefault=e.id
            left join sys.extended_properties g on a.id=g.major_id AND a.colid=g.minor_id
            left join sys.extended_properties f on d.id=f.class and f.minor_id=0
            --where b.name is not null
            --WHERE d.name=‘TestTB‘ --如果只查询指定表,加上此条件
            WHERE d.NAME = ‘" + tb_name + @"‘ --如果只查询指定表,加上此条件
            order by a.id,a.colorder
            ";
        SqlCommand command = new SqlCommand(selectQuery,conn);
        SqlDataAdapter ad = new SqlDataAdapter(command);
        System.Data.DataSet ds = new DataSet();
        ad.Fill(ds);  

        WriteLine("    public partial class " + tb_name);
        WriteLine("    {");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            string fieldType="";
            switch(dr["类型"].ToString()){
                case "bit":
                    fieldType="bool";
                    break;

                case "int":
                    fieldType="int";
                    break;
                case "smallint":
                    fieldType="int";
                    break;
                case "tinyint":
                    fieldType="int";
                    break;
                case "bigint":
                    fieldType="int";
                    break;
                case "float":
                    fieldType="float";
                    break;
                case "double":
                    fieldType="float";
                    break;
                case "decimal":
                    fieldType="float";
                    break;

                case "datetime":
                    fieldType="DateTime";
                    break;
                case "date":
                    fieldType="DateTime";
                    break;
                case "smalldatetime":
                    fieldType="DateTime";
                    break;
                case "timestamp":
                    fieldType="int";
                    break;

                default:
                    fieldType="string";
                    break;
            }
            string temp="        public " + fieldType +" " + dr["字段名"] + " { get; set; }";
            if(!string.IsNullOrEmpty(dr["说明"].ToString()))
                temp += "//"+dr["说明"].ToString();
            WriteLine(temp);
        }
        WriteLine("    }");
    }
    conn.Close();
#>
}

时间: 2024-12-11 18:36:48

t4 template multi file output的相关文章

用T4 Template生成代码

1 T4语法 T4的语法与ASP.NET的方式比较类似.主要包括指令.文本块.控制块. 1.1    指令 指令主要包括template, output, assembly, import, include等类型,用以告诉T4引擎如何编译和运行一个模板.这些指令相当于T4引擎的配置参数. 示例: <#@ template debug="true" hostspecific="true" language="C#" #> 告诉T4引擎控

knockoutjs如何动态加载外部的file作为component中的template数据源

玩过knockoutjs的都知道,有一个强大的功能叫做component,而这个component有个牛逼的地方就是拥有自己的viewmodel和template, 比如下面这样: ko.components.register('message-editor', { viewModel: function(){}, template:"" }); 很显然,viewmodel就是function函数区,而template就是模板区,然后通过register函数将component注册到k

C# Meta Programming - Let Your Code Generate Code - Introduction of The Text Template Transformation Toolkit(T4)

<#@ template language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <# Type[] types_to_generate = new[] { typeof(object), t

[Java in NetBeans] Lesson 17. File Input/Output.

这个课程的参考视频和图片来自youtube. 主要学到的知识点有: We want to handle the bad Error. (e.g bad input / bugs in program) 1. File() : A Java representation of a file. File file = new File("test.txt"); 2. PrintWriter() : Write to a file. Write string into the file. /

[转]MVC实用架构设计(三)——EF-Code First(3):使用T4模板生成相似代码

本文转自:http://www.cnblogs.com/guomingfeng/p/mvc-ef-t4.html 〇.目录 一.前言 二.工具准备 三.T4代码生成预热 (一) 单文件生成:HelloWorld.cs (二) 多文件生成 四.生成数据层实体相关相似代码 (一) 生成准备 (二) 生成实体相关相似代码 生成实体映射配置类 生成实体仓储接口 生成实体仓储实现 五.源码获取 系列导航 一.前言 经过前面EF的<第一篇>与<第二篇>,我们的数据层功能已经较为完善了,但有不少

Metadata file not found - Data.Entity.Model

错误 3 正在编译转换: 未能找到元数据文件“F:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\..\IDE\Microsoft.Data.Entity.Design.DatabaseGeneration.dll” E:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Entity Framework

使用T4模板生成不同部署环境下的配置文件

在开发企业级应用的时候,通常会有不同的开发环境,比如有开发环境,测试环境,正式环境,生产环境等.在一份代码部署到不同环境的时候,不同环境的配置文件可能需要根据目标环境不同而不同.比如在开发环境中,数据库使用的是开发环境的数据库,消息队列也使用的部署在开发机上的消息队列,传统的方式是,由发布或者配置管理员来维护这些不同环境的配置文件.通常,手工的针对不同的环境去修改配置文件容易产生错误. 有很多种不同的方式来针对不同的部署环境生成配置,最笨的方法就是可以维护几套不同的配置文件,然后在编译事件中根据

t4 根据表名数组生成实体

<#@ template debug="false" hostspecific="true" language="C#" #> <#@ assembly name="System.Core.dll" #> <#@ assembly name="System.Data.dll" #> <#@ assembly name="System.Data.DataSe

t4-editor使用方法 Visual T4

原文发布时间为:2011-05-17 -- 来源于本人的百度文章 [由搬家工具导入] http://visualstudiogallery.msdn.microsoft.com/40a887aa-f3be-40ec-a85d-37044b239591  可以这里下载,也可以在 vs的 工具——扩展管理器 里面搜索 安装即可。 引入一些常用的命名空间并使用的方法如下: <#@ template debug="false" hostspecific="false"