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移动插件实现
序言 本章作为自己动手写插件的第一篇文章,会尽可能的详细描述一些实现的方式和预备知识的讲解,随着知识点积累的一点点深入,可能到了后期讲解也会有所跳跃.所以,希望知识点不是很扎实的读者或者是初学者,不要 ...
随机推荐
- 网络对抗技术 2017-2018-2 20155215 Exp9 Web安全基础
1.实践过程 前期准备:WebGoat WebGoat分为简单版和开发板,简单版是个Java的Jar包,只需要有Java环境即可,我们在命令行里执行java -jar webgoat-containe ...
- 20155235 《网络攻防》 实验八 Web基础
20155235 <网络攻防> 实验八 Web基础 实验内容 Web前端HTML(0.5分) 能正常安装.启停Apache.理解HTML,理解表单,理解GET与POST方法,编写一个含有表 ...
- 20155308《网络对抗》Exp9 Web安全基础实践
20155308<网络对抗>Exp9 Web安全基础实践 本实践的目标理解常用网络攻击技术的基本原理.Webgoat实践下相关实验. 基础问题回答 SQL注入攻击原理,如何防御? 原理:攻 ...
- HTML基础之CSS
CSS选择器 1.id选择器 2.class选择器 3.标签选择器 4.层级选择器(空格) 5.组合选择器(逗号) 6.属性选择器(中括号) <!DOCTYPE html> <htm ...
- vue-cli 3.0 实现A-Z字母滑动选择城市列表
项目地址: https://github.com/caochangkui/vue-cli3 项目代码: 城市列表首页: City.vue <template> <div id=&qu ...
- 设计模式 笔记 备忘录模式 Memento
//---------------------------15/04/27---------------------------- //Memento 备忘录模式----对象行为型模式 /* 1:意图 ...
- TensorFlow训练MNIST数据集(1) —— softmax 单层神经网络
1.MNIST数据集简介 首先通过下面两行代码获取到TensorFlow内置的MNIST数据集: from tensorflow.examples.tutorials.mnist import inp ...
- c++时间计算模块
c++时间计算模块 可用于计算代码运行耗时.计算代码运行时间线(比如处理与运行时间相关函数). 该模块从实际项目中产生,使用方式仁者见仁智者见智,设计思想可供参考. 源码: //author: cai ...
- Markdown语言学习
看够了单一的文本文档么?或者写一个word各种调整样式?试试Markdown吧! Markdown是一种文本标记语言,通过简单的标记语法,使单一的文本内容具有一定的格式. 下面来看看常用的各种标记吧 ...
- C#回调函数的简单讲解与应用例子(最简单讲解,大神绕道)
本博客一直以来的宗旨就是:用最简单的方式讲清楚不复杂的问题. 因为本人也很菜所以也没法讲太复杂HHHHHH...... 所以如果哪天某个大神看到了觉得讲的有问题欢迎指出. 话不多说进入正题.. ——— ...