用CodeSmith生成自定义模板

  当生成应用程序时,无论是编写数据访问代码还是生成自定义实体自定义集合,你会发现经常需要重复完成某些特定的任务。最近用CodeSmith编写了界面层到数据库访问层的模板以及用于生成存储过程的模板,感觉CodeSmith非常不错,不仅有利于提高团队的工作效率,自动完成那些最为乏味的任务,而且有利于让大家的代码保持一定的一致性和规范性。下面详细介绍一下如何生成自定义模板(以自定义实体为列),以作为总结,也希望对您有所帮助。

第一步是添加模板头,声明模板的语言、目标语言以及简要模板说明:   

以下是代码片段:
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="Template description here." %>

指明这是一个C#语言的模板。CodeSmith 包括一个名为 SchemaExplorer 的特殊的程序集,可用来从表、存储过程或几乎任何其他 SQL Server对象生成模板。下面引入该集合和命名空间:

以下是代码片段:
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="System.Data" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>

第二步,属性声明,在这里可声明将在模板每次运行时指定的属性,以方便设置一系列需要传入的参数:

以下是代码片段:
<%@ Property Name="DataBase" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="aaa" %>

如上边所示,在进行代码生成时,在CodeSmith Explorer中选择模板后生成代码的窗口中,变量的名称为DataBase,类型是SchemaExplorer.DatabaseSchema,类别是Context,当用户选中这个属性时对于属性的描述Description。

以下是代码片段:
<%@ Property Name="TableName" Type="System.String" Default="" Optional="False" Category="Strings" Description="bbb" %>
<%@ Property Name="NameSpace" Type="System.String"  Default="" Optional="True" Category="Strings" Description="cccc" %>

如上边所示,变量的名称为TableName,NameSpace,类型是String,类别是Strings,当用户选中这个属性时对于属性的描述Description。

以下是代码片段:
<%@ Property Name="Author" Type="System.String" Default="Author" Optional="False" Category="" Description="??" %>
<%@ Property Name="Description" Type="System.String" Default="Description" Optional="False" Category="" Description="?????" %>

如上面所示,变量的名称为Author,Description,类型是String,类别为空(显示为“杂项”),当用户选中这个属性时对于属性的描述Description。

相应属性界面显示如下图所示:

 

第三步,编写C#语言模板类部分代码。CodeSmith模板脚本格式:

以下是代码片段:
CodeTemplateRule rule=new CodeTemplateRule();

        public class CodeTemplateRule
        {

实例化类CodeTemplateRule。

以下是代码片段:
    public ColumnSchemaCollection GetColumnCollection(DatabaseSchema dataBase,string tableName)
    {
        TableSchemaCollection tables = new TableSchemaCollection(dataBase.Tables);
        ColumnSchemaCollection columns=null;
        for(int i=0;i        {
            if(tables[i].Name.ToUpper()==tableName.ToUpper())
            {
                TableSchema ts=tables[i];
                columns=new ColumnSchemaCollection(ts.Columns);
            }
        }
        return columns;
    }

 函数作用:输入数据库名和表名,得到列集合信息。用内部函数ColumnSchemaCollection可以得到某张表的所有列的集合。

以下是代码片段:
    public string GetTableName(string tableName)
    {
        int i=tableName.IndexOf("_");
        return tableName.Substring(i+1,tableName.Length-(i+1));
    }

 函数作用:对输入的表名格式化,得到去掉前缀的表名,如PE_User,返回User。

以下是代码片段:
    public string GetType(ColumnSchema column)
    {
        if (column.Name.EndsWith("TypeCode")) return column.Name;
       
        switch (column.DataType)
        {
            case DbType.AnsiString: return "string";
            case DbType.AnsiStringFixedLength: return "string";
            case DbType.Binary: return "byte[]";
            case DbType.Boolean: return "bool";
            case DbType.Byte: return "int";
            case DbType.Currency: return "decimal";
            case DbType.Date: return "DateTime";
            case DbType.DateTime: return "DateTime";
            case DbType.Decimal: return "decimal";
            case DbType.Double: return "double";
            case DbType.Guid: return "Guid";
            case DbType.Int16: return "short";
            case DbType.Int32: return "int";
            case DbType.Int64: return "long";
            case DbType.Object: return "object";
            case DbType.SByte: return "sbyte";
            case DbType.Single: return "float";
            case DbType.String: return "string";
            case DbType.StringFixedLength: return "string";
            case DbType.Time: return "TimeSpan";
            case DbType.UInt16: return "ushort";
            case DbType.UInt32: return "uint";
            case DbType.UInt64: return "ulong";
            case DbType.VarNumeric: return "decimal";
            default:
            {
                return "__UNKNOWN__" + column.NativeType;
            }
        }
    }

函数作用:得到表字段的类型。

以下是代码片段:
    public string GetDefaultValue(ColumnSchema column)
    {
        if (column.Name.EndsWith("TypeCode")) return column.Name;
       
        switch (column.DataType)
        {
            case DbType.AnsiString: return "/"/"";
            case DbType.AnsiStringFixedLength: return "/"/"";
            case DbType.Binary: return "null";
            case DbType.Boolean: return "false";
            case DbType.Byte: return "0";
            case DbType.Currency: return "0";
            case DbType.Date: return "DateTime.Parse(/"1900-1-1/")";
            case DbType.DateTime: return "DateTime.Parse(/"1900-1-1/")";
            case DbType.Decimal: return "0";
            case DbType.Double: return "0";
            case DbType.Guid: return "Guid.NewGuid().ToString()";
            case DbType.Int16: return "0";
            case DbType.Int32: return "0";
            case DbType.Int64: return "0";
            case DbType.Object: return "/"/"";
            case DbType.SByte: return "0";
            case DbType.Single: return "0";
            case DbType.String: return "/"/"";
            case DbType.StringFixedLength: return "";
            case DbType.Time: return "DateTime.Parse(/"1900-1-1/")";
            case DbType.UInt16: return "0";
            case DbType.UInt32: return "0";
            case DbType.UInt64: return "0";
            case DbType.VarNumeric: return "0";
            default:
            {
                return "__UNKNOWN__" + column.NativeType;
            }
        }
    }

函数作用:得到表字段的默认值。

以下是代码片段:
    public string ConvPropertyName(string name)
    {
        return name.Substring(0,1).ToUpper() +
            name.Substring(1);
    }

函数作用:对输入的名称格式化,得到首字母为大写的名称,如user,返回User。

第四步,编写实际生成模板主体的代码,根据你需要的格式输出。代码如下:

以下是代码片段:

using System;
using System.Collections.Generic;
using System.Text;

namespace PowerEasy.Model.<%= NameSpace %>
{
    ///


    /// Description:<%= Description %>
    ///

    public class <%= rule.ConvPropertyName(rule.GetTableName(TableName)) %>Info
    {
        ///
        ///<%= Description %>
        ///

        public <%= rule.ConvPropertyName(rule.GetTableName(TableName)) %>Info()
        {
        } 
 
      <%
       ColumnSchemaCollection columns=rule.GetColumnCollection(DataBase,TableName);
       for(int i=0;i       {
        Response.Write("        //"+columns[i].Description+"/r/n");
        Response.Write("        private "+rule.GetType(columns[i])+" m_"+columns[i].Name+";/r/n");
       }
      %> 
 
     #region
      <%
       for(int i=0;i       {
      %>
        ///
        ///<%= columns[i].Description %>
        ///

        public <%= rule.GetType(columns[i]) %> <%= rule.ConvPropertyName(columns[i].Name) %>
        {
            get { return m_<%= columns[i].Name %>; }
            set { m_<%= columns[i].Name %>=value; }
        }
      <%  
       }
      %> 
          #endregion
    }
}

最后,CodeSmithStudio.exe运行模板  。填写你的参数,运行后就得到了你需要的实体代码:

以下是引用片段:
using System;
using System.Collections.Generic;
using System.Text;

namespace AAA
{
    ///


    /// Description:BBB实体
    ///

    public class OrderInfo
    {
        ///
        ///Description
        ///

        public OrderInfo()
        {
        }

        //订单ID
        private int m_OrderId;
        //订单编号
        private string m_OrderNum;
        //用户名
        private string m_UserName;
        //代理商名
        private string m_AgentName;
        //客户ID
        private int m_ClientId;
        //订单总金额
        private decimal m_MoneyTotal;
        //购买商品合计金额
        private decimal m_MoneyGoods;
        //是否需要开发票
        private bool m_NeedInvoice;
        //发表内容,包括抬头、商品名称、金额等
        private string m_InvoiceContent;
        //是否已开发票
        private bool m_Invoiced;
        //备注
        private string m_Remark;
        //已收款
        private decimal m_MoneyReceipt;
        //开始服务日期
        private DateTime m_BeginDate;
        //录入时间
        private DateTime m_InputTime;
        //受货人姓名
        private string m_ContacterName;
        //收货人地址
        private string m_Address;
        //邮编
        private string m_ZipCode;
        //手机
        private string m_Mobile;
        //联系电话
        private string m_Phone;
        //EMAIL
        private string m_Email;
        //付款方式
        private int m_PaymentType;
        //送货方式
        private int m_DeliverType;
        //订单状态
        private int m_Status;
        //物流状态
        private int m_DeliverStatus;
        //是否开通下载
        private bool m_EnableDownload;
        //返还的现金券
        private decimal m_PresentMoney;
        //赠送点券
        private int m_PresentPoint;
        //得到的积分
        private int m_PresentExp;
        //付款方式的折扣
        private double m_Discount_Payment;
        //运费
        private decimal m_Charge_Deliver;
        private string m_ClientName;

        #region
        ///


        ///订单ID
        ///

        public int OrderId
        {
            get { return m_OrderId; }
            set { m_OrderId = value; }
        }
        ///
        ///订单编号
        ///

        public string OrderNum
        {
            get { return m_OrderNum; }
            set { m_OrderNum = value; }
        }
        ///
        ///用户名
        ///

        public string UserName
        {
            get { return m_UserName; }
            set { m_UserName = value; }
        }
        ///
        ///代理商名
        ///

        public string AgentName
        {
            get { return m_AgentName; }
            set { m_AgentName = value; }
        }
        ///
        ///客户ID
        ///

        public int ClientId
        {
            get { return m_ClientId; }
            set { m_ClientId = value; }
        }
        ///
        ///订单总金额
        ///

        public decimal MoneyTotal
        {
            get { return m_MoneyTotal; }
            set { m_MoneyTotal = value; }
        }
        ///
        ///购买商品合计金额
        ///

        public decimal MoneyGoods
        {
            get { return m_MoneyGoods; }
            set { m_MoneyGoods = value; }
        }
        ///
        ///是否需要开发票
        ///

        public bool NeedInvoice
        {
            get { return m_NeedInvoice; }
            set { m_NeedInvoice = value; }
        }
        ///
        ///发表内容,包括抬头、商品名称、金额等
        ///

        public string InvoiceContent
        {
            get { return m_InvoiceContent; }
            set { m_InvoiceContent = value; }
        }
        ///
        ///是否已开发票
        ///

        public bool Invoiced
        {
            get { return m_Invoiced; }
            set { m_Invoiced = value; }
        }
        ///
        ///备注
        ///

        public string Remark
        {
            get { return m_Remark; }
            set { m_Remark = value; }
        }
        ///
        ///已收款
        ///

        public decimal MoneyReceipt
        {
            get { return m_MoneyReceipt; }
            set { m_MoneyReceipt = value; }
        }
        ///
        ///开始服务日期
        ///

        public DateTime BeginDate
        {
            get { return m_BeginDate; }
            set { m_BeginDate = value; }
        }
        ///
        ///录入时间
        ///

        public DateTime InputTime
        {
            get { return m_InputTime; }
            set { m_InputTime = value; }
        }
        ///
        ///受货人姓名
        ///

        public string ContacterName
        {
            get { return m_ContacterName; }
            set { m_ContacterName = value; }
        }
        ///
        ///收货人地址
        ///

        public string Address
        {
            get { return m_Address; }
            set { m_Address = value; }
        }
        ///
        ///邮编
        ///

        public string ZipCode
        {
            get { return m_ZipCode; }
            set { m_ZipCode = value; }
        }
        ///
        ///手机
        ///

        public string Mobile
        {
            get { return m_Mobile; }
            set { m_Mobile = value; }
        }
        ///
        ///联系电话
        ///

        public string Phone
        {
            get { return m_Phone; }
            set { m_Phone = value; }
        }
        ///
        ///EMAIL
        ///

        public string Email
        {
            get { return m_Email; }
            set { m_Email = value; }
        }
        ///
        ///付款方式
        ///

        public int PaymentType
        {
            get { return m_PaymentType; }
            set { m_PaymentType = value; }
        }
        ///
        ///送货方式
        ///

        public int DeliverType
        {
            get { return m_DeliverType; }
            set { m_DeliverType = value; }
        }
        ///
        ///订单状态
        ///

        public int Status
        {
            get { return m_Status; }
            set { m_Status = value; }
        }
        ///
        ///物流状态
        ///

        public int DeliverStatus
        {
            get { return m_DeliverStatus; }
            set { m_DeliverStatus = value; }
        }
        ///
        ///是否开通下载
        ///

        public bool EnableDownload
        {
            get { return m_EnableDownload; }
            set { m_EnableDownload = value; }
        }
        ///
        ///返还的现金券
        ///

        public decimal PresentMoney
        {
            get { return m_PresentMoney; }
            set { m_PresentMoney = value; }
        }
        ///
        ///赠送点券
        ///

        public int PresentPoint
        {
            get { return m_PresentPoint; }
            set { m_PresentPoint = value; }
        }
        ///
        ///得到的积分
        ///

        public int PresentExp
        {
            get { return m_PresentExp; }
            set { m_PresentExp = value; }
        }
        ///
        ///付款方式的折扣
        ///

        public double DiscountPayment
        {
            get { return m_Discount_Payment; }
            set { m_Discount_Payment = value; }
        }
        ///
        ///运费
        ///

        public decimal ChargeDeliver
        {
            get { return m_Charge_Deliver; }
            set { m_Charge_Deliver = value; }
        }
        ///
        ///客户姓名
        ///

        public string ClientName
        {
            get { return m_ClientName; }
            set { m_ClientName = value; }
        }
        #endregion
    }
}

你可能感兴趣的:(用CodeSmith生成自定义模板)