CodeSmith自己动手写模板

CodeSmith学习笔记------

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

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

①外部变量:

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

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

CodeSmith自己动手写模板

还有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自己动手写模板
上一篇:Spring RedisTemplate操作-Set操作(5)


下一篇:在Java Web程序中使用监听器可以通过以下两种方法