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#的注释,不会被写进生成的代码中。 为换行符。 Response.WriteLine(" {0},", table.Name); else Response.WriteLine(" {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  return Directory; 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()% | %}%