CodeSmith自己动手写模板

CodeSmith学习笔记------

1.新建一个Code Smith Generator Template(C sharp)

2.一些常见标签的解释:

①外部变量:

<%@ Property Name="SampleStringProperty" Default="SomeValue" Type="System.String" %>

表示定义一个string类型的外部变量,在需要在生成的时候才输入,此属性有默认值,也可以由用户在右下角的属性栏里修改属性的值。

还有Optional:是否允许为空(即不输入),Category:是说你声明的这个属性的类别(CodeSmith会按分类分开展示让你输入)。

②与数据库交互

CodeSmith与数据库的联系,在CodeSmith中自带一个程序集SchemaExplorer.dll,这个程序集中的类主要用于获取数据库中各种对象的结构。

1 <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Optional="False" Description="源表名" %>
2
3 <%@ Property Name="SourceDB" Type="SchemaExplorer.DatabaseSchema" Optional="False" %>
4
5 <%@ Assembly Name="SchemaExplorer" %>
6
7 <%@ Import Namespace="SchemaExplorer" %>

Assembly:引用程序集,Import:相当于using命名空间。
Type="SchemaExplorer.DatabaseSchema"此类型会在属性栏生成一个数据库的选择框,Type="SchemaExplorer.TableSchema"即表的选择框。③自定义方法:
1 <script runat="template">
2 // My methods here.
3 public string SampleMethod()
4 {
5   return "Method output.";
6 }
7 </script>
<script runat="template"></script>标签内写的是自定义函数(C#代码)④模板部分书写:C#代码要用<%%>包括,值类型要使用<%=%>例如:生成一个Model层的模板
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4
 5 Namespace Model
 6 {
 7     Class <%=TargetTable.Name%>
 8     {
 9         <%  for (int i=0;i<TargetTable.Columns.Count;i++)
10         {
11             SchemaExplorer.ColumnSchema col = TargetTable.Columns[i];%>
12             public <%=col.SystemType%> <%=col.Name%>{get;set;}
13       <%}%>
14     }
15 }

⑤一份完整的DAL的模板示例:

  1 <%@ CodeTemplate Language="C#" TargetLanguage="C#"
  2     Src="ToolsCodeTemplate.cs" Inherits="ToolsCodeTemplate"%>
  3 <%@ Property Name="TargetTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="TargetTable that the object is based on." %>
  4 <%@ Property Name="ModelsNamespace" Default="MyOffice.Models" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
  5 <%@ Property Name="DALNamespace" Default="MyOffice.DAL" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
  6 <%@ Property Name="DALClassNameSurfix" Default="Service" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
  7 <%@ Assembly Name="SchemaExplorer" %>
  8 <%@ Assembly Name="System.Data" %>
  9 <%@ Import Namespace="SchemaExplorer" %>
 10 <%@ Import Namespace="System.Data" %>
 11 <%@ Import Namespace="System.Text.RegularExpressions" %>
 12 <% PrintHeader(); %>
 13 using System;
 14 using System.Collections.Generic;
 15 using System.Text;
 16 using System.Data;
 17 using System.Data.SqlClient;
 18 using <%= ModelsNamespace %>;
 19
 20 namespace <%= DALNamespace %>
 21 {
 22     public partial class <%= GetDALClassName() %>
 23     {
 24         <%-- public static Book AddBook(Book book) --%>
 25         public <%= GetModelClassName() %> Add
 26             (<%= GetModelClassName() %> <%= GetModelParamName() %>)
 27         {
 28             <%if(IsIdentityPK())
 29             {%>
 30                 string sql ="<%= GetAutoIncInsertSQLLine()%>";
 31                 SqlParameter[] para = new SqlParameter[]
 32                     {
 33                         <%
 34                         for(int i=0; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
 35                         {
 36                             ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i];
 37
 38                         %>
 39                         new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>)),
 40                         <%
 41                         }
 42                         %>
 43                     };
 44
 45                 <%= GetPKPropertyType() %> newId = (<%= GetPKPropertyType() %>)SqlHelper.ExecuteScalar(sql, para);
 46                 return GetBy<%= GetPKPropertyName() %>(newId);
 47             <%}else
 48             {%>
 49                 string sql ="<%= GetCommonInsertSQLLine()%>";
 50                 SqlParameter[] para = new SqlParameter[]
 51                     {
 52                         <%
 53                         for(int i=0; i<TargetTable.Columns.Count; i++)
 54                         {
 55                             ColumnSchema column = TargetTable.Columns[i];
 56                         %>
 57                         new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>)),
 58                         <%
 59                         }
 60                         %>
 61                     };
 62                 SqlHelper.ExecuteNonQuery(sql, para);
 63                 return <%= GetModelParamName() %>;
 64             <%}%>
 65         }
 66
 67         <%-- public static bool DeleteBookById(int id) --%>
 68         public int DeleteBy<%= GetPKPropertyName() %>(<%= GetPKPropertyType() %> <%= GetPKParamName() %>)
 69         {
 70             string sql = "DELETE <%= TargetTable.Name %> WHERE <%= GetPKPropertyName() %> = @<%= GetPKPropertyName() %>";
 71
 72            SqlParameter[] para = new SqlParameter[]
 73             {
 74                 new SqlParameter("@<%= GetPKName() %>", <%= GetPKParamName() %>)
 75             };
 76
 77             return SqlHelper.ExecuteNonQuery(sql, para);
 78         }
 79
 80
 81         <%-- public static bool ModifyBook(Book book) --%>
 82         public int Update(<%= GetModelClassName() %> <%= GetModelParamName() %>)
 83         {
 84             string sql =
 85                 "UPDATE <%= TargetTable.Name %> " +
 86                 "SET " +
 87             " <%= TargetTable.NonPrimaryKeyColumns[0].Name %> = @<%= TargetTable.NonPrimaryKeyColumns[0].Name %>"
 88             <%
 89             for(int i=1; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
 90             {
 91                 ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i];
 92             %>
 93                 +", <%= column.Name %> = @<%= column.Name %>"
 94             <%
 95             }
 96             %>
 97
 98             +" WHERE <%= GetPKName() %> = @<%= GetPKName() %>";
 99
100
101             SqlParameter[] para = new SqlParameter[]
102             {
103                 new SqlParameter("@<%= GetPKName() %>", <%= GetModelParamName() %>.<%= GetPKName() %>)
104                 <%
105                 for(int i=0; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
106                 {
107                     ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i];
108                 %>
109                     ,new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>))
110                 <%
111                 }
112                 %>
113             };
114
115             return SqlHelper.ExecuteNonQuery(sql, para);
116         }
117
118         <%-- public static Book GetBookById(int id) --%>
119         public <%= GetModelClassName() %> GetBy<%= GetPKPropertyName() %>(<%= GetPKPropertyType() %> <%= GetPKParamName() %>)
120         {
121             string sql = "SELECT * FROM <%= TargetTable.Name %> WHERE <%= GetPKPropertyName() %> = @<%= GetPKPropertyName() %>";
122             using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql, new SqlParameter("@<%= GetPKPropertyName() %>", <%= GetPKParamName() %>)))
123             {
124                 if (reader.Read())
125                 {
126                     return ToModel(reader);
127                 }
128                 else
129                 {
130                     return null;
131                 }
132                }
133         }
134
135         public <%= GetModelClassName() %> ToModel(SqlDataReader reader)
136         {
137             <%= GetModelClassName() %> <%= GetModelParamName() %> = new <%= GetModelClassName() %>();
138
139             <% foreach(ColumnSchema column in TargetTable.Columns) %>
140             <% { %>
141             <%= GetModelParamName() %>.<%= GetPropertyName(column) %> = (<%=GetPropertyType(column)%>)ToModelValue(reader,"<%=column.Name%>");
142             <% } %>
143             return <%= GetModelParamName() %>;
144         }
145
146         public int GetTotalCount()
147         {
148             string sql = "SELECT count(*) FROM <%= TargetTable.Name %>";
149             return (int)SqlHelper.ExecuteScalar(sql);
150         }
151
152         public IEnumerable<<%= GetModelClassName() %>> GetPagedData(int minrownum,int maxrownum)
153         {
154             string sql = "SELECT * from(SELECT *,row_number() over(order by <%=this.GetPKName()%>) rownum FROM <%= TargetTable.Name %>) t where rownum>[email protected] and rownum<[email protected]";
155             using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql,
156                 new SqlParameter("@minrownum",minrownum),
157                 new SqlParameter("@maxrownum",maxrownum)))
158             {
159                 return ToModels(reader);
160             }
161         }
162
163         public IEnumerable<<%= GetModelClassName() %>> GetAll()
164         {
165             string sql = "SELECT * FROM <%= TargetTable.Name %>";
166             using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql))
167             {
168                 return ToModels(reader);
169             }
170         }
171
172         protected IEnumerable<<%= GetModelClassName() %>> ToModels(SqlDataReader reader)
173         {
174             var list = new List<<%= GetModelClassName() %>>();
175             while(reader.Read())
176             {
177                 list.Add(ToModel(reader));
178             }
179             return list;
180         }
181
182         protected object ToDBValue(object value)
183         {
184             if(value==null)
185             {
186                 return DBNull.Value;
187             }
188             else
189             {
190                 return value;
191             }
192         }
193
194         protected object ToModelValue(SqlDataReader reader,string columnName)
195         {
196             if(reader.IsDBNull(reader.GetOrdinal(columnName)))
197             {
198                 return null;
199             }
200             else
201             {
202                 return reader[columnName];
203             }
204         }
205     }
206 }
207 <script runat="template">
208 public bool IsIdentityPK()
209 {
210     foreach(ColumnSchema column in TargetTable.Columns)
211     {
212         if((bool)column.ExtendedProperties["CS_IsIdentity"].Value)
213         {
214             return true;
215         }
216     }
217     return false;
218 }
219
220 ///////////////////////////////////////////////////////////////
221 // CLASS NAMES by Shen Bo
222 ///////////////////////////////////////////////////////////////
223 // UserService
224 public string GetDALClassName()
225 {
226     return     GetModelClassName() + DALClassNameSurfix;
227 }
228 // User
229 public string GetModelClassName()
230 {
231     return     GetModelClassName(TargetTable);
232 }
233 // user
234 public string GetModelMemberVarName()
235 {
236     return GetModelParamName();
237 }
238 // user
239 public string GetModelParamName()
240 {
241     return MakeCamel(GetModelClassName());
242 }
243
244
245 ///////////////////////////////////////////////////////////////
246 // INSERT SQL LINES by Shen Bo
247 ///////////////////////////////////////////////////////////////
248 public string GetAutoIncInsertSQLLine()
249 {
250     string result;
251     result = "INSERT INTO " + TargetTable.Name + " (";
252     foreach(ColumnSchema column in TargetTable.NonPrimaryKeyColumns)
253     {
254         result += column.Name + ", ";
255     }
256     result = result.Substring(0, result.Length-2);
257     result += ") ";
258     result+=" output inserted."+GetPKName();
259     result += " VALUES (";
260     foreach(ColumnSchema column in TargetTable.NonPrimaryKeyColumns)
261     {
262         result += "@" + column.Name + ", ";
263     }
264     result = result.Substring(0, result.Length-2);
265     result += ")";
266     return result;
267 }
268
269 public string GetCommonInsertSQLLine()
270 {
271     string result;
272     result = "INSERT INTO " + TargetTable.Name + " (";
273     foreach(ColumnSchema column in TargetTable.Columns)
274     {
275         result += column.Name + ", ";
276     }
277     result = result.Substring(0, result.Length-2);
278     result += ") ";
279     result += " VALUES (";
280     foreach(ColumnSchema column in TargetTable.Columns)
281     {
282         result += "@" + column.Name + ", ";
283     }
284     result = result.Substring(0, result.Length-2);
285     result += ")";
286     return result;
287 }
288
289 ///////////////////////////////////////////////////////////////
290 // PRIMARY KEY TYPE by Shen Bo
291 ///////////////////////////////////////////////////////////////
292 // int
293 public string GetPKPropertyType()
294 {
295     return     GetPKType(TargetTable);
296 }
297
298 ///////////////////////////////////////////////////////////////
299 // PRIMARY KEY NAME by Shen Bo
300 ///////////////////////////////////////////////////////////////
301 // Id
302 public string GetPKPropertyName()
303 {
304     return MakePascal(GetPKName());
305 }
306 // id
307 public string GetPKParamName()
308 {
309     return GetPKMemberVarName();
310 }
311 // id
312 public string GetPKMemberVarName()
313 {
314     return MakeCamel(GetPKName());
315 }
316 // Id
317 public string GetPKName()
318 {
319     return GetPKName(TargetTable);
320 }
321
322 public override string GetFileName()
323 {
324     return this.GetDALClassName() + ".cs";
325 }
326
327 </script>
 
 

 

时间: 2024-08-25 12:43:45

CodeSmith自己动手写模板的相关文章

《自己动手写开源框架10》:Web界面快速开发实践

下面是一些常用的链接,供大家使用: GIT地址:https://git.oschina.net/tinyframework/tiny问题报告:https://git.oschina.net/tinyframework/tiny/issues更多内容,请看本人博客,不一样的内容,一样的精彩! 在展示过程的同时,会把相关的知识做一个充分的介绍 .一.寻找网站模板 要做网站,不能没有模板,自己不会做网页设计,咋办?问谷歌找百度呗,找了一阵,看到下面这个模板不错,就它了. http://www.toop

自己动手写PHP MVC框架

来自:yuansir-web.com / [email protected] 代码下载: https://github.com/yuansir/tiny-php-framework PHP的框架众多,对于哪个框架最好,哪个框架最烂,是否应该用框架,对于这些争论在论坛里面都有人争论,这里不做评价, 个人觉得根据自己需求,选中最佳最适合自己MVC框架,并在开发中能够体现出敏捷开发的效果就OK了,作为一个PHPer要提高自己的对PHP和MVC的框架的认识,所以自己写一个MVC框架是很有必要的, 即使不

《自己动手写框架9》:理想的开源框架与设计原则

理想的开源框架?她应该是小的.简单的,满足Simple Is Beautiful?她应该是成长性好的,随着不断的扩展,她可以越来越丰满?她应该是有良好工具支持的,为什么要花时间做工具可以完成的事情呢??她应该是自组装的,也就是尽可能的脱离配置,而是用一种依赖即可用,取消依赖即消失的全自动处理模式?她应该是模块化的,所有的内容都可以被打入jar包而作为一个整体进行发布,并且能支持热部署的,可以开着车儿换轮胎的?她应该是支持水平部署的,想加服务器就加,想减服务器就减?她应该是有良好知识积累体系的,使

《自己动手写框架7》:关于框架体系与战术的思考

什么是框架? 这个问题实际上许多"做框架"的人也不明白. 框架和库的本质不同在于: 框架考虑的是机制的复用,而库主要考虑的是代码的复用 框架考虑的是在机制不变的情况下进行扩展,而库则基本不考虑扩展方面的问题 框架本身是不完整的,在大多数的情况下它自己是干不了啥事情的,而库自身是完整的,可以解决某个领域的问题. 框架是活的,通过不断的扩展与衍生,它就更加强大,而库而是死的,发布时是怎样,就是怎样. 当然,关于这两货之间的比较,还有许多个角度,但我个人觉得本质是我上面举的这些. 设计的时候

【原创】连“霍金”都想学习的“人工智能”---【自己动手写神经网络】小白入门连载开始了(1)

欢迎关注[自己动手写神经网络]的博客连载!!! 第1章 神经网络简介 神经网络这个词,相信大家都不陌生.就在你打开本书,并试图了解神经网络时,你已经在使用一个世界上最复杂的神经网络——你的大脑,一个由大约1000亿个神经元(每个单元拥有约1万个连接)构成的复杂系统.但人的大脑太过复杂,以至于科学家们到目前为止仍然无法准确解释大脑的工作原理和方式.但有幸的是,生物神经网络的最最基本的元素已经能够被识别,而这就构成了本书想为你介绍的人工神经网络(Artificial Neural Network).

自己动手写ORM的感受

之前看到奋斗前辈和时不我待前辈的自己动手写ORM系列博客,感觉讲解的通俗易懂,清晰透彻.作为一个菜鸟,闲来也想着自己写一个ORM,一来加深自己对 ORM的理解,以求对EF,NHibernate等ROM框架的使用能更加轻车熟路.二来也可在写ORM之时熟悉反射的应用场景,反射的优缺点,优化方 法,Lambda表达式,表达式树等.,对自己也是一个不错的锻炼. ORM的原理也就表映射,反射,拼接sql,缓存,Lambda进行方法调用.网上有很多源码参考和原理讲解,对着敲一敲完成一个简易的ORM并不是什么

自己动手写快速开发框架1【EF+WEBAPI+EASYUI+SEAJS+...】大概想法

自己动手写个框架,大约周期为半年,作为5年.net工作的积累及思考,构想是蛮大的,先看架构图(貌似什么都想做...): 已经开始了大概半个月时间,大概的更新记录如下: 20160715: 1.后端加入EF 的Code First 2.前端引用easyui 3.加入log4net日志管理 4.日志管理加入txt记录管理页面 20160727: 1.引入seajs,管理所有前前端接口 2.加入日志支持数据库记录 3.引入signalr 支持消息推送 20160801: 1.修正了清除日志功能 2.将

《自己动手写框架8》:高屋建瓴,理念先行

<史记·高祖本纪>:"地势便利,其以下兵于诸侯,譬犹居高屋之上建瓴水也."这里用到了高屋建瓴这个词.意思是把瓶子里的水从高层顶上倾倒.比喻居高临下,不可阻遏的形势.现指对事物把握全面,了解透彻.此典故于汉高祖刘邦欲杀功臣韩信,大夫田肯进言到"陛下牢牢地控制着三秦(关中),陛下利用这雄险的地势,来控制.驾御诸侯,就如从高高的屋脊上把水从瓶子里倒下去."以此来表彰韩信的功劳,于是,刘邦赦免了韩信,只是将他降为淮阴侯. 同样,设计企业框架,也要对事物把握全面,

自己动手写工具:百度图片批量下载器

开篇:在某些场景下,我们想要对百度图片搜出来的东东进行保存,但是一个一个得下载保存不仅耗时而且费劲,有木有一种方法能够简化我们的工作量呢,让我们在离线模式下也能爽爽地浏览大量的美图呢?于是,我们想到了使用网络抓取去帮我们去下载图片,并且保存到我们设定的文件夹中,现在我们就来看看如何来设计开发一个这样的图片批量下载器. 一.关于网络抓取与爬虫 网络蜘蛛的主要作用是从Internet上不停地下载网络资源.它的基本实现思想就是通过一个或多个入口网址来获取更多的URL,然后通过对这些URL所指向的网络资