首页 > 代码库 > ToolsCodeTemplate使用
ToolsCodeTemplate使用
最近学习使用CodeSmith代码生成器
CodeSmith 是一种语法类似于asp.net的基于模板的代码生成器,程序可以自定义模板,从而减少重复编码的劳动量,提高效率。
作用:CodeSmith 是一种基于模板的代码生成工具,它使用类似于ASP.NET的语法来生成任意类型的代码或文本。与其他许多代码生成工具不同,CodeSmith 不要求您订阅特定的应用程序设计或体系结构。使用 CodeSmith,可以生成包括简单的强类型集合和完整应用程序在内的任何东西。
当您生成应用程序时,您经常需要重复完成某些特定的任务,例如编写数据访问代码或者生成自定义集合。CodeSmith 在这些时候特别有用,因为您可以编写模板自动完成这些任务,从而不仅提高您的工作效率,而且能够自动完成那些最为乏味的任务。CodeSmith 附带了许多模板,包括对应于所有 .NET 集合类型的模板以及用于生成存储过程的模板,但该工具的真正威力在于能够创建自定义模板。
应用:CodeSmith 是一种语法类似于asp.net的基于模板的代码生成器,程序可以自定义模板,从而减少重复编码的劳动量,提高效率。
安装CodeSmith 2.6注册后发现有两个可运行程序CodeSmith Studio.exe和CodeSmith Explorer.exe
CodeSmith Studio.exe用来创建自定义模板
CodeSmith Explorer.exe用来导入模板并且生成代码
打开 CodeSmith Studio.exe,新建一个C#模板。发现有如下类似与asp.net的标识符号
<% %>
<%= %>
<%@ %>
<script runat="template"> </script>
官方站点:http://www.codesmithtools.com/
下面是使用CodeSmith常用的方法
1 using System; 2 using SchemaExplorer; 3 using System.Data; 4 using CodeSmith.Engine; 5 using System.Text.RegularExpressions; 6 7 /// <summary> 8 /// CodeSmith公用方法类 9 /// </summary> 10 public class ToolsCodeTemplate:CodeTemplate 11 { 12 #region 获取Molde类名称 13 /// <summary> 14 /// 获取Molde类名称 15 /// </summary> 16 /// <param name="table">表</param> 17 /// <returns>表名称(表名称即为Model类名称)</returns> 18 public string GetModelClassName(TableSchema table) 19 { 20 string result; 21 if ( table.ExtendedProperties.Contains("ModelName") ) 22 { 23 result = (string)table.ExtendedProperties["ModelName"].Value; 24 return MakePascal(result); 25 } 26 27 if (table.Name.EndsWith("s")) 28 { 29 result = MakeSingle(table.Name); 30 } 31 else 32 { 33 result = table.Name; 34 } 35 36 return MakePascal(result); 37 } 38 #endregion 39 40 #region 获取属性名称 41 /// <summary> 42 /// 获取属性名称 43 /// </summary> 44 /// <param name="column"></param> 45 /// <returns></returns> 46 public string GetPropertyName(ColumnSchema column) 47 { 48 return MakePascal(GetNameFromDBFieldName(column)); 49 } 50 #endregion 51 52 #region 获取从数据库字段得到的名称 53 /// <summary> 54 /// 获取从数据库字段得到的名称 55 /// </summary> 56 /// <param name="column"></param> 57 /// <returns></returns> 58 public string GetNameFromDBFieldName(ColumnSchema column) 59 { 60 return column.Name; 61 } 62 #endregion 63 64 #region 获取属性类型 65 /// <summary> 66 /// 获取属性类型 67 /// </summary> 68 /// <param name="column">列</param> 69 /// <returns>属性类型</returns> 70 public string GetPropertyType(ColumnSchema column) 71 { 72 return GetCSharpTypeFromDBFieldType(column); 73 } 74 #endregion 75 76 #region 获取主键名称 77 /// <summary> 78 /// 获取主键名称 79 /// </summary> 80 /// <param name="TargetTable">表</param> 81 /// <returns>主键名称</returns> 82 public string GetPKName(TableSchema TargetTable) 83 { 84 if (TargetTable.PrimaryKey != null) 85 { 86 if (TargetTable.PrimaryKey.MemberColumns.Count == 1) 87 { 88 return TargetTable.PrimaryKey.MemberColumns[0].Name; 89 } 90 else 91 { 92 throw new Exception("This template will not work on primary keys with more than one member column."); 93 } 94 } 95 else 96 { 97 throw new Exception("This template will only work on tables with a primary key."); 98 } 99 }100 #endregion101 102 #region 获取主键类型103 /// <summary>104 /// 获取主键类型105 /// </summary>106 /// <param name="TargetTable">表</param>107 /// <returns>主键类型</returns>108 public string GetPKType(TableSchema TargetTable)109 {110 if (TargetTable.PrimaryKey != null)111 {112 if (TargetTable.PrimaryKey.MemberColumns.Count == 1)113 {114 return GetCSharpTypeFromDBFieldType(TargetTable.PrimaryKey.MemberColumns[0]);115 }116 else117 {118 throw new ApplicationException("This template will not work on primary keys with more than one member column.");119 }120 }121 else122 {123 throw new ApplicationException("This template will only work on MyTables with a primary key.");124 }125 }126 #endregion127 128 #region 类型转化129 /// <summary>130 /// 获取数据库类型转化为C#类型131 /// </summary>132 /// <param name="column">列</param>133 /// <returns>C#类型的字符串</returns>134 public string GetCSharpTypeFromDBFieldType(ColumnSchema column)135 {136 if (column.Name.EndsWith("TypeCode")) return column.Name;137 string type;138 switch (column.DataType)139 {140 case DbType.AnsiString: type= "string";break;141 case DbType.AnsiStringFixedLength: type= "string";break;142 case DbType.Binary: type= "byte[]";break;143 case DbType.Boolean: type= "bool";break;144 case DbType.Byte: type= "byte";break;145 case DbType.Currency: type= "decimal";break;146 case DbType.Date: type= "DateTime";break;147 case DbType.DateTime: type= "DateTime";break;148 case DbType.Decimal: type= "decimal";break;149 case DbType.Double: type= "double";break;150 case DbType.Guid: type= "Guid";break;151 case DbType.Int16: type= "short";break;152 case DbType.Int32: type= "int";break;153 case DbType.Int64: type= "long";break;154 case DbType.Object: type= "object";break;155 case DbType.SByte: type= "sbyte";break;156 case DbType.Single: type= "float";break;157 case DbType.String: type= "string";break;158 case DbType.StringFixedLength: type= "string";break;159 case DbType.Time: type= "TimeSpan";break;160 case DbType.UInt16: type= "ushort";break;161 case DbType.UInt32: type= "uint";break;162 case DbType.UInt64: type= "ulong";break;163 case DbType.VarNumeric: type= "decimal";break;164 default:165 {166 type= "__UNKNOWN__" + column.NativeType;//未知167 break;168 }169 }170 //是否为Null171 if(column.AllowDBNull && column.SystemType.IsValueType)172 {173 type=type+"?";174 }175 return type;176 }177 /// <summary>178 /// 获取数据库类型转化为C#类型179 /// </summary>180 /// <param name="dbType">DbType的类型</param>181 /// <returns>C#类型的字符串</returns>182 public string GetDBTypeToCSharpType (System.Data.DbType dbType)183 {184 switch (dbType)185 {186 case DbType.AnsiString:return "string";187 case DbType.AnsiStringFixedLength:return "string";188 case DbType.Binary:return "byte[]";189 case DbType.Boolean:return "bool";190 case DbType.Byte:return "byte";191 case DbType.Currency:return "decimal";192 case DbType.Date:return "DateTime";193 case DbType.DateTime:return "DateTime";194 case DbType.DateTime2:return "DateTime";195 case DbType.DateTimeOffset:return "DateTime";196 case DbType.Decimal:return "decimal";197 case DbType.Double:return "double";198 case DbType.Guid:return "Guid";199 case DbType.Int16:return "short";200 case DbType.Int32:return "int";201 case DbType.Int64:return "long";202 case DbType.Object:return "object";203 case DbType.SByte:return "sbyte";204 case DbType.Single:return "float";205 case DbType.String:return "string";206 case DbType.StringFixedLength:return "string";207 case DbType.Time:return "DateTime";208 case DbType.UInt16:return "ushort";209 case DbType.UInt32:return "uint";210 case DbType.UInt64:return "ulong";211 case DbType.VarNumeric:return "decimal";212 case DbType.Xml:return "string";213 default:return "object";214 }215 }216 #endregion217 218 #region 骆驼命名法,帕斯卡命名法和匈牙利命名法219 /// <summary>220 /// 获取首字母大写的字符串221 /// </summary>222 /// <param name="value">字符串(例如:xiangyisheng)</param>223 /// <returns>xiangyisheng => Xiangyisheng</returns>224 public string MakePascal(string value)225 {226 return value.Substring(0, 1).ToUpper() + value.Substring(1);227 }228 /// <summary>229 /// 获取首字母小写的字符串230 /// </summary>231 /// <param name="value">字符串(例如:Xiangyisheng)</param>232 /// <returns>Xiangyisheng => xiangyisheng</returns>233 public string MakeCamel(string value)234 {235 return value.Substring(0, 1).ToLower() + value.Substring(1);236 }237 /// <summary>238 /// 获取小写的字符串239 /// </summary>240 /// <param name="value">字符串(例如:XiangYiSheng)</param>241 /// <returns>XiangYiSheng => xiangyisheng</returns>242 public string MakeSmall(string value)243 {244 return value.ToLower();245 } 246 /// <summary>247 /// 获取单数形式的字符串248 /// </summary>249 /// <param name="name">字符串(例如:Xiangyishengs)</param>250 /// <returns>Xiangyishengs => Xiangyisheng</returns>251 public string MakeSingle(string name)252 {253 Regex plural1 = new Regex("(?<keep>[^aeiou])ies$");254 Regex plural2 = new Regex("(?<keep>[aeiou]y)s$");255 Regex plural3 = new Regex("(?<keep>[sxzh])es$");256 Regex plural4 = new Regex("(?<keep>[^sxzhyu])s$");257 258 if(plural1.IsMatch(name))259 return plural1.Replace(name, "${keep}y");260 else if(plural2.IsMatch(name))261 return plural2.Replace(name, "${keep}");262 else if(plural3.IsMatch(name))263 return plural3.Replace(name, "${keep}");264 else if(plural4.IsMatch(name))265 return plural4.Replace(name, "${keep}");266 267 return name;268 }269 /// <summary>270 /// 获取复数形式的字符串271 /// </summary>272 /// <param name="name">字符串(例如:Xiangyisheng)</param>273 /// <returns>Xiangyisheng => Xiangyishengs</returns>274 public string MakePlural(string name)275 {276 Regex plural1 = new Regex("(?<keep>[^aeiou])y$");277 Regex plural2 = new Regex("(?<keep>[aeiou]y)$");278 Regex plural3 = new Regex("(?<keep>[sxzh])$");279 Regex plural4 = new Regex("(?<keep>[^sxzhy])$");280 281 if(plural1.IsMatch(name))282 return plural1.Replace(name, "${keep}ies");283 else if(plural2.IsMatch(name))284 return plural2.Replace(name, "${keep}s");285 else if(plural3.IsMatch(name))286 return plural3.Replace(name, "${keep}es");287 else if(plural4.IsMatch(name))288 return plural4.Replace(name, "${keep}s");289 290 return name;291 }292 #endregion293 294 #region 打印标题295 /// <summary>296 /// 打印标题297 /// </summary>298 public void PrintHeader()299 {300 Response.WriteLine("//============================================================");301 Response.WriteLine("//http://www.cnblogs.com/xiangyisheng");302 Response.WriteLine("//============================================================");303 Response.WriteLine();304 }305 #endregion306 }
下面是我理解ToolsCodeTemplate测试例子
1 <%-- 2 名称:测试模板 3 作者:长毛象 4 描述:测试模板 5 网址:http://www.cnblogs.com/xiangyisheng 6 --%> 7 <%@ CodeTemplate Language="C#" TargetLanguage="text" Src=http://www.mamicode.com/"ToolsCodeTemplate.cs" Inherits="ToolsCodeTemplate" Debug="False" Description="测试模板" ResponseEncoding="UTF-8" %> 8 <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Default="" Optional="False" Category="Table" Description="源表名" OnChanged="" Editor="" EditorBase="" Serializer="" %> 9 <%@ Assembly Name="SchemaExplorer" %>10 <%@ Import Namespace="SchemaExplorer" %>11 <%@ Import Namespace="System.Data" %>12 <% PrintHeader(); %>13 14 <%--获取Molde类名称 参数:表--%>15 获取Molde类名称:<%= this.GetModelClassName(this.SourceTable) %>16 17 <%--获取属性名称 参数:列--%>18 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>19 获取属性名称:<%=this.GetPropertyName(column)%>20 <%}%>21 22 <%--获取从数据库字段得到的名称 参数:列--%>23 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>24 获取从数据库字段得到的名称:<%=this.GetNameFromDBFieldName(column)%>25 <%}%>26 27 <%--获取属性类型 参数:列--%>28 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>29 获取属性类型:<%=this.GetPropertyType(column)%>30 <%}%>31 32 <%--获取主键名称 参数:表--%>33 获取主键名称:<%= this.GetPKName(this.SourceTable) %>34 35 <%--获取主键类型 参数:表--%>36 获取主键类型:<%= this.GetPKType(this.SourceTable) %>37 38 <%--获取数据库类型转化为C#类型 参数:列--%>39 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>40 获取数据库类型转化为C#类型:<%=this.GetCSharpTypeFromDBFieldType(column)%>41 <%}%>42 43 <%--获取数据库类型转化为C#类型2 参数:列类型--%>44 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>45 获取数据库类型转化为C#类型2:<%=this.GetDBTypeToCSharpType(column.DataType)%>46 <%}%>47 48 <%--获取首字母大写的字符串 参数:字符串--%>49 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>50 获取首字母大写的字符串:<%=this.MakePascal(column.Name)%>51 <%}%>52 53 <%--获取首字母小写的字符串 参数:字符串--%>54 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>55 获取首字母小写的字符串:<%=this.MakeCamel(column.Name)%>56 <%}%>57 58 <%--获取小写的字符串 参数:字符串--%>59 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>60 获取小写的字符串:<%=this.MakeSmall(column.Name)%>61 <%}%>62 63 <%--获取单数形式的字符串 参数:字符串--%>64 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>65 获取单数形式的字符串:<%=this.MakeSingle(column.Name)%>66 <%}%>67 68 <%--获取复数形式的字符串 参数:字符串--%>69 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>70 获取首字母大写的字符串:<%=this.MakePascal(column.Name)%>71 <%}%>
创建生成实体类的模板,代码如下:
1 <%-- 2 Name:实体类 3 Author: Eason.Xiang 4 Description: 5 --%> 6 <%@ CodeTemplate Language="C#" TargetLanguage="C#" Src=http://www.mamicode.com/"ToolsCodeTemplate.cs" Inherits="ToolsCodeTemplate" Debug="False" Description="生成指定Table的实体类(使用原始方式封装字段(Ctrl+R+E))" ResponseEncoding="UTF-8" %> 7 <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Default="" Optional="False" Category="Table" Description="源表名" OnChanged="" Editor="" EditorBase="" Serializer="" %> 8 <%@ Property Name="NameSpace" Type="System.String" Default="Model" Optional="False" Category="NameSpace" Description="命名空间" OnChanged="" Editor="" EditorBase="" Serializer="" %> 9 <%@ Property Name="IsFK" Type="System.Boolean" Default="False" Optional="False" Category="Other" Description="是否处理外键" OnChanged="" Editor="" EditorBase="" Serializer="" %>10 <%@ Property Name="Author" Type="System.String" Default="Jack.Zhou" Optional="False" Category="Other" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>11 <%@ Assembly Name="SchemaExplorer" %>12 <%@ Assembly Name="System.Data" %>13 <%@ Assembly Name="mscorlib" %>14 <%@ Import Namespace="SchemaExplorer" %>15 <%@ Import Namespace="System.Data" %>16 <%@ Import Namespace="System.Collections.Generic" %>17 <% PrintHeader(); %>18 using System;19 using System.Collections.Generic;20 using System.Text;21 namespace <%=this.NameSpace%>22 {23 /// <summary>24 /// 实体类<%=this.GetModelClassName(this.SourceTable)%>25 /// </summary>26 public class <%=this.GetModelClassName(this.SourceTable)%>27 {28 #region 私有字段29 <%foreach(ColumnSchema column in this.SourceTable.ForeignKeyColumns){%>30 <%if(!IsFK){%>31 private <%=this.GetCSharpTypeFromDBFieldType(column)%> _<%=this.MakeCamel(column.Name)%>;32 <%}else{%>33 private <%=this.GetFKClassName(column)%> _<%=this.MakeCamel(column.Name)%>;34 <%}%>35 <%}%>36 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>37 private <%=this.GetCSharpTypeFromDBFieldType(column)%> _<%=this.MakeCamel(column.Name)%>;38 <%}%>39 #endregion40 41 #region 公开属性42 <%foreach(ColumnSchema column in this.SourceTable.ForeignKeyColumns){%>43 <%if(!IsFK){%>44 public <%=this.GetCSharpTypeFromDBFieldType(column)%> <%=this.MakePascal(column.Name)%>45 {46 get{return _<%=this.MakeCamel(column.Name)%>;}47 set{_<%=this.MakeCamel(column.Name)%>=value;}48 }49 <%}else{%>50 public <%=this.GetFKClassName(column)%> <%=this.MakePascal(column.Name)%>51 {52 get{return _<%=this.MakeCamel(column.Name)%>;}53 set{_<%=this.MakeCamel(column.Name)%>=value;}54 }55 <%}%>56 <%}%>57 <%foreach(ColumnSchema column in this.SourceTable.NonForeignKeyColumns){%>58 public <%=this.GetCSharpTypeFromDBFieldType(column)%> <%=this.MakePascal(column.Name)%>59 {60 get{return _<%=this.MakeCamel(column.Name)%>;}61 set{_<%=this.MakeCamel(column.Name)%>=value;}62 }63 <%}%>64 #endregion65 }66 }67 <script runat="template">68 #region 获取外键类名69 public string GetFKClassName(ColumnSchema column)70 {71 foreach(TableKeySchema key in this.SourceTable.ForeignKeys)72 {73 foreach(MemberColumnSchema fk in key.ForeignKeyMemberColumns)74 {75 if(fk.Name==column.Name)76 {77 return this.GetModelClassName(key.PrimaryKeyTable);78 }79 }80 }81 return "";82 }83 #endregion84 </script>
CodeSmith截图
好了,目前大概就学到这里了。(原文:http://www.cnblogs.com/xiangyisheng/p/6208637.html)
ToolsCodeTemplate使用