CodeSmith模板代碼生成實戰詳解


前言

公司項目是基於soa面向服務的架構思想開發的,項目分解眾多子項目是必然的。然而子項目的架子結構種類也過多的話,就會對后期的開發維護產生一鍋粥的感覺。為了盡可能的在結構層避免出現這種混亂的現象,我們就做了一個決定,使用一個統一的架子結構,讓項目管理變的簡單起來。

這樣一來,結構中各層就會有很多重復的代碼或者重復的邏輯出現,為啦提高開發效率,節約開發時間,我們采用了codesmith根據自定義模板,生成代碼功能。讓單表的增刪改查功能從數據訪問層到ui展示層一鍵批量生成。下面就開始我的codeSmith模板編寫歷程回顧。

CodeSmith安裝下載

官網地址:http://www.codesmithtools.com

下載地址:http://www.codesmithtools.com/downloads

我使用的,帶破解注冊工具的codesmith鏈接:http://pan.baidu.com/s/1dDdndsd

傻瓜式安裝,不做介紹。只不過你安裝完需要很多碼。那么煩啦,就用我百度雲里面的。帶注冊軟件,安裝完之后,不要急於打開codesmith,先去用注冊軟件注冊下。

安裝完成,破解成功。

打開codesmith主界面如下。

 

Note:打開新建Csharp template,然后后綴名為cst的就是模板文件,自己寫的模板代碼,就在這種后綴格式的文件中。然后光標放在模板文件中,F5即可生成你要代碼的文件。

寫自己的codesmith模板代碼。

1、自定義參數模板

Note:從這里我們能看到參數的聲明,與基本語法的使用規則,需帶<%%>。熟悉之后,在右下角給參數賦值,然后光標放入模板中,點擊f5生成代碼,看下,推敲下。

2、遍歷數據庫中表的模板

 

Note:圖片展示的是怎么設置數據庫配置

模板代碼如下

<%--引入c#模板--%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create an enum of tables." %>
<%--聲明數據庫的參數,在左下角的Database屬性中,選擇要操作的數據庫名稱--%>
<%@ Property Category="Database" Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Optional="False" Description="Database the table enums will come from." %>
<%--引入下面的類庫,操作數據庫必備的。不要糾結加入就行啦。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%--SourceDatabase, 是你選擇數據庫的屬性類,涵蓋數據庫的名稱,創建時間,字符串鏈接,描述等等,自己可以點點看 --%>
public enum <%=SourceDatabase.Name %>Tables
{
<%-- 遍歷數據庫中的表集合 --%>
<% for(int x = 0; x < SourceDatabase.Tables.Count; x++) 
{ 
    TableSchema table = SourceDatabase.Tables[x];
    if (x < SourceDatabase.Tables.Count -1)
        //輸出表名,這里是c#的注釋,不會被寫進生成的代碼中。\t為換行符。
        Response.WriteLine("\t{0},", table.Name);
    else
        Response.WriteLine("\t{0}", table.Name);
}
%>    
}

3、遍歷數據庫表中的字段,聲明並使用自定義函數

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create a list of properties from database table." %>
<%--聲明數據庫表的參數,在左下角的表屬性中,選擇要操作的數據庫表--%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
<%--引入system類型轉為c#的數據類型的映射字典 --%>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%--引入下面的類庫,操作數據庫必備的。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%--遍歷數據庫表的字段屬性--%>
<% foreach (ColumnSchema column in this.SourceTable.Columns) {  %>
<%--拼接字符串,輸出c#中實體的屬性--%>
public <%= ControlType(CSharpAlias[column.SystemType.FullName]) %> <%= StringUtil.ToPascalCase(column.Name) %>{ get; set; }

<% } %>
<script runat="template">
 //如果類型為int,或datetime類型輸出可空類型
 public string ControlType(object val)
 {
     var ty=val.ToString();
     if(ty=="int")
     {
         return "int?";
     }
     if(ty=="System.DateTime")
     {
         return "System.DateTime?";
     }
     return ty;
 }
</script>

4、批量生成文件,並指定生成文件位置

 

代碼如下

<%@ Template Language="C#" TargetLanguage="Text" %>
<%-- 注冊要生成的模板 --%>
<%@ Register Name="TableEnumTemplate" Template="TableEnum.cst" MergeProperties="Flase" ExcludeProperties=""%>
<%@ Register Name="TableClumTemplate" Template="TableProperties.cst" MergeProperties="Flase" ExcludeProperties=""%>

<%--聲明數據庫的參數,在左下角的Database屬性中,選擇要操作的數據庫名稱--%>
<%@ Property Category="Database" Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Optional="False" Description="Database the table enums will come from." %>
<%--Type數據類型為TableSchema,表明參數Table是一個表對象。--%>
<%@ Property Name="SourceTable" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>
<%-- 執行輸出文件的函數 --%>
<% this.OutPutFile(); %>
<script runat="template">
    //輸出文件
    private void OutPutFile()
    {
        //生成列舉表名的模板
        CodeTemplate table =new TableEnumTemplate();
        //指定輸出路徑
        string tableFilePath = OutputDirectory +"\\"+ this.SourceDatabase.Name +".cs";
        //給子模板參數賦值
        table.SetProperty("SourceDatabase",this.SourceDatabase);
        table.RenderToFile(tableFilePath,true);
        
        //生成列表表字段的模板
        CodeTemplate cloumn =new TableClumTemplate();
        //指定輸出路徑
        string cloumnFilePath = OutputDirectory +"\\"+ this.SourceTable.Name +".cs";
         //給子模板參數賦值
        cloumn.SetProperty("SourceTable",this.SourceTable);
        cloumn.RenderToFile(cloumnFilePath,true);
    }
    //解決方案輸出路徑
    private string Directory = String.Empty;
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] 
    [Optional, NotChecked]
    [DefaultValue("")]
    public string OutputDirectory 
    { 
        get
        {
            return Directory;
        }
        set
        {
            if (value.EndsWith("\\")) value = value.Substring(0, value.Length -1);
            Directory = value;
        } 
    }
</script>

數據庫表生成md文檔模板

 

<%--目標語言C#--%>
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="" Debug="True" ResponseEncoding="UTF-8"%>

<%--Type數據類型為TableSchema,表明參數Table是一個表對象。--%>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>

<%--引入數據庫操作組件--%>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
### <%=Table.FullName %>表描述

|字段名|數據類型|是否可空|數據庫類型|長度|描述|
|--|--|--|--|--|--|
<%for(int i=0;i<Table.Columns.Count;i++){%>
|<%=Table.Columns[i].Name.ToString()%>|<%=Table.Columns[i].SystemType.ToString()%>|<%=Table.Columns[i].AllowDBNull?"Yes":"No" %> |<%=Table.Columns[i].NativeType.ToString() %>|<%=Table.Columns[i].Size %>|<%=Table.Columns[i].Description.ToString()%>|
<%}%>        

 

  

 

好啦,就這么多啦,能滿足我的需求啦。

小結

如果你在看到本文后有什么疑問,請加入博客左上角群,一起交流學習。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM