十七、EnterpriseFrameWork框架核心类库之Web控制器

回《【开源】EnterpriseFrameWork框架系列文章索引

EFW框架源代码下载:http://pan.baidu.com/s/1qWJjo3U

EFW框架中的WebController就是解决JqueryEasyUI与逻辑层的交互,之间的数据是通过Json字符串来传递;值得注意的是WebController的代码一定不要和EFWWeb项目放在一起,你可以单独建一个项目类库,也可以和逻辑层项目放一起;在EFWWeb项目不要编写任何C#代码,这个在前面的文章中就提过,可以让你的Web项目发布更省事一点,免去编译EFWWeb项目的痛苦;

控制器可以调用分层一下的所有代码,包括ObjectModel、Dao、Entity,甚至可以直接用oleDb编写SQL语句操作数据库;还有控制器与控制器之间是不能存在任何依赖关系的;

本章主要内容通过解读框架源代码来学习WebController是怎么实现的,以及思考这样实现会给我们开发带来什么好处;

本文要点:

1.如何使用Web控制器

2.Web控制器的设计思路

3.Web控制器基类AbstractController的实现

4.Web控制器的自定义标签WebControllerAttribute和WebMethodAttribute

5.基于JqueryEasyUI封装的Web控制器的实现

6.Web常用组件封装成控制器

Web控制器源代码目录

十七、EnterpriseFrameWork框架核心类库之Web控制器

EFW框架控制器设计图

十七、EnterpriseFrameWork框架核心类库之Web控制器

1.如何使用Web控制器

讲解EFW框架中的Web控制器的使用之前先看看传统的Web系统是如何开发的;

十七、EnterpriseFrameWork框架核心类库之Web控制器

如上图,传统方式一个aspx文件对应一个cs文件,开发方式跟Winform桌面程序相同,都是事件响应的模式;我们再看看EFW框架中是如何开放的;

十七、EnterpriseFrameWork框架核心类库之Web控制器十七、EnterpriseFrameWork框架核心类库之Web控制器

如上图,有两个项目EFWWeb项目和Books项目,EFWWeb项目里面只有界面HTML代码和JS代码,后台CS代码在另外的Books项目中;接着看里面的详细代码,界面层是如何调用后台的Web控制器的;

Book.aspx文件

 <%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>书籍管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="../../../WebPlugin/jquery-easyui-1.3.4/themes/default/easyui.css"/>
<link rel="stylesheet" type="text/css" href="../../../WebPlugin/jquery-easyui-1.3.4/themes/icon.css"/>
<script type="text/javascript" src="../../../WebPlugin/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="../../../WebPlugin/jquery-easyui-1.3.4/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../../WebPlugin/jquery-easyui-1.3.4/locale/easyui-lang-zh_CN.js"></script>
<script src="../../../WebPlugin/JQueryCommon2.0.js" type="text/javascript"></script>
<script src="Book.js" type="text/javascript"></script>
</head>
<body class="easyui-layout">
<div region="center" style="overflow:hidden;">
<div id="grid-tool">
<table cellpadding="0" cellspacing="0" style="width:100%">
<tr>
<td style="padding-left:2px">
<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-add" onclick="btn_add();">新增</a>
<a href="#" class="easyui-linkbutton" plain="true" iconCls="icon-edit" onclick="btn_alter();">修改</a>
</td>
<td style="text-align:right;padding-right:2px">
<input class="easyui-searchbox" data-options="prompt:'请输入书籍名称'" style="width:250px"></input>
</td>
</tr>
</table>
</div>
<table id="bookGird" class="easyui-datagrid" toolbar="#grid-tool" fit="true" border="false" singleSelect="true">
<thead>
<tr>
<th field="Id" width="100">序号</th>
<th field="BookName" width="80">书籍名称</th>
<th field="BuyPrice" width="120">购书价格</th>
<th field="BuyDate" width="200">购书时间</th>
<th field="Flag" width="80">是否丢失</th>
</tr>
</thead>
</table>
</div> <%--弹出窗界面--%>
<div id="dialog-book" title="新增书籍" class="easyui-dialog" icon="icon-save" style="background:#fafafa;padding:10px;width:350px;height:250px;" buttons="#dlg-buttons1" resizable="true" modal="true">
<form id="bookform" method="post">
<table>
<tr>
<td><label>书籍名称:</label></td>
<td><input name="BookName" class="easyui-validatebox" style="width:200px;" type="text" required="true"></input></td>
</tr>
<tr>
<td><label>购书价格:</label></td>
<td><input name="BuyPrice" class="easyui-validatebox" style="width:200px;" type="text" required="true"></input></td>
</tr>
<tr>
<td><label>购书日期:</label></td>
<td><input name="BuyDate" class="easyui-datebox" style="width:200px;" type="text" required="true"></input></td>
</tr>
<tr>
<td><label>是否丢失:</label></td>
<td><input id="_flag" type="checkbox"/></td>
</tr>
</table>
<input id="book_id" type="hidden" name="Id" ></input>
<input id="book_flag" type="hidden" name="Flag" ></input>
</form>
</div>
<div id="dlg-buttons1">
<a href="#" class="easyui-linkbutton" onclick="btn_save();">确定</a>
<a href="#" class="easyui-linkbutton" onclick="$('#dialog-book').dialog('close');">取消</a>
</div>
</body>
</html>

Book.js文件

 //初始化入口
$(function() {
$('#dialog-book').dialog('close');
//加载网格数据
$('#bookGird').datagrid('options').url = 'Controller.aspx?controller=bookController&method=SearchBook&schar=&flag=0';
//$('#bookGird').datagrid('reload');
});
//添加
function btn_add(){
$('#dialog-book').dialog({ title: '新增书籍' });
$("#bookform").form('clear');
$("#book_id").val(0);
$("#book_flag").val(0);
$("#_flag").removeAttr("checked");
}
//修改
function btn_alter(){
$('#dialog-book').dialog({ title: '修改书籍' });
var selected = $('#bookGird').datagrid('getSelected');
if (selected) {
$("#bookform").form("load", selected); if (selected.Flag == "1")
$("#_flag").attr("checked", "true");
else
$("#_flag").removeAttr("checked");
}
}
//保存
function btn_save() {
var ckval=$("#_flag").attr("checked")=="checked"?1:0;
$('#book_flag').val(ckval);
formSubmit('#bookform', 'Controller.aspx?controller=bookController&method=SaveBook', function() {
$('#dialog-book').dialog('close');
$('#bookGird').datagrid('reload');
});
}

bookController.cs文件

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EFWCoreLib.WebFrame.Controller;
using Books.Entity;
using Books.Dao;
using System.Data; namespace Books.WebController
{
[WebController]
public class bookController : EFWCoreLib.WebFrame.Controller.AbstractJqueryController
{
[WebMethod]
public void SaveBook()
{
Book book = GetModel<Book>();
book.save();
TxtJson = ReturnSuccess("保存书籍成功!");
}
[WebMethod]
public void SearchBook()
{
string schar = ParamsData["schar"];
int flag = Convert.ToInt32(ParamsData["flag"]); IBookDao bdao = NewDao<IBookDao>();
DataTable dt = bdao.GetBooks(schar, flag);
TxtJson = ToGridJson(dt);
} public void TestEntity()
{
//创建实体对象实例
Book book = NewObject<Book>(); //1.根据id获取一条记录
book= book.getmodel() as Book; //2.修改或者新增一条记录
book.BookName = "人月神话";
book.BuyPrice = ;
book.BuyDate = Convert.ToDateTime("2014-01-01");
book.save(); //3.根据id删除表数据
book.delete(); //4.获取表所有记录转换为List实体对象
List<Book> booklist = book.getlist<Book>(); //5.获取表所有记录转换为DataTable
DataTable dt = book.gettable();
}
}
}

我们先说Book.aspx文件,里面的代码是基于JqueryEasyUI框架编写的,实现了一个网格数据,上面有添加、修改工具栏按钮,点击按钮弹出维护界面;这些代码没有什么好讲得,等你熟悉JqueryEasyUI的相关控件后,就能很快的开发各种复杂界面;我们接着看Book.js脚本文件,是采用Jquery的方式编写javascript脚本;

十七、EnterpriseFrameWork框架核心类库之Web控制器

界面加载后就会执行这段代码,实现网格的数据显示,给datagrid控件设置url地址就会自动向后台发送Ajax请求,请求返回的Json数据datagrid控件解析后显示在界面;重点说一下这个url的参数意思,这是通往后台控制器的桥梁;controller指定后台控制器的名称bookController,method指定控制器内的方法名SearchBook,注意名称的大小写别搞错了;

十七、EnterpriseFrameWork框架核心类库之Web控制器

总结一下,Ajax向后台发送请求的URL必须采用Controller.aspx?controller=XXX&method=XXX这种格式,调试的时候控制器中打了断点没有进来,首先查看指定的控制器名称和方法名称是否正确;

2.Web控制器的设计思路

上文中举的实例是利用JqueryEasyUI开发的,如果我的项目不想要JqueryEasyUI,用更专业的Extjs或其他界面框架怎么办,EFW框架设计的时候充分的考虑到了这一点,我们看最上的“EFW框架控制器设计图”,bookController继承的是AbstractJqueryController对象,AbstractJqueryController对象又继承的AbstractController对象,AbstractController是Web控制器的核心基类,AbstractJqueryController就是针对JqueryEasyUI框架实现的控制器,我们要实现Extjs框架,就只要想只要像AbstractJqueryController一样编写一个适合Extjs框架的控制器基类,我们的bookController继承它就行了;

还有比如我们还开发手机上运行的网页程序,同样可以用这种方式来实现,下一个版本会把jquery.mobile引入到EFW框架中;

十七、EnterpriseFrameWork框架核心类库之Web控制器

3.Web控制器基类AbstractController的实现

这里讲解一下Web控制器的核心基类AbstractController的代码实现;

AbstractController文件

 public abstract class AbstractController:AbstractBusines
{
public AbstractDatabase oleDb
{
get
{
return _oleDb;
}
} public SysLoginRight GetSysLoginRight
{
get
{
if (sessionData != null && sessionData.ContainsKey("RoleUser"))
{
return (SysLoginRight)sessionData["RoleUser"];
}
else
{
return new SysLoginRight();
}
}
} public HttpContext context { get; set; } private System.Collections.Generic.Dictionary<string, Object> _sessionData;
/// <summary>
/// Session数据传入后台
/// </summary>
public System.Collections.Generic.Dictionary<string, Object> sessionData
{
get
{
return _sessionData;
}
set
{
_sessionData = value;
}
} private System.Collections.Generic.Dictionary<string, Object> _putOutData;
/// <summary>
/// 后台传出数据到Session数据
/// </summary>
public System.Collections.Generic.Dictionary<string, Object> PutOutData
{
get
{
return _putOutData;
}
set
{
_putOutData = value;
}
} private List<string> _clearKey;
/// <summary>
/// 清除Session的数据
/// </summary>
public List<string> ClearKey
{
get { return _clearKey; }
set { _clearKey = value; }
} private System.Collections.Generic.Dictionary<string, string> _paramsData;
/// <summary>
/// Url参数传递数据
/// </summary>
public System.Collections.Generic.Dictionary<string, string> ParamsData
{
get { return _paramsData; }
set { _paramsData = value; }
} private System.Collections.Generic.Dictionary<string, string> _formData;
/// <summary>
/// Form提交的数据
/// </summary>
public System.Collections.Generic.Dictionary<string, string> FormData
{
get { return _formData; }
set { _formData = value; }
} }

AbstractController基类封装了三方面的内容:

1)数据库操作对象,这个我们之前第十章也讲过为什么要在控制器开放oleDb,这也是为了让框架分层使用起来更灵活,且兼容性强;

2)系统登录用户信息SysLoginRight,此属性封装了用户登录后的姓名、部门、机构等信息;这样在控制器中查询当前登录用户的数据时候会很简单;

3)网页中的数据,如请求参数、Session数据、表单数据等;从界面传进来的数据都可以从中获取;

4.Web控制器的自定义标签WebControllerAttribute和WebMethodAttribute

为了能让系统根据url中控制器名称和方法名称找到对应的代码执行,就像Webservice服务一样需要对Web控制器的类名和方法名上加上上面两个自定义标签;

十七、EnterpriseFrameWork框架核心类库之Web控制器

WebControllerAttribute文件

  [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class WebControllerAttribute : Attribute
{
string _memo;
public string Memo
{
get { return _memo; }
set { _memo = value; }
}
}

WebMethodAttribute文件

  [AttributeUsageAttribute(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class WebMethodAttribute : Attribute
{
private string _openDBNames;
/// <summary>
/// 打开数据库,中间用,号隔开
/// </summary>
public string OpenDBKeys
{
get { return _openDBNames; }
set { _openDBNames = value; }
} string _memo;
public string Memo
{
get { return _memo; }
set { _memo = value; }
}
}

值得注意的就是,控制器的名称在整个系统中不能重复,如果出现相同名称的控制器,系统就可能无法正确调用对应的控制器;

5.基于JqueryEasyUI封装的Web控制器的实现

接下来讲解一下基于JqueryEasyUI封装的AbstractJqueryController的代码是如何实现的;AbstractJqueryController类继承了IToJqueryEasyUIJson接口,IToJqueryEasyUIJson接口就是提取出了把数据对象转换为符合JqueryEasyUI控件的Json字符串的方法;如:datagrid控件、Tree控件、treegrid控件等

IToJqueryEasyUIJson接口文件

 /// <summary>
/// 对象转与JqueryEasyUI匹配的Json格式
/// </summary>
public interface IToJqueryEasyUIJson
{ string TxtJson { get; set; }
string FilterJson(string json);//过滤json字符串中所有特殊字符 string ToJson(object model);
string ToJson(System.Data.DataTable dt);//转json字符串,combobox控件用此方法
string ToJson(Hashtable hash); string ToGridJson(string tojson, int totalCount);
string ToGridJson(string rowsjson, string footjson, int totalCount); string ToGridJson(System.Data.DataTable dt);
string ToGridJson(System.Data.DataTable dt, int totalCount);
string ToGridJson(System.Data.DataTable dt, int totalCount, System.Collections.Hashtable[] footers); string ToGridJson(System.Collections.IList list);
string ToGridJson(System.Collections.IList list, int totalCount);
string ToGridJson(System.Collections.IList list, int totalCount, System.Collections.Hashtable[] footers); string ToFloorJson(List<floorclass> floor);
string ToFloorJson(List<floorclass> floor, int totalCount); string ToTreeJson(List<treeNode> list); string ToTreeGridJson(List<treeNodeGrid> list);
string ToTreeGridJson(List<treeNodeGrid> list, System.Collections.Hashtable[] footers);
string ToTreeGridJson(DataTable dt, string IdName, string _parentIdName);
string ToTreeGridJson(DataTable dt, string IdName, string _parentIdName, System.Collections.Hashtable[] footers);
string ToTreeGridJson(string rowsjson, string footjson, int totalCount); T GetModel<T>();//从form表单提交的数据转为实体对象
T GetModel<T>(T model);//从form表单提交的数据赋值给model DataTable ToDataTable(string json);
List<T> ToList<T>(string json); string ReturnSuccess();
string ReturnSuccess(string info);
string ReturnSuccess(string info, string data);
string ReturnError(string errmsg); string ToView();//回退
string ToView(string info);//提示后再回退
string ToView(string info, string Url);//提示后调整到执行页面 }

AbstractJqueryController文件

 /// <summary>
/// 基于JqueryEasyUI框架的Web控制器基类
/// </summary>
public abstract class AbstractJqueryController : AbstractController, IToJqueryEasyUIJson
{
private string _txtJson; public string TxtJson
{
get { return _txtJson; }
set { _txtJson = value; }
} #region IController2 成员 public string FilterJson(string json)
{
throw new NotImplementedException();
} public string ToJson(object model)
{
string value = JavaScriptConvert.SerializeObject(model, new AspNetDateTimeConverter());
return value;
} public string ToJson(System.Data.DataTable dt)
{
string value = JavaScriptConvert.SerializeObject(dt);
return value;
} public string ToJson(System.Collections.Hashtable hash)
{
string value = JavaScriptConvert.SerializeObject(hash, new AspNetDateTimeConverter());
return value;
} public string ToGridJson(string rowsjson, int totalCount)
{
return ToGridJson(rowsjson, null, totalCount);
} public string ToGridJson(string rowsjson, string footjson, int totalCount)
{
if (footjson == null)
return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + "}";
else
return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + ",\"footer\":" + footjson + "}";
} public string ToGridJson(System.Data.DataTable dt)
{
return ToGridJson(dt, -, null);
} public string ToGridJson(System.Data.DataTable dt, int totalCount)
{
return ToGridJson(dt, totalCount, null);
} public string ToGridJson(System.Data.DataTable dt, int totalCount, System.Collections.Hashtable[] footers)
{
totalCount = totalCount == - ? dt.Rows.Count : totalCount;
string rowsjson = ToJson(dt);
string footjson = footers == null ? null : ToJson(footers);
return ToGridJson(rowsjson, footjson, totalCount);
} public string ToGridJson(System.Collections.IList list)
{
return ToGridJson(list, -, null);
} public string ToGridJson(System.Collections.IList list, int totalCount)
{
return ToGridJson(list, totalCount, null);
} public string ToGridJson(System.Collections.IList list, int totalCount, System.Collections.Hashtable[] footers)
{
totalCount = totalCount == - ? list.Count : totalCount;
string rowsjson = ToJson(list);
string footjson = footers == null ? null : ToJson(footers);
return ToGridJson(rowsjson, footjson, totalCount); } public string ToFloorJson(List<floorclass> floor)
{
return ToFloorJson(floor, floor.Count);
} public string ToFloorJson(List<floorclass> floor, int totalCount)
{
string Json = "{\"total\":" + totalCount + ",\"rows\":[";
string str = "";
for (int i = ; i < floor.Count; i++)
{
if (str == "")
{
str += "{\"floorid\":" + floor[i].floorid + ",\"floortext\":\"" + floor[i].floortext + "\",\"room\":";
}
else
{
str += ",{\"floorid\":" + floor[i].floorid + ",\"floortext\":\"" + floor[i].floortext + "\",\"room\":";
}
str += JavaScriptConvert.SerializeObject(floor[i].room);
str += "}";
}
Json += str;
Json += "]}"; return Json;
} public string ToTreeJson(List<treeNode> list)
{
JsonConverter converter = new AspNetDateTimeConverter();
string value = JavaScriptConvert.SerializeObject(list, converter);
value = value.Replace("check", "checked");
return value;
} public string ToTreeGridJson(List<treeNodeGrid> list)
{
return ToTreeGridJson(list, null);
} public string ToTreeGridJson(List<treeNodeGrid> list, System.Collections.Hashtable[] footers)
{
List<Hashtable> hashlist = new List<Hashtable>();
for (int i = ; i < list.Count; i++)
{
Hashtable hash = new Hashtable();
hash.Add("id", list[i].id);
if (list[i]._parentId > )
hash.Add("_parentId", list[i]._parentId);
if (!string.IsNullOrEmpty(list[i].state))
hash.Add("state", list[i].state);
if (!string.IsNullOrEmpty(list[i].iconCls))
hash.Add("iconCls", list[i].iconCls);
if (list[i].check)
hash.Add("check", list[i].check);
if (list[i].model != null)
{
PropertyInfo[] propertys = list[i].model.GetType().GetProperties();
for (int j = ; j < propertys.Length; j++)
{
if (!hash.ContainsKey(propertys[j].Name))
hash.Add(propertys[j].Name, propertys[j].GetValue(list[i].model, null));
}
} hashlist.Add(hash);
} int totalCount = hashlist.Count;
string rowsjson = ToJson(hashlist);
string footjson = footers == null ? null : ToJson(footers);
return ToTreeGridJson(rowsjson, footjson, totalCount);
} public string ToTreeGridJson(System.Data.DataTable dt, string IdName, string _parentIdName)
{
return ToTreeGridJson(dt, IdName, _parentIdName, null);
} public string ToTreeGridJson(System.Data.DataTable dt, string IdName, string _parentIdName, System.Collections.Hashtable[] footers)
{
List<Hashtable> hashlist = new List<Hashtable>();
for (int i = ; i < dt.Rows.Count; i++)
{
Hashtable hash = new Hashtable();
hash.Add("id", dt.Rows[i][IdName]);
if (Convert.ToInt32(dt.Rows[i][_parentIdName]) > )
hash.Add("_parentId", dt.Rows[i][_parentIdName]);
for (int j = ; j < dt.Columns.Count; j++)
{
if (dt.Columns[j].ColumnName.ToLower() == IdName.ToLower()) continue;
if (dt.Columns[j].ColumnName.ToLower() == _parentIdName.ToLower()) continue; hash.Add(dt.Columns[j].ColumnName, dt.Rows[i][j]);
}
hashlist.Add(hash);
} int totalCount = hashlist.Count;
string rowsjson = ToJson(hashlist);
string footjson = footers == null ? null : ToJson(footers);
return ToTreeGridJson(rowsjson, footjson, totalCount);
} public string ToTreeGridJson(string rowsjson, string footjson, int totalCount)
{
if (footjson == null)
return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + "}";
else
return "{\"total\":" + totalCount + ",\"rows\":" + rowsjson + ",\"footer\":" + footjson + "}";
} public T GetModel<T>()
{
T model = NewObject<T>();
return GetModel<T>(model);
} public T GetModel<T>(T model)
{
System.Reflection.PropertyInfo[] propertys = model.GetType().GetProperties();
for (int j = ; j < propertys.Length; j++)
{
if (propertys[j].Name == "WorkId") break;
if (FormData.ContainsKey(propertys[j].Name) == true)
{
if (propertys[j].PropertyType.Equals(typeof(Int32)))
propertys[j].SetValue(model, Convert.ToInt32(FormData[propertys[j].Name].Trim() == "" ? "" : FormData[propertys[j].Name]), null);
else if (propertys[j].PropertyType.Equals(typeof(Int64)))
propertys[j].SetValue(model, Convert.ToInt64(FormData[propertys[j].Name].Trim() == "" ? "" : FormData[propertys[j].Name]), null);
else if (propertys[j].PropertyType.Equals(typeof(decimal)))
propertys[j].SetValue(model, Convert.ToDecimal(FormData[propertys[j].Name].Trim() == "" ? "" : FormData[propertys[j].Name]), null);
else if (propertys[j].PropertyType.Equals(typeof(DateTime)))
propertys[j].SetValue(model, Convert.ToDateTime(FormData[propertys[j].Name].Trim() == "" ? DateTime.Now.ToString() : FormData[propertys[j].Name]), null);
else
propertys[j].SetValue(model, FormData[propertys[j].Name], null);
}
} return model;
} public System.Data.DataTable ToDataTable(string json)
{
throw new NotImplementedException();
} public List<T> ToList<T>(string json)
{
Newtonsoft.Json.JavaScriptArray jsonArray = (Newtonsoft.Json.JavaScriptArray)Newtonsoft.Json.JavaScriptConvert.DeserializeObject(json); List<T> list = new List<T>();
T model = NewObject<T>(); System.Reflection.PropertyInfo[] propertys = model.GetType().GetProperties(); for (int i = ; i < jsonArray.Count; i++)
{
T _model = (T)((ICloneable)model).Clone(); Newtonsoft.Json.JavaScriptObject Jobject = ((Newtonsoft.Json.JavaScriptObject)((Newtonsoft.Json.JavaScriptArray)jsonArray)[i]);
for (int n = ; n < Jobject.Count; n++)
{
for (int j = ; j < propertys.Length; j++)
{
if (propertys[j].Name == "WorkId") break;
if (Jobject.ToList()[n].Key.Trim().ToUpper() == propertys[j].Name.ToUpper())
{ if (propertys[j].PropertyType.Equals(typeof(Int32)))
propertys[j].SetValue(_model, Convert.ToInt32(Jobject.ToList()[n].Value.ToString().Trim() == "" ? : Jobject.ToList()[n].Value), null);
else if (propertys[j].PropertyType.Equals(typeof(Int64)))
propertys[j].SetValue(_model, Convert.ToInt64(Jobject.ToList()[n].Value.ToString().Trim() == "" ? : Jobject.ToList()[n].Value), null);
else if (propertys[j].PropertyType.Equals(typeof(decimal)))
propertys[j].SetValue(_model, Convert.ToDecimal(Jobject.ToList()[n].Value.ToString().Trim() == "" ? : Jobject.ToList()[n].Value), null);
else if (propertys[j].PropertyType.Equals(typeof(DateTime)))
propertys[j].SetValue(_model, Convert.ToDateTime(Jobject.ToList()[n].Value.ToString().Trim() == "" ? DateTime.Now.ToString() : Jobject.ToList()[n].Value), null);
else
propertys[j].SetValue(_model, Jobject.ToList()[n].Value.ToString(), null);
break;
}
}
}
list.Add(_model);
} return list;
} public string ReturnSuccess()
{
return ReturnSuccess(null, null);
} public string ReturnSuccess(string info)
{
return ReturnSuccess(info, null);
} public string ReturnSuccess(string info, string data)
{
info = info == null ? "" : info;
data = data == null ? "\"\"" : data;
return "{\"ret\":0,\"msg\":" + "\"" + info + "\"" + ",\"data\":" + data + "}";
} public string ReturnError(string errmsg)
{
return "{\"ret\":1,\"msg\":" + "\"" + errmsg + "\"" + "}";
} public string ToView()
{
return ToView(null, null);
} public string ToView(string info)
{
return ToView(info, null);
} public string ToView(string info, string Url)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language=\"javascript\" type=\"text/javascript\">\n");
if (info != null)
sb.Append("alert('" + info + "');\n");
if (Url != null)
sb.Append("window.location.href='" + Url + "'\n");
sb.Append("history.back();\n");
sb.Append("</script>\n");
return sb.ToString();
} #endregion
}

开发一个新界面框架的Web控制器,一定要先设计好数据转换接口,因为到时候继承它的所有控制器都会使用这些封装的方法进行数据转换,到时候再改动此接口影响的代码就多啦;

还有就是TxtJson这个属性,系统就是把此属性中的数据输出到界面上的;

为什么要再EFW框架中默认使用JqueryEasyUI了,最主要的是学习成本底,基本上花的几个小时属性一下Demo中的控件就会用了;还有就是它是基于Jquery开发的,所以自己也可以再基础上进行一些扩展开发,能够满足一些特殊的需求;刚开始项目中是用的Extjs开发,就是因为学习成本太高了,一个新手一开始根本摸不到边,特别是设计界面与操作数据都是用JS代码,代码编写得规范的还好,编写得不好的,真的是太难看了;而我选择JqueryeasyUI另一点就是设计界面不用js代码,用html标签代码就可以搞定,非常方便;

6.Web常用组件封装成控制器

Web系统中一些常用到的组件也封装成独立的控制器方便使用:

1)调试控制器DebugController

 /// <summary>
/// 控制器调试
/// </summary>
[WebController]
public class DebugController : AbstractController
{
private List<Hashtable> getHashList(string[] str)
{
List<Hashtable> hashlist = new List<Hashtable>();
for (int i = ; i < str.Length; i++)
{
Hashtable hash = new Hashtable();
hash.Add("code", i);
hash.Add("Name", str[i]);
hashlist.Add(hash);
}
return hashlist;
} [WebMethod]
public void GetControllerClassNameData()
{
List<Cmd_Controller> cmd = (List<Cmd_Controller>)AppGlobal.cache.GetData("cmdWebController");
List<string> classlist =new List<string>();
for (int i = ; i < cmd.Count; i++)
{
classlist.Add(cmd[i].controllerName);
}
context.Response.Charset = "UTF-8";
//把数据输出到页面
context.Response.Write(JavaScriptConvert.SerializeObject(getHashList(classlist.ToArray())));
} [WebMethod]
public void GetControllerMethodNameData()
{
List<string> methodlist = new List<string>(); string ClassName = ParamsData["ClassName"];
List<Cmd_Controller> cmd = (List<Cmd_Controller>)AppGlobal.cache.GetData("cmdWebController");
Cmd_Controller cmdC = cmd.Find(x => x.controllerName == ClassName);
if (cmdC != null)
{
for (int i = ; i < cmdC.cmdMethod.Count; i++)
{
methodlist.Add(cmdC.cmdMethod[i].methodName);
}
} context.Response.Charset = "UTF-8";
//把数据输出到页面
context.Response.Write(JavaScriptConvert.SerializeObject(getHashList(methodlist.ToArray())));
}
}

十七、EnterpriseFrameWork框架核心类库之Web控制器

2)登录验证码ImageUniqueCode

 /// <summary>
/// 登录验证码控制器
/// </summary>
public class ImageUniqueCode : AbstractController
{
public static readonly string ImageUniqueCode_Session = "ImageUniqueCode"; public void CreateCode()
{
context.Response.ContentType = "image/gif";
//建立Bitmap对象,绘图
Bitmap basemap = new Bitmap(, );
Graphics graph = Graphics.FromImage(basemap);
graph.FillRectangle(new SolidBrush(Color.White), , , , );
Font font = new Font(FontFamily.GenericSerif, , FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
string letter;
StringBuilder s = new StringBuilder(); //添加随机字符
for (int x = ; x < ; x++)
{
letter = letters.Substring(r.Next(, letters.Length - ), );
s.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * , r.Next(, ));
} //混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), );
for (int x = ; x < ; x++)
graph.DrawLine(linePen, new Point(r.Next(, ), r.Next(, )), new Point(r.Next(, ), r.Next(, ))); //将图片保存到输出流中
basemap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
context.Session[ImageUniqueCode_Session] = s.ToString();
} public void CreateNumCode()
{
context.Response.ContentType = "image/gif";
//建立Bitmap对象,绘图
Bitmap basemap = new Bitmap(, );
Graphics graph = Graphics.FromImage(basemap);
graph.FillRectangle(new SolidBrush(Color.White), , , , );
Font font = new Font(FontFamily.GenericSerif, , FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "";
string letter;
StringBuilder s = new StringBuilder(); //添加随机字符
for (int x = ; x < ; x++)
{
letter = letters.Substring(r.Next(, letters.Length - ), );
s.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * , r.Next(, ));
} //混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), );
for (int x = ; x < ; x++)
graph.DrawLine(linePen, new Point(r.Next(, ), r.Next(, )), new Point(r.Next(, ), r.Next(, ))); //将图片保存到输出流中
basemap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
context.Session[ImageUniqueCode_Session] = s.ToString();
} public void CheckCode()
{
string code = ParamsData["UniqueCode"];
if (code.ToUpper() == sessionData[ImageUniqueCode_Session].ToString().ToUpper())
{
context.Response.Write("");
}
else
{
context.Response.Write("");
}
}
}

3)上传下载文件kindeditorUpload

 /// <summary>
/// kindeditor控件上传下载的操作控制器
/// </summary>
public class kindeditorUpload : AbstractController
{
public void uploadfile()
{
//String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); //文件保存目录路径
String savePath = @"~/userfiles/"; //文件保存目录URL
String saveUrl = @"/userfiles/"; //定义允许上传的文件扩展名
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
extTable.Add("flash", "swf,flv");
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //最大文件大小
int maxSize = ;
this.context = context; HttpPostedFile imgFile = context.Request.Files["imgFile"];
if (imgFile == null)
{
showError("请选择文件。");
} String dirPath = context.Server.MapPath(savePath);
if (!Directory.Exists(dirPath))
{
showError("上传目录不存在。");
} String dirName = context.Request.QueryString["dir"];
if (String.IsNullOrEmpty(dirName))
{
dirName = "image";
}
if (!extTable.ContainsKey(dirName))
{
showError("目录名不正确。");
} String fileName = imgFile.FileName;
String fileExt = Path.GetExtension(fileName).ToLower(); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
{
showError("上传文件大小超过限制。");
} if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring().ToLower()) == -)
{
showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
} //创建文件夹
dirPath += dirName + "/";
saveUrl += dirName + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
dirPath += ymd + "/";
saveUrl += ymd + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
} String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + fileExt;
String filePath = dirPath + newFileName; imgFile.SaveAs(filePath); String fileUrl = saveUrl + newFileName; Hashtable hash = new Hashtable();
hash["error"] = ;
hash["url"] = fileUrl;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JavaScriptConvert.SerializeObject(hash));
context.Response.End(); } public void filemanager()
{
//String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1); //根目录路径,相对路径
String rootPath = @"~/userfiles/";
//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
String rootUrl = @"/userfiles/";
//图片扩展名
String fileTypes = "gif,jpg,jpeg,png,bmp"; String currentPath = "";
String currentUrl = "";
String currentDirPath = "";
String moveupDirPath = ""; String dirPath = context.Server.MapPath(rootPath);
String dirName = context.Request.QueryString["dir"];
if (!String.IsNullOrEmpty(dirName))
{
if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -)
{
context.Response.Write("Invalid Directory name.");
context.Response.End();
}
dirPath += dirName + "/";
rootUrl += dirName + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
} //根据path参数,设置各路径和URL
String path = context.Request.QueryString["path"];
path = String.IsNullOrEmpty(path) ? "" : path;
if (path == "")
{
currentPath = dirPath;
currentUrl = rootUrl;
currentDirPath = "";
moveupDirPath = "";
}
else
{
currentPath = dirPath + path;
currentUrl = rootUrl + path;
currentDirPath = path;
moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
} //排序形式,name or size or type
String order = context.Request.QueryString["order"];
order = String.IsNullOrEmpty(order) ? "" : order.ToLower(); //不允许使用..移动到上一级目录
if (Regex.IsMatch(path, @"\.\."))
{
context.Response.Write("Access is not allowed.");
context.Response.End();
}
//最后一个字符不是/
if (path != "" && !path.EndsWith("/"))
{
context.Response.Write("Parameter is not valid.");
context.Response.End();
}
//目录不存在或不是目录
if (!Directory.Exists(currentPath))
{
context.Response.Write("Directory does not exist.");
context.Response.End();
} //遍历目录取得文件信息
string[] dirList = Directory.GetDirectories(currentPath);
string[] fileList = Directory.GetFiles(currentPath); switch (order)
{
case "size":
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new SizeSorter());
break;
case "type":
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new TypeSorter());
break;
case "name":
default:
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new NameSorter());
break;
} Hashtable result = new Hashtable();
result["moveup_dir_path"] = moveupDirPath;
result["current_dir_path"] = currentDirPath;
result["current_url"] = currentUrl;
result["total_count"] = dirList.Length + fileList.Length;
List<Hashtable> dirFileList = new List<Hashtable>();
result["file_list"] = dirFileList;
for (int i = ; i < dirList.Length; i++)
{
DirectoryInfo dir = new DirectoryInfo(dirList[i]);
Hashtable hash = new Hashtable();
hash["is_dir"] = true;
hash["has_file"] = (dir.GetFileSystemInfos().Length > );
hash["filesize"] = ;
hash["is_photo"] = false;
hash["filetype"] = "";
hash["filename"] = dir.Name;
hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
dirFileList.Add(hash);
}
for (int i = ; i < fileList.Length; i++)
{
FileInfo file = new FileInfo(fileList[i]);
Hashtable hash = new Hashtable();
hash["is_dir"] = false;
hash["has_file"] = false;
hash["filesize"] = file.Length;
hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring().ToLower()) >= );
hash["filetype"] = file.Extension.Substring();
hash["filename"] = file.Name;
hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
dirFileList.Add(hash);
}
context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
context.Response.Write(JavaScriptConvert.SerializeObject(result));
context.Response.End(); } private void showError(string message)
{
Hashtable hash = new Hashtable();
hash["error"] = ;
hash["message"] = message;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JavaScriptConvert.SerializeObject(hash));
context.Response.End();
} }

4)图表显示WebFusionChart

 public delegate object DelegateChart(XmlDocument xmldoc);

     public static class WebFusionChart
{
public static XmlDocument CreateChartXML()
{
StringBuilder sb = new StringBuilder();
sb.Append("<graph>");
sb.Append("</graph>");
XmlDocument _xmlDoc = new XmlDocument();
_xmlDoc.LoadXml(sb.ToString()); return _xmlDoc;
} /// <summary>
/// 根据XML数据文件创建对象
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static XmlDocument CreateChartXML(string filename)
{
XmlDocument _xmlDoc = new XmlDocument();
_xmlDoc.Load(filename);
return _xmlDoc;
}
/// <summary>
///
/// </summary>
/// <param name="chartXML"></param>
/// <param name="AttributeName"></param>
/// <param name="AttributeValue"></param>
public static void AddgraphAttribute(XmlDocument chartXML, string AttributeName, string AttributeValue)
{
chartXML.DocumentElement.SetAttribute(AttributeName, AttributeValue);
} public static void Addcategories(XmlDocument chartXML)
{
XmlElement xmlcategories = chartXML.CreateElement("categories");
chartXML.DocumentElement.AppendChild(xmlcategories);
} public static void AddcategoriesAttribute(XmlDocument chartXML, int index, string AttributeName, string AttributeValue)
{
((XmlElement)chartXML.DocumentElement.SelectNodes("categories")[index]).SetAttribute(AttributeName, AttributeValue);
} public static void Addcategory(XmlDocument chartXML, int index)
{
XmlElement xmlcategory = chartXML.CreateElement("category");
chartXML.DocumentElement.SelectNodes("categories")[index].AppendChild(xmlcategory);
} public static void AddcategoryAttribute(XmlDocument chartXML, int index, int index2, string AttributeName, string AttributeValue)
{
((XmlElement)chartXML.DocumentElement.SelectNodes("categories")[index].SelectNodes("category")[index2]).SetAttribute(AttributeName, AttributeValue);
} public static void Adddataset(XmlDocument chartXML)
{
XmlElement xmldataset = chartXML.CreateElement("dataset");
chartXML.DocumentElement.AppendChild(xmldataset);
} public static void AdddatasetAttribute(XmlDocument chartXML, int index, string AttributeName, string AttributeValue)
{
((XmlElement)chartXML.DocumentElement.SelectNodes("dataset")[index]).SetAttribute(AttributeName, AttributeValue);
} public static void Addset(XmlDocument chartXML, int index)
{
XmlElement xmlset = chartXML.CreateElement("set");
chartXML.DocumentElement.SelectNodes("dataset")[index].AppendChild(xmlset);
} public static void AddsetAttribute(XmlDocument chartXML, int index, int index2, string AttributeName, string AttributeValue)
{
((XmlElement)chartXML.DocumentElement.SelectNodes("dataset")[index].SelectNodes("set")[index2]).SetAttribute(AttributeName, AttributeValue);
} public static string chartXMLtoJson(XmlDocument chartXML)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
chartXML.Save(sw);
string xmlstr = sw.ToString();
xmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Replace("\r\n", "").Replace("\"", "'");
return "{\"data\":\"" + xmlstr + "\"}";
} public static string chartXMLtoJson(XmlDocument chartXML, int rowNum)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
chartXML.Save(sw);
string xmlstr = sw.ToString();
xmlstr = xmlstr.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Replace("\r\n", "").Replace("\"", "'");
return "{\"data\":\"" + xmlstr + "\",\"rowNum\":\"" + rowNum.ToString() + "\"}";
} public static string GetLineChartXmlDataDemo1()
{
XmlDocument xmlchart = CreateChartXML(); AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "lineThickness", "");
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "numVDivLines", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "yAxisMinValue", "");
AddgraphAttribute(xmlchart, "shadowAlpha", ""); Addcategories(xmlchart);
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , , "Name", "Jan");
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , , "Name", "Feb");
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , , "Name", "Mar"); Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, , "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, , "color", "A66EDD");
AdddatasetAttribute(xmlchart, , "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, , "anchorRadius", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", ""); Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, , "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, , "color", "A66EDD");
AdddatasetAttribute(xmlchart, , "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, , "anchorRadius", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", "");
Addset(xmlchart, );
AddsetAttribute(xmlchart, , , "value", ""); return chartXMLtoJson(xmlchart);
} public static string GetLineChartXmlDataDemo2()
{
DataTable dt = new DataTable();
DelegateChart chart = delegate(XmlDocument xmlchart)
{
AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "lineThickness", "");
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "numVDivLines", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "yAxisMinValue", "");
AddgraphAttribute(xmlchart, "shadowAlpha", "");
return xmlchart;//?
};
return CreateLineXMLData(dt, chart);
} public static string CreateLineXMLData(DataTable dt, DelegateChart chart)
{
XmlDocument xmlchart = CreateChartXML(); AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "lineThickness", "");
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "numVDivLines", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "yAxisMinValue", "");
AddgraphAttribute(xmlchart, "shadowAlpha", ""); Addcategories(xmlchart);
//创建X轴
for (int i = ; i < dt.Rows.Count; i++)
{
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , , "Name", dt.Rows[i][].ToString());
} //画线
for (int i = ; i < dt.Columns.Count; i++)//多少条线
{
Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, i - , "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, i - , "color", "A66EDD");
AdddatasetAttribute(xmlchart, i - , "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, i - , "anchorRadius", ""); for (int j = ; j < dt.Rows.Count; j++)//画每条线的点的位置
{
Addset(xmlchart, j);
AddsetAttribute(xmlchart, i - , j, "value", dt.Rows[j][i].ToString());
}
} if (chart != null)
chart(xmlchart); return chartXMLtoJson(xmlchart);
} public static string CreateLineXMLData(DataTable dt, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes)
{
DelegateChart chart = delegate(XmlDocument xmlchart)
{
AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "lineThickness", "");
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "numVDivLines", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "yAxisMinValue", "");
AddgraphAttribute(xmlchart, "shadowAlpha", "");
return xmlchart;//?
};
return CreateLineXMLData(dt, chart, chartAttribute, categoriesColumn, valueColumns, valueAttributes);
}
/// <summary>
/// 创建图表线数据源的方法
/// </summary>
/// <param name="dt">数据集</param>
/// <param name="chart">回调函数用来数据源属性</param>
/// <param name="chartAttribute">数据源根节点属性</param>
/// <param name="categoriesColumn">指定dt数据集中列名一致的列值为X轴内容</param>
/// <param name="valueColumns">指定dt数据集中列名一致的数组列值为线的值,可以有多条线</param>
/// <param name="valueAttributes">给每条线赋相关属性值</param>
/// <returns></returns>
public static string CreateLineXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes)
{
XmlDocument xmlchart = CreateChartXML();
AddgraphAttribute(xmlchart, "caption", "XXXXXX统计");//主标题
AddgraphAttribute(xmlchart, "subcaption", "2009年");//子标题
AddgraphAttribute(xmlchart, "xAxisName", "月份");//x轴标题
AddgraphAttribute(xmlchart, "yAxisName", "销售额");//y轴标题
AddgraphAttribute(xmlchart, "yAxisMinValue", "");//y轴最小值
AddgraphAttribute(xmlchart, "numVDivLines", "");//y抽分隔线条数
AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");//y轴值得单位
AddgraphAttribute(xmlchart, "lineThickness", "");//折线的粗细
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "shadowAlpha", ""); if (chartAttribute != null)
{
foreach (DictionaryEntry de in chartAttribute)
{
AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString());
}
} Addcategories(xmlchart);
//创建X轴
for (int i = ; i < dt.Rows.Count; i++)
{
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , i, "Name", dt.Rows[i][categoriesColumn].ToString());
} //画线
for (int i = ; i < valueColumns.Length; i++)//多少条线
{
Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, i, "color", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorRadius", ""); if (valueAttributes != null)
{
foreach (DictionaryEntry de in valueAttributes[i])
{
AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString());
}
} for (int j = ; j < dt.Rows.Count; j++)//画每条线的点的位置
{
Addset(xmlchart, i);
AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString());
}
} if (chart != null)
chart(xmlchart); return chartXMLtoJson(xmlchart, dt.Rows.Count);
} /// <summary>
/// 创建图表具状图数据源的方法
/// </summary>
/// <param name="dt">数据集</param>
/// <param name="chart">回调函数用来数据源属性</param>
/// <param name="chartAttribute">数据源根节点属性</param>
/// <param name="categoriesColumn">指定dt数据集中列名一致的列值为X轴内容</param>
/// <param name="valueColumns">指定dt数据集中列名一致的数组列值为线的值,可以有多条线</param>
/// <param name="valueAttributes">给每条线赋相关属性值</param>
/// <returns></returns>
public static string CreateColumnXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes)
{
XmlDocument xmlchart = CreateChartXML();
AddgraphAttribute(xmlchart, "caption", "XXXXXX统计");//主标题
AddgraphAttribute(xmlchart, "subcaption", "2009年");//子标题
AddgraphAttribute(xmlchart, "xAxisName", "月份");//x轴标题
AddgraphAttribute(xmlchart, "yAxisName", "销售额");//y轴标题
AddgraphAttribute(xmlchart, "yAxisMinValue", "");//y轴最小值
AddgraphAttribute(xmlchart, "numVDivLines", "");//y抽分隔线条数
AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");//y轴值得单位
AddgraphAttribute(xmlchart, "lineThickness", "");//折线的粗细
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "shadowAlpha", ""); if (chartAttribute != null)
{
foreach (DictionaryEntry de in chartAttribute)
{
AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString());
}
} Addcategories(xmlchart);
//创建X轴
for (int i = ; i < dt.Rows.Count; i++)
{
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , i, "Name", dt.Rows[i][categoriesColumn].ToString());
} //画线
for (int i = ; i < valueColumns.Length; i++)//多少条线
{
Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, i, "color", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorRadius", ""); if (valueAttributes != null)
{
foreach (DictionaryEntry de in valueAttributes[i])
{
AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString());
}
} for (int j = ; j < dt.Rows.Count; j++)//画每条线的点的位置
{
Addset(xmlchart, i);
AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString());
}
} if (chart != null)
chart(xmlchart); return chartXMLtoJson(xmlchart, dt.Rows.Count);
} /// <summary>
/// 创建图表饼图数据源的方法
/// </summary>
/// <param name="dt">数据集</param>
/// <param name="chart">回调函数用来数据源属性</param>
/// <param name="chartAttribute">数据源根节点属性</param>
/// <param name="categoriesColumn">指定dt数据集中列名一致的列值为X轴内容</param>
/// <param name="valueColumns">指定dt数据集中列名一致的数组列值为线的值,可以有多条线</param>
/// <param name="valueAttributes">给每条线赋相关属性值</param>
/// <returns></returns>
public static string CreatePieXMLData(DataTable dt, DelegateChart chart, Hashtable chartAttribute, string categoriesColumn, string[] valueColumns, Hashtable[] valueAttributes)
{
XmlDocument xmlchart = CreateChartXML();
AddgraphAttribute(xmlchart, "caption", "XXXXXX统计");//主标题
AddgraphAttribute(xmlchart, "subcaption", "2009年");//子标题
AddgraphAttribute(xmlchart, "xAxisName", "月份");//x轴标题
AddgraphAttribute(xmlchart, "yAxisName", "销售额");//y轴标题
AddgraphAttribute(xmlchart, "yAxisMinValue", "");//y轴最小值
AddgraphAttribute(xmlchart, "numVDivLines", "");//y抽分隔线条数
AddgraphAttribute(xmlchart, "numdivlines", "");
AddgraphAttribute(xmlchart, "numberPrefix", "$");//y轴值得单位
AddgraphAttribute(xmlchart, "lineThickness", "");//折线的粗细
AddgraphAttribute(xmlchart, "showValues", "");
AddgraphAttribute(xmlchart, "formatNumberScale", "");
AddgraphAttribute(xmlchart, "rotateNames", "");
AddgraphAttribute(xmlchart, "decimalPrecision", "");
AddgraphAttribute(xmlchart, "anchorRadius", "");
AddgraphAttribute(xmlchart, "anchorBgAlpha", "");
AddgraphAttribute(xmlchart, "divLineAlpha", "");
AddgraphAttribute(xmlchart, "showAlternateHGridColor", "");
AddgraphAttribute(xmlchart, "shadowAlpha", ""); if (chartAttribute != null)
{
foreach (DictionaryEntry de in chartAttribute)
{
AddgraphAttribute(xmlchart, de.Key.ToString(), de.Value.ToString());
}
} Addcategories(xmlchart);
//创建X轴
for (int i = ; i < dt.Rows.Count; i++)
{
Addcategory(xmlchart, );
AddcategoryAttribute(xmlchart, , i, "Name", dt.Rows[i][categoriesColumn].ToString());
} //画线
for (int i = ; i < valueColumns.Length; i++)//多少条线
{
Adddataset(xmlchart);
AdddatasetAttribute(xmlchart, i, "seriesName", "Current Year");
AdddatasetAttribute(xmlchart, i, "color", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorBorderColor", "A66EDD");
AdddatasetAttribute(xmlchart, i, "anchorRadius", ""); if (valueAttributes != null)
{
foreach (DictionaryEntry de in valueAttributes[i])
{
AdddatasetAttribute(xmlchart, i, de.Key.ToString(), de.Value.ToString());
}
} for (int j = ; j < dt.Rows.Count; j++)//画每条线的点的位置
{
Addset(xmlchart, i);
AddsetAttribute(xmlchart, i, j, "value", dt.Rows[j][valueColumns[i]].ToString());
}
} if (chart != null)
chart(xmlchart); return chartXMLtoJson(xmlchart, dt.Rows.Count);
}
}

5)报表开发WebReportAll

  /// <summary>
/// Web报表封装帮助类
/// </summary>
public static class WebReportAll
{
/// <summary>
/// 转换为报表数据
/// </summary>
/// <param name="dtDetail">明细数据内容</param>
/// <returns></returns>
public static string ToReportData(DataTable dtDetail)
{
RAXmlDataSource xmlData = new RAXmlDataSource();
//xmlData.SetMaster(dtMaster, "");
xmlData.AddDetail("Detail1", dtDetail, "", "");
return xmlData.ExportToJson();
}
/// <summary>
/// 转换为报表数据
/// </summary>
/// <param name="dtMaster">报表页眉数据内容</param>
/// <param name="dtDetail">明细数据内容</param>
/// <returns></returns>
public static string ToReportData(DataTable dtMaster, DataTable dtDetail)
{
RAXmlDataSource xmlData = new RAXmlDataSource();
xmlData.SetMaster(dtMaster, "");
xmlData.AddDetail("Detail1", dtDetail, "", "");
return xmlData.ExportToJson();
}
/// <summary>
/// 转换为报表数据
/// </summary>
/// <param name="dtMaster">报表页眉数据内容</param>
/// <param name="dtDetails">多个明细数据内容</param>
/// <returns></returns>
public static string ToReportData(DataTable dtMaster, DataTable[] dtDetails)
{
RAXmlDataSource xmlData = new RAXmlDataSource();
xmlData.SetMaster(dtMaster, "");
for (int i = ; i < dtDetails.Length; i++)
{
xmlData.AddDetail("Detail" + (i + ).ToString(), dtDetails[i], "", "");
}
return xmlData.ExportToJson();
}
}

6)Excel导入导出ExcelHelper

 /// <summary>
/// 导出Excel
/// </summary>
public class ExcelHelper
{
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
/// <Author></Author>
public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
{
using (MemoryStream ms = Export(dtSource, strHeaderText, new Dictionary<string, string>()))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
} public static void Export(DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames, string strFileName)
{
using (MemoryStream ms = Export(dtSource, strHeaderText, columnNames))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
} /// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <Author> 2010-5-8 22:21:41</Author>
public static MemoryStream Export(DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); #region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "";
workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "曾浩"; //填加xls文件作者信息
si.ApplicationName = ""; //填加xls文件创建程序信息
si.LastAuthor = ""; //填加xls文件最后保存者信息
si.Comments = "说明信息"; //填加xls文件作者信息
si.Title = ""; //填加xls文件标题信息
si.Subject = "";//填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = ; i < dtSource.Rows.Count; i++)
{
for (int j = ; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
} int rowIndex = ;
int index = ;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet = (HSSFSheet)workbook.CreateSheet();
} #region 表头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow();
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(strHeaderText); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font); headerRow.GetCell().CellStyle = headStyle;
if (columnNames.Count > )
{
sheet.AddMergedRegion(new Region(, , , columnNames.Count - ));
}
else
sheet.AddMergedRegion(new Region(, , , dtSource.Columns.Count - ));
//headerRow.Dispose();
}
#endregion #region 列头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font); index = ;
foreach (DataColumn column in dtSource.Columns)
{
if (columnNames.Count > )
{
if (columnNames.ContainsKey(column.ColumnName))
{ headerRow.CreateCell(index).SetCellValue(columnNames[column.ColumnName]);
headerRow.GetCell(index).CellStyle = headStyle; //设置列宽
sheet.SetColumnWidth(index, (Encoding.GetEncoding().GetBytes(columnNames[column.ColumnName]).Length + ) * ); index++;
}
}
else
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + ) * );
}
}
//headerRow.Dispose();
}
#endregion rowIndex = ;
}
#endregion #region 填充内容
index = ;
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
if (columnNames.Count > )
{
if (columnNames.ContainsKey(column.ColumnName))
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(index); string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
} index++;
}
}
else
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal); string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
}
#endregion rowIndex++;
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Workbook.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放 sheet
return ms;
} } /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">文件名</param>
/// <Author> 2010-5-8 22:21:41</Author>
public static void ExportByWeb(HttpContext context, DataTable dtSource, string strHeaderText, Dictionary<string, string> columnNames, string strFileName)
{ HttpContext curContext = context; // 设置编码和附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, columnNames).GetBuffer());
//curContext.Response.End();
} /// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow();
int cellCount = headerRow.LastCellNum; for (int j = ; j < cellCount; j++)
{
HSSFCell cell = (HSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} for (int i = (sheet.FirstRowNum + ); i <= sheet.LastRowNum; i++)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
} dt.Rows.Add(dataRow);
}
return dt;
} }

7)模板引擎TemplateHelper

 /// <summary>
/// NVelocity模板引擎帮助类
/// </summary>
public class TemplateHelper
{
private VelocityEngine velocity = null;
private IContext context = null; public static string templatePath = "CodeTemplate"; public TemplateHelper()
{
velocity = new VelocityEngine(); //使用设置初始化VelocityEngine
ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); // props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
// props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); // props.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl\\,NVelocity"); velocity.Init(props);
//RuntimeConstants.RESOURCE_MANAGER_CLASS
//为模板变量赋值
context = new VelocityContext(); } /// <summary>
/// 给模板变量赋值
/// </summary>
/// <param name="key">模板变量</param>
/// <param name="value">模板变量值</param>
public void Put(string key, object value)
{
context.Put(key, value);
} /// <summary>
/// 生成字符
/// </summary>
/// <param name="templatFileName">模板文件名</param>
public string BuildString(string templateFile)
{
//从文件中读取模板
Template template = velocity.GetTemplate(templateFile); //合并模板
StringWriter writer = new StringWriter();
template.Merge(context, writer);
return writer.ToString();
} public bool ContainsKey(string keyName)
{
return context.ContainsKey(keyName);
} }

更多组件持续封装中!

上一篇:php学习网址


下一篇:十八、【开源】EnterpriseFrameWork框架核心类库之Winform控制器