用NVelocity写的一个简单的实体生成器

1、TestClass.aspx页面内容如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestClass.aspx.cs" Inherits="TestClass" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        输入表名:<asp:TextBox ID="TextBox1" runat="server" Width="180px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="代码生成生成" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

2、cs代码如下:其中SQLHelper参照我写的SQLHelper类这篇文章,数据库连接字符串写在SQLHelper中,所以此时直接调用SQLHelper.ExecuteReader(“SQL语句”)就会返回SqlDataReader,数据库为SqlServer2000/2005/2008

 

代码
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Data.SqlClient;
using NVelocity.App;
using Commons.Collections;
using NVelocity;
using System.IO;
using NVelocity.Runtime;
using System.Text;
using AnalysisRuleFileDAL;

public partial class TestClass : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}


#region 带SQLHelper的getCharptByChaptNo方法 根据ChapterNo获取Chapter信息
/// <summary>
/// 根据ChapterNo获取Chapter信息
/// </summary>
/// <param name="chptNo">ChapterNo</param>
/// <returns>Chapter</returns>
public IList<SQLColem> getTableColByName(string name)
{

IList
<SQLColem> list = new List<SQLColem>();
string sqlStr = @"SELECT a.[name] as '字段名称', (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) as '标识'
,b.name '类型'
,a.length '占用字节数'
,(case when a.isnullable = 1 then '√'else '' end) '允许空'
,isnull(e.text,'') '默认值'
,cast(isnull(g.[value],'') as varchar(100)) AS '字段说明'
FROM syscolumns a
left join systypes b
on a.xtype = b.xusertype
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id = g.id AND a.colid = g.smallid inner join sysobjects on sysobjects.id = a.id
where sysobjects.xtype='U' and sysobjects.name='
" + name + "'";//sql 语句
SqlDataReader rs = null;//定义SqlDataReader

try
{

rs
= SQLHelper.ExecuteReader(sqlStr);
//根据sql 语句获得SqlDataReader

//循环读取数据
while (rs.Read())
{
SQLColem colom
= new SQLColem();// 实例化Chapter
StringBuilder str = new StringBuilder(Convert.ToString(rs[0]));

string first = str.ToString().Substring(0,1);
//首字母小写
str = str.Replace(first.Substring(0, 1), first.Substring(0, 1).ToLower(), 0, 2);

colom.Realname
= str.ToString();// str.ToString();

//首字母大写
str = str.Replace(first.Substring(0, 1), first.Substring(0, 1).ToUpper(), 0, 2);

colom.Bigname
= str.ToString();
string type = Convert.ToString(rs[2]);
switch (type)
{
case "char":
case "varchar":
case "nchar":
case "nvarchar":
type
= "string";
break;
case "datetime":
case "smalldatetime":
type
= "DateTime";
break;
case "decimal":
case "numeric":
case "money":
case "smallmoney":
type
= "double";
break;
case "float":
type
= "float";
break;
case "int":
case "smallint":
case "tinyint":
case "bit":
type
= "int";
break;
default:
break;
}

colom.Type
= type;
list.Add(colom);

}
}
catch (Exception)
{
rs.Dispose();
rs.Close();
}
finally
{
rs.Dispose();
rs.Close();
}

return list;
}
#endregion

/// <summary>
/// 生成事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
//获取表名,生成Class类模板
string tablename = this.TextBox1.Text.Trim();
tempToClass(tablename);
}


/// <summary>
/// 代码生成模板
/// </summary>
/// <param name="tablename"></param>
private void tempToClass(string tablename)
{
StringBuilder str
= new StringBuilder(tablename);

String className
= str.Replace(tablename.Substring(0, 1), tablename.Substring(0, 1).ToUpper(),0,1).ToString();
IList
<SQLColem> listUsers = new List<SQLColem>();

listUsers
= getTableColByName(tablename);

Response.Write(listUsers.Count);

IList
<string> listAssembly = new List<string>();
// 添加程序集名称
listAssembly.Add("LibTest");

//创建NVelocity引擎的实例对象
VelocityEngine velocity = new VelocityEngine();
//初始化该实例对象
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.RESOURCE_LOADER,
"file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(Request.PhysicalPath)
+ "/Template/");
props.AddProperty(RuntimeConstants.INPUT_ENCODING,
"gb2312");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING,
"gb2312");
velocity.Init(props);
//从文件中读取模板
Template temp = velocity.GetTemplate("tempClass.htm");
VelocityContext vltContext
= new VelocityContext();
vltContext.Put(
"ClassName", className);
vltContext.Put(
"ListUsers", listUsers);
//合并模板
StringWriter writer = new StringWriter();
//velocity.MergeTemplate(context, writer);
temp.Merge(vltContext, writer);

//Template vltTemplate = velocity.GetTemplate("LibTest.Resources.Default.htm");
//System.IO.StringWriter vltWriter = new System.IO.StringWriter();
//temp.Merge(vltContext, vltWriter);
//生成静态页
using (StreamWriter writer2 = new StreamWriter(Server.MapPath("") + "/" + className + ".cs", false, Encoding.UTF8, 200))
{
writer2.Write(writer);
writer2.Flush();
writer2.Close();
}
}
}

 3、SQLColem.cs文件内容如下:

 

代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

/// <summary>
///SQLColem 的摘要说明
/// </summary>
public class SQLColem
{
public SQLColem()
{
//
//TODO: 在此处添加构造函数逻辑
//
}

private string realname;
private string bigname;
private string type;

public string Type
{
get { return type; }
set { type = value; }
}



public string Bigname
{
get { return bigname; }
set { bigname = value; }
}

public string Realname
{
get { return realname; }
set { realname = value; }
}
}

 

posted @ 2010-03-09 16:44  why520crazy  阅读(442)  评论(0编辑  收藏  举报