用CodeSmith生成自定義模板
當生成應(yīng)用程序時,無論是編寫數(shù)據(jù)訪問代碼還是生成自定義實體自定義集合,你會發(fā)現(xiàn)經(jīng)常需要重復(fù)完成某些特定的任務(wù)。最近用CodeSmith編寫了界面層到數(shù)據(jù)庫訪問層的模板以及用于生成存儲過程的模板,感覺CodeSmith非常不錯,不僅有利于提高團隊的工作效率,自動完成那些最為乏味的任務(wù),而且有利于讓大家的代碼保持一定的一致性和規(guī)范性。下面詳細介紹一下如何生成自定義模板(以自定義實體為列),以作為總結(jié),也希望對您有所幫助。
第一步是添加模板頭,聲明模板的語言、目標語言以及簡要模板說明:
以下是代碼片段: <%@ 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" %> |
第二步,屬性聲明,在這里可聲明將在模板每次運行時指定的屬性,以方便設(shè)置一系列需要傳入的參數(shù):
以下是代碼片段: <%@ 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。
相應(yīng)屬性界面顯示如下圖所示:
第三步,編寫C#語言模板類部分代碼。CodeSmith模板腳本格式:
以下是代碼片段: 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; } |
函數(shù)作用:輸入數(shù)據(jù)庫名和表名,得到列集合信息。用內(nèi)部函數(shù)ColumnSchemaCollection可以得到某張表的所有列的集合。
以下是代碼片段: public string GetTableName(string tableName) { int i=tableName.IndexOf("_"); return tableName.Substring(i+1,tableName.Length-(i+1)); } |
函數(shù)作用:對輸入的表名格式化,得到去掉前綴的表名,如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ù)作用:得到表字段的默認值。
以下是代碼片段: public string ConvPropertyName(string name) { return name.Substring(0,1).ToUpper() + name.Substring(1); } |
函數(shù)作用:對輸入的名稱格式化,得到首字母為大寫的名稱,如user,返回User。
第四步,編寫實際生成模板主體的代碼,根據(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運行模板 。填寫你的參數(shù),運行后就得到了你需要的實體代碼:
以下是引用片段: using System; using System.Collections.Generic; using System.Text; namespace AAA /// Description:BBB實體 /// public class OrderInfo { /// ///Description /// public OrderInfo() { } //訂單ID #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; } } /// ///是否需要開發(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; } } /// ///是否已開發(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; } } /// ///開始服務(wù)日期 /// 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; } } /// ///聯(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; } } /// ///是否開通下載 /// public bool EnableDownload { get { return m_EnableDownload; } set { m_EnableDownload = value; } } /// ///返還的現(xiàn)金券 /// 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 由 Eric J. Smith 編寫,下載地址是:
用戶登錄
還沒有賬號?
立即注冊