打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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>

好啦,就这么多啦,能满足我的需求啦。

小结

如果你在看到本文后有什么疑问,请加入博客左上角群,一起交流学习。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
黄聪:如何使用CodeSmith批量生成代码(原创)
OushuDB 数据库基本用法(中)
Primer-Blast介绍
EntityFramework+Wcf 模板 for CodeSmith
CHAPTER 14 在Turbine里使用Velocity - Velocity空间 -...
Exchange2013/2016下通过RDB(恢复数据库)还原用户邮箱数据
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服