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移动插件实现
序言 本章作为自己动手写插件的第一篇文章,会尽可能的详细描述一些实现的方式和预备知识的讲解,随着知识点积累的一点点深入,可能到了后期讲解也会有所跳跃.所以,希望知识点不是很扎实的读者或者是初学者,不要 ...
随机推荐
- 一个评测指标就是MAP(Mean Average Precision)平均精度均值。
一个评测指标就是MAP(Mean Average Precision)平均精度均值. 转载 2017年09月13日 10:07:12 标签: 深度学习 892 来源01:Mean Average Pr ...
- js中的数据类型及判断方法
ECMAScirpt 变量有两种不同的数据类型:基本类型,引用类型. 基本类型 ● Boolean ● Null ● Undefined ● Number ● String ● Symbol (ECM ...
- nvm管理不同版本的node和npm
写在前面 nvm(nodejs version manager)是nodejs的管理工具,如果你需要快速更新node版本,并且不覆盖之前的版本:或者想要在不同的node版本之间进行切换:使用nvm来安 ...
- chrome播放m3u8視頻失败
由于项目后台需要播放m3u8视频,但此视频格式在移动端和Safari支持比较友善但是PC浏览器中都不太尽如人意,所以想在Chrome中播放只能借助第三方插件来播放. 有一款Video.js插件极大的简 ...
- OD之去除nag弹窗(四)
在某些方面,一个软件如果没有注册的话,老是会弹出烦人的注册弹窗,就如下图一样: 出现了两次弹窗,开始一次,关闭后又一次,老办法,拖进OD进行分析;不过看出程序很简单,就出现了messagebox的调用 ...
- Unity Dotween官方案例学习
本文只涉及一些案例,具体查看 DoTween 官方文档. 一. Basics public class Basics : MonoBehaviour { public Transform redCub ...
- CentOS7安装OpenStack(Rocky版)-01.控制节点的系统环境准备
分享一下Rocky版本的OpenStack安装管理经验: OpenStack每半年左右更新一版,目前是版本是201808月发布的版本-R版(Rocky),目前版本安装方法优化较好,不过依然是比较复杂 ...
- raft--分布式一致性协议
0. 写在前面的话 一直从事分布式对象存储工作,在分布式对象存储的运营,开发等工作中,数据一致性是至关重要的.因此想写一篇关于分布式一致性的文章.一来,可以和大家分享.二来,可以提高自己的文字提炼能力 ...
- MyBatis3-动态SQL语句
MyBatis的动态SQL语句是基于OGNL表达式的.可以方便的在SQL语句中实现某些逻辑,总体说来MyBatis动态SQL语句主要有以下几类: 1.if语句(简单的条件判断). 2.choose(w ...
- BugPhobia准备篇章:团队Beta阶段准备工作分析
0x00:序言 To the searching tags, you may well fall in love withhttp://xueba.nlsde.buaa.edu.cn/ 再见,无忧时光 ...