用CodeSmith生成自定義模板
當(dāng)生成應(yīng)用程序時(shí),無(wú)論是編寫(xiě)數(shù)據(jù)訪問(wèn)代碼還是生成自定義實(shí)體自定義集合,你會(huì)發(fā)現(xiàn)經(jīng)常需要重復(fù)完成某些特定的任務(wù)。最近用CodeSmith編寫(xiě)了界面層到數(shù)據(jù)庫(kù)訪問(wèn)層的模板以及用于生成存儲(chǔ)過(guò)程的模板,感覺(jué)CodeSmith非常不錯(cuò),不僅有利于提高團(tuán)隊(duì)的工作效率,自動(dòng)完成那些最為乏味的任務(wù),而且有利于讓大家的代碼保持一定的一致性和規(guī)范性。下面詳細(xì)介紹一下如何生成自定義模板(以自定義實(shí)體為列),以作為總結(jié),也希望對(duì)您有所幫助。
第一步是添加模板頭,聲明模板的語(yǔ)言、目標(biāo)語(yǔ)言以及簡(jiǎn)要模板說(shuō)明:
以下是代碼片段: <%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="Template description here." %> |
指明這是一個(gè)C#語(yǔ)言的模板。CodeSmith 包括一個(gè)名為 SchemaExplorer 的特殊的程序集,可用來(lái)從表、存儲(chǔ)過(guò)程或幾乎任何其他 SQL Server對(duì)象生成模板。下面引入該集合和命名空間:
以下是代碼片段: <%@ Assembly Name="System.Data" %> <%@ Import Namespace="System.Data" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> |
第二步,屬性聲明,在這里可聲明將在模板每次運(yùn)行時(shí)指定的屬性,以方便設(shè)置一系列需要傳入的參數(shù):
以下是代碼片段: <%@ Property Name="DataBase" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="aaa" %> |
如上邊所示,在進(jìn)行代碼生成時(shí),在CodeSmith Explorer中選擇模板后生成代碼的窗口中,變量的名稱為DataBase,類型是SchemaExplorer.DatabaseSchema,類別是Context,當(dāng)用戶選中這個(gè)屬性時(shí)對(duì)于屬性的描述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" %> |
如上邊所示,變量的名稱為T(mén)ableName,NameSpace,類型是String,類別是Strings,當(dāng)用戶選中這個(gè)屬性時(shí)對(duì)于屬性的描述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,類別為空(顯示為“雜項(xiàng)”),當(dāng)用戶選中這個(gè)屬性時(shí)對(duì)于屬性的描述Description。
相應(yīng)屬性界面顯示如下圖所示:
第三步,編寫(xiě)C#語(yǔ)言模板類部分代碼。CodeSmith模板腳本格式:
以下是代碼片段: public class CodeTemplateRule |
實(shí)例化類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; } |
函數(shù)作用:輸入數(shù)據(jù)庫(kù)名和表名,得到列集合信息。用內(nèi)部函數(shù)ColumnSchemaCollection可以得到某張表的所有列的集合。
以下是代碼片段: public string GetTableName(string tableName) { int i=tableName.IndexOf("_"); return tableName.Substring(i+1,tableName.Length-(i+1)); } |
函數(shù)作用:對(duì)輸入的表名格式化,得到去掉前綴的表名,如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; } } } |
函數(shù)作用:得到表字段的類型。
以下是代碼片段: 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; } } } |
函數(shù)作用:得到表字段的默認(rèn)值。
以下是代碼片段: public string ConvPropertyName(string name) { return name.Substring(0,1).ToUpper() + name.Substring(1); } |
函數(shù)作用:對(duì)輸入的名稱格式化,得到首字母為大寫(xiě)的名稱,如user,返回User。
第四步,編寫(xiě)實(shí)際生成模板主體的代碼,根據(jù)你需要的格式輸出。代碼如下:
以下是代碼片段: using System; 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運(yùn)行模板 。填寫(xiě)你的參數(shù),運(yùn)行后就得到了你需要的實(shí)體代碼:
以下是引用片段: using System; using System.Collections.Generic; using System.Text; namespace AAA /// Description:BBB實(shí)體 /// public class OrderInfo { /// ///Description /// public OrderInfo() { } //訂單ID #region ///訂單ID /// public int OrderId { get { return m_OrderId; } set { m_OrderId = value; } } /// ///訂單編號(hào) /// 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; } } /// ///購(gòu)買(mǎi)商品合計(jì)金額 /// public decimal MoneyGoods { get { return m_MoneyGoods; } set { m_MoneyGoods = value; } } /// ///是否需要開(kāi)發(fā)票 /// public bool NeedInvoice { get { return m_NeedInvoice; } set { m_NeedInvoice = value; } } /// ///發(fā)表內(nèi)容,包括抬頭、商品名稱、金額等 /// public string InvoiceContent { get { return m_InvoiceContent; } set { m_InvoiceContent = value; } } /// ///是否已開(kāi)發(fā)票 /// 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; } } /// ///開(kāi)始服務(wù)日期 /// public DateTime BeginDate { get { return m_BeginDate; } set { m_BeginDate = value; } } /// ///錄入時(shí)間 /// 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; } } /// ///手機(jī) /// public string Mobile { get { return m_Mobile; } set { m_Mobile = value; } } /// ///聯(lián)系電話 /// 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; } } /// ///訂單狀態(tài) /// public int Status { get { return m_Status; } set { m_Status = value; } } /// ///物流狀態(tài) /// public int DeliverStatus { get { return m_DeliverStatus; } set { m_DeliverStatus = value; } } /// ///是否開(kāi)通下載 /// public bool EnableDownload { get { return m_EnableDownload; } set { m_EnableDownload = value; } } /// ///返還的現(xiàn)金券 /// public decimal PresentMoney { get { return m_PresentMoney; } set { m_PresentMoney = value; } } /// ///贈(zèng)送點(diǎn)券 /// 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; } } /// ///運(yùn)費(fèi) /// 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 由 Eric J. Smith 編寫(xiě),下載地址是:
用戶登錄
還沒(méi)有賬號(hào)?
立即注冊(cè)