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,这个程序集中的类主要用于获取数据库中各种对象的结构。
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Optional="False" Description="源表名" %> <%@ Property Name="SourceDB" Type="SchemaExplorer.DatabaseSchema" Optional="False" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %>
Assembly:引用程序集,Import:相当于using命名空间。
Type="SchemaExplorer.DatabaseSchema"此类型会在属性栏生成一个数据库的选择框,Type="SchemaExplorer.TableSchema"即表的选择框。
③自定义方法:
<script runat="template">
// My methods here.
public string SampleMethod()
{
return "Method output.";
}
</script>
<script runat="template"></script>标签内写的是自定义函数(C#代码)
④模板部分书写:
C#代码要用<%%>包括,值类型要使用<%=%>
例如:生成一个Model层的模板
using System;
using System.Collections.Generic;
using System.Text; Namespace Model
{
Class <%=TargetTable.Name%>
{
<% for (int i=;i<TargetTable.Columns.Count;i++)
{
SchemaExplorer.ColumnSchema col = TargetTable.Columns[i];%>
public <%=col.SystemType%> <%=col.Name%>{get;set;}
<%}%>
}
}
⑤一份完整的DAL的模板示例:
<%@ CodeTemplate Language="C#" TargetLanguage="C#"
Src="ToolsCodeTemplate.cs" Inherits="ToolsCodeTemplate"%>
<%@ Property Name="TargetTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="TargetTable that the object is based on." %>
<%@ Property Name="ModelsNamespace" Default="MyOffice.Models" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
<%@ Property Name="DALNamespace" Default="MyOffice.DAL" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
<%@ Property Name="DALClassNameSurfix" Default="Service" Type="System.String" Category="Context" Description="TargetTable that the object is based on." %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<% PrintHeader(); %>
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using <%= ModelsNamespace %>; namespace <%= DALNamespace %>
{
public partial class <%= GetDALClassName() %>
{
<%-- public static Book AddBook(Book book) --%>
public <%= GetModelClassName() %> Add
(<%= GetModelClassName() %> <%= GetModelParamName() %>)
{
<%if(IsIdentityPK())
{%>
string sql ="<%= GetAutoIncInsertSQLLine()%>";
SqlParameter[] para = new SqlParameter[]
{
<%
for(int i=; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
{
ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i]; %>
new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>)),
<%
}
%>
}; <%= GetPKPropertyType() %> newId = (<%= GetPKPropertyType() %>)SqlHelper.ExecuteScalar(sql, para);
return GetBy<%= GetPKPropertyName() %>(newId);
<%}else
{%>
string sql ="<%= GetCommonInsertSQLLine()%>";
SqlParameter[] para = new SqlParameter[]
{
<%
for(int i=; i<TargetTable.Columns.Count; i++)
{
ColumnSchema column = TargetTable.Columns[i];
%>
new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>)),
<%
}
%>
};
SqlHelper.ExecuteNonQuery(sql, para);
return <%= GetModelParamName() %>;
<%}%>
} <%-- public static bool DeleteBookById(int id) --%>
public int DeleteBy<%= GetPKPropertyName() %>(<%= GetPKPropertyType() %> <%= GetPKParamName() %>)
{
string sql = "DELETE <%= TargetTable.Name %> WHERE <%= GetPKPropertyName() %> = @<%= GetPKPropertyName() %>"; SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("@<%= GetPKName() %>", <%= GetPKParamName() %>)
}; return SqlHelper.ExecuteNonQuery(sql, para);
} <%-- public static bool ModifyBook(Book book) --%>
public int Update(<%= GetModelClassName() %> <%= GetModelParamName() %>)
{
string sql =
"UPDATE <%= TargetTable.Name %> " +
"SET " +
" <%= TargetTable.NonPrimaryKeyColumns[0].Name %> = @<%= TargetTable.NonPrimaryKeyColumns[0].Name %>"
<%
for(int i=; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
{
ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i];
%>
+", <%= column.Name %> = @<%= column.Name %>"
<%
}
%> +" WHERE <%= GetPKName() %> = @<%= GetPKName() %>"; SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("@<%= GetPKName() %>", <%= GetModelParamName() %>.<%= GetPKName() %>)
<%
for(int i=; i<TargetTable.NonPrimaryKeyColumns.Count; i++)
{
ColumnSchema column = TargetTable.NonPrimaryKeyColumns[i];
%>
,new SqlParameter("@<%= column.Name %>", ToDBValue(<%= GetModelParamName() %>.<%= column.Name %>))
<%
}
%>
}; return SqlHelper.ExecuteNonQuery(sql, para);
} <%-- public static Book GetBookById(int id) --%>
public <%= GetModelClassName() %> GetBy<%= GetPKPropertyName() %>(<%= GetPKPropertyType() %> <%= GetPKParamName() %>)
{
string sql = "SELECT * FROM <%= TargetTable.Name %> WHERE <%= GetPKPropertyName() %> = @<%= GetPKPropertyName() %>";
using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql, new SqlParameter("@<%= GetPKPropertyName() %>", <%= GetPKParamName() %>)))
{
if (reader.Read())
{
return ToModel(reader);
}
else
{
return null;
}
}
} public <%= GetModelClassName() %> ToModel(SqlDataReader reader)
{
<%= GetModelClassName() %> <%= GetModelParamName() %> = new <%= GetModelClassName() %>(); <% foreach(ColumnSchema column in TargetTable.Columns) %>
<% { %>
<%= GetModelParamName() %>.<%= GetPropertyName(column) %> = (<%=GetPropertyType(column)%>)ToModelValue(reader,"<%=column.Name%>");
<% } %>
return <%= GetModelParamName() %>;
} public int GetTotalCount()
{
string sql = "SELECT count(*) FROM <%= TargetTable.Name %>";
return (int)SqlHelper.ExecuteScalar(sql);
} public IEnumerable<<%= GetModelClassName() %>> GetPagedData(int minrownum,int maxrownum)
{
string sql = "SELECT * from(SELECT *,row_number() over(order by <%=this.GetPKName()%>) rownum FROM <%= TargetTable.Name %>) t where rownum>=@minrownum and rownum<=@maxrownum";
using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql,
new SqlParameter("@minrownum",minrownum),
new SqlParameter("@maxrownum",maxrownum)))
{
return ToModels(reader);
}
} public IEnumerable<<%= GetModelClassName() %>> GetAll()
{
string sql = "SELECT * FROM <%= TargetTable.Name %>";
using(SqlDataReader reader = SqlHelper.ExecuteDataReader(sql))
{
return ToModels(reader);
}
} protected IEnumerable<<%= GetModelClassName() %>> ToModels(SqlDataReader reader)
{
var list = new List<<%= GetModelClassName() %>>();
while(reader.Read())
{
list.Add(ToModel(reader));
}
return list;
} protected object ToDBValue(object value)
{
if(value==null)
{
return DBNull.Value;
}
else
{
return value;
}
} protected object ToModelValue(SqlDataReader reader,string columnName)
{
if(reader.IsDBNull(reader.GetOrdinal(columnName)))
{
return null;
}
else
{
return reader[columnName];
}
}
}
}
<script runat="template">
public bool IsIdentityPK()
{
foreach(ColumnSchema column in TargetTable.Columns)
{
if((bool)column.ExtendedProperties["CS_IsIdentity"].Value)
{
return true;
}
}
return false;
} ///////////////////////////////////////////////////////////////
// CLASS NAMES by Shen Bo
///////////////////////////////////////////////////////////////
// UserService
public string GetDALClassName()
{
return GetModelClassName() + DALClassNameSurfix;
}
// User
public string GetModelClassName()
{
return GetModelClassName(TargetTable);
}
// user
public string GetModelMemberVarName()
{
return GetModelParamName();
}
// user
public string GetModelParamName()
{
return MakeCamel(GetModelClassName());
} ///////////////////////////////////////////////////////////////
// INSERT SQL LINES by Shen Bo
///////////////////////////////////////////////////////////////
public string GetAutoIncInsertSQLLine()
{
string result;
result = "INSERT INTO " + TargetTable.Name + " (";
foreach(ColumnSchema column in TargetTable.NonPrimaryKeyColumns)
{
result += column.Name + ", ";
}
result = result.Substring(, result.Length-);
result += ") ";
result+=" output inserted."+GetPKName();
result += " VALUES (";
foreach(ColumnSchema column in TargetTable.NonPrimaryKeyColumns)
{
result += "@" + column.Name + ", ";
}
result = result.Substring(, result.Length-);
result += ")";
return result;
} public string GetCommonInsertSQLLine()
{
string result;
result = "INSERT INTO " + TargetTable.Name + " (";
foreach(ColumnSchema column in TargetTable.Columns)
{
result += column.Name + ", ";
}
result = result.Substring(, result.Length-);
result += ") ";
result += " VALUES (";
foreach(ColumnSchema column in TargetTable.Columns)
{
result += "@" + column.Name + ", ";
}
result = result.Substring(, result.Length-);
result += ")";
return result;
} ///////////////////////////////////////////////////////////////
// PRIMARY KEY TYPE by Shen Bo
///////////////////////////////////////////////////////////////
// int
public string GetPKPropertyType()
{
return GetPKType(TargetTable);
} ///////////////////////////////////////////////////////////////
// PRIMARY KEY NAME by Shen Bo
///////////////////////////////////////////////////////////////
// Id
public string GetPKPropertyName()
{
return MakePascal(GetPKName());
}
// id
public string GetPKParamName()
{
return GetPKMemberVarName();
}
// id
public string GetPKMemberVarName()
{
return MakeCamel(GetPKName());
}
// Id
public string GetPKName()
{
return GetPKName(TargetTable);
} public override string GetFileName()
{
return this.GetDALClassName() + ".cs";
} </script>

CodeSmith自己动手写模板的更多相关文章
- 动手写一个简单的Web框架(模板渲染)
动手写一个简单的Web框架(模板渲染) 在百度上搜索jinja2,显示的大部分内容都是jinja2的渲染语法,这个不是Web框架需要做的事,最终,居然在Werkzeug的官方文档里找到模板渲染的代码. ...
- 自己动手写PHP MVC框架
自己动手写PHP MVC框架 来自:yuansir-web.com / yuansir@live.cn 代码下载: https://github.com/yuansir/tiny-php-framew ...
- 自己动手写Vector【Cherno C++教程】
动手写一个Vector 本文是对<最好的C++教程>的动手写数据结构部分的一个整理,主要包含91p动手写Array数组和92p动手写Vector数组的内容. 自己动手来写这些数据结构是学习 ...
- 【原创】自己动手写控件----XSmartNote控件
一.前面的话 在上一篇博文自己动手写工具----XSmartNote [Beta 3.0]中,用到了若干个自定义控件,其中包含用于显示Note内容的简单的Label扩展控件,用于展示标签内容的labe ...
- 【原创】自己动手写工具----XSmartNote [Beta 3.0]
一.前面的话 在动笔之前,一直很纠结到底要不要继续完成这个工具,因为上次给它码代码还是一年多之前的事情,参考自己动手写工具----XSmartNote [Beta 2.0],这篇博文里,很多园友提出了 ...
- 【原创】自己动手写工具----XSmartNote [Beta 2.0]
一.前面的话 在上一篇自己动手写工具----XSmartNote中,我简单介绍了这个小玩意儿的大致界面和要实现的功能,看了一下园子里的评论,评价褒贬不一,有人说“现在那么多云笔记的工具”,“极简版ev ...
- 【原创】自己动手写工具----签到器[Beta 2.0]
一.前面的话 上一篇中基本实现了简单的签到任务,但是不够灵活.在上一篇自己动手写工具----签到器的结尾中,我设想了几个新增功能来提高工具的灵活程度,下面把新增功能点列出来看看: (1)新增其他的进程 ...
- 自己动手写ORM的感受
之前看到奋斗前辈和时不我待前辈的自己动手写ORM系列博客,感觉讲解的通俗易懂,清晰透彻.作为一个菜鸟,闲来也想着自己写一个ORM,一来加深自己对 ORM的理解,以求对EF,NHibernate等ROM ...
- 自己动手写插件底层篇—基于jquery移动插件实现
序言 本章作为自己动手写插件的第一篇文章,会尽可能的详细描述一些实现的方式和预备知识的讲解,随着知识点积累的一点点深入,可能到了后期讲解也会有所跳跃.所以,希望知识点不是很扎实的读者或者是初学者,不要 ...
随机推荐
- 20155334 曹翔 Exp3 免杀原理与实践
20155334 曹翔 Exp3 免杀原理与实践 小记:这次实验,困难重重,失败练练,搞得我们是心急如焚,焦头烂额,哭爹喊娘 一.基础问题回答 杀软是如何检测出恶意代码的? 每个杀软都有自己的检测库, ...
- [python]记录Windows下安装matplot的经历
最近学习在看<机器学习实战>一书,第二章的时候要用到Natplotlib画图,于是便开始安装Matplotlib.本文所用到的所有安装包都可以在文末的链接中找到. 首先从Matplotli ...
- [UOJ#268]. 【清华集训2016】数据交互[动态dp+可删堆维护最长链]
题意 给出 \(n\) 个点的树,每个时刻可能出现一条路径 \(A_i\) 或者之前出现的某条路径 \(A_i\) 消失,每条路径有一个权值,求出在每个时刻过后能够找到的权值最大的路径(指所有和该路径 ...
- C++学习 内存模型和名称空间
1.单独编译 C++鼓励程序员将组件函数放在独立的文件中,如果只修改了一个文件,则可以只重新编译该文件,然后将它与其他文件的编译版本链接. 一般非常有用的组织程序的策略是把程序分成三部分: 头文件:包 ...
- B1030 完美数列 (25 分)
这是一道二分法的题目,许久不使用二分法,感觉有点生疏. #include<bits/stdc++.h> using namespace std; const int MAXN=100000 ...
- Keras学习笔记。
1. keras.layers.Dense (Fully Connected Neural NetWork),所实现的运算是output = activation(dot(input, kernel) ...
- PBFT_拜占庭容错算法
根据论文<Practical Byzantine Fault Tolerance and Proactive Recovery>整理 Practical byzantine fault t ...
- PAT甲题题解-1041. Be Unique (20)-水题
博主欢迎转载,但请给出本文链接,我尊重你,你尊重我,谢谢~http://www.cnblogs.com/chenxiwenruo/p/6789189.html特别不喜欢那些随便转载别人的原创文章又不给 ...
- BugPhobia准备篇章:团队Beta阶段准备工作分析
0x00:序言 To the searching tags, you may well fall in love withhttp://xueba.nlsde.buaa.edu.cn/ 再见,无忧时光 ...
- Daily Scrum NO.1
工作概况 符美潇(PM): 今日工作 1.根据开发进程分配第一步开发工作,对相应的成员提出今日的开发要求:要求成员自己所负责的线程池,动态爬取,去重,文件分类等部分进行资料的相关了解. 2.Daily ...