测试代码
private List<string> CurrentCheckedItems
{
get
{
return (List<string>)ViewState["CurrentCheckedItems"] ?? new List<string>();
}
set
{
ViewState["CurrentCheckedItems"] = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
EpochSoft.CostController.Inteface.VoucherCommonAdapter.YingChunExcelAdapter yinc = new EpochSoft.CostController.Inteface.VoucherCommonAdapter.YingChunExcelAdapter();
EpochSoft.CostController.Inteface.Fundation.AdapterRequestInfo info = new EpochSoft.CostController.Inteface.Fundation.AdapterRequestInfo();
this.CurrentCheckedItems = this.GetCheckedList();
info.RequestInfo = this.CurrentCheckedItems.ToArray();
EpochSoft.CostController.Inteface.Fundation.AdapterResponseInfo resInfo = yinc.Run(info);
}
private List<string> GetCheckedList()
{
List<string> result = new List<string>();
//string[] languages = { "WLZDH20110316009", "WLZDH20110317002" };
string[] languages = { "8b9687a2-3125-4211-a743-9b0334e6fdb5", "53a443c2-ed6a-43b0-b427-0cff708433a3", "6f4e990a-0f27-404b-83f8-60d667f1b22f" };
for(int i=0;i<languages.Length;i++){
result.Add(languages[i].ToString());
}
return result;
}
using System;
using System.Collections.Generic;
using System.Text;
using EpochSoft.CostController.Inteface.Fundation;
using System.Data;
using EpochSoft.CostController.Inteface.VoucherCommonAdapter.ESVoucherService;
using System.Data.OleDb;
namespace EpochSoft.CostController.Inteface.VoucherCommonAdapter
{
public class YingChunExcelAdapter : ICommonAdapter
{
#region ICommonAdapter Members
/// <summary>
/// 中烟凭证审核时的处理逻辑是:
/// a.在控制系统的“凭证审核”页面审核完凭证后点击“凭证审核”按钮,凭证自动通过接口将凭证传给总账系统(NC)。
/// b.NC系统接受到控制系统传递凭证后验证凭证的正确性,如果正确无误,反馈凭证号给控制系统,控制系统记录该凭证号。如果错误,则反馈错误信息,控制系统接收错误信息并显示给操作人员。
/// </summary>
/// <param name="input">input.RequestInfo数据包含一个voucherDataID</param>
/// <returns></returns>
public AdapterResponseInfo Run(AdapterRequestInfo input)
{
VoucherService vs = new VoucherService();
int state = vs.Logon("Epochsoft", "Epochsoft");
//vs.ExportVoucherModel(new string[] { "" });
AdapterResponseInfo responseInfo = new AdapterResponseInfo(true);
try
{
DataTable dt = new DataTable("BillMainDataTable");
VoucherItem[] items = vs.ExportVoucherModelByVoucherDataIDs(input.RequestInfo);
if (input.RequestInfo[0].ToString() != null)
{
string auxiliaryAccounStr = string.Empty;
for (int i = 0; i < items[0].Body[0].AuxiliaryAccountingItem.Length; i++)
{
auxiliaryAccounStr += items[0].Body[0].AuxiliaryAccountingItem[i].DimName + ",";
}
for (int j = 0; j < items[0].Body[0].Field.Length; j++)
{
if (auxiliaryAccounStr.IndexOf(items[0].Body[0].Field[j].FieldName) == -1)
{
dt.Columns.Add(new DataColumn(items[0].Body[0].Field[j].FieldName, typeof(string)));
}
}
dt.Columns.Add(new DataColumn("辅助核算", typeof(string)));
for(int ii=0;ii<items.Length;ii++)
{
string auxiliaryAccountStr = string.Empty;
string auxiliaryStr = string.Empty;
for (int i = 0; i < items[0].Body[0].AuxiliaryAccountingItem.Length; i++)
{
auxiliaryStr += items[0].Body[0].AuxiliaryAccountingItem[i].DimName + ",";
auxiliaryAccountStr += items[ii].Body[0].AuxiliaryAccountingItem[i].DimName + "---" + items[ii].Body[0].AuxiliaryAccountingItem[i].MemberCode + "---" + items[ii].Body[0].AuxiliaryAccountingItem[i].MemberName + "||";
}
auxiliaryAccountStr = auxiliaryAccountStr.Substring(0, auxiliaryAccountStr.Length - 2);
DataRow row = dt.NewRow();
for (int j = 0; j < items[0].Body[0].Field.Length; j++)
{
if (auxiliaryAccountStr.IndexOf(items[0].Body[0].Field[j].FieldName) == -1)
{
row[items[0].Body[0].Field[j].FieldName] = items[ii].Body[0].Field[j].Value.ToString();
}
}
row["辅助核算"] = auxiliaryAccountStr;
dt.Rows.Add(row);
}
}
BizExcel ImportExcel = new BizExcel();
ImportExcel.Write(dt);
}
catch (Exception ex)
{
responseInfo.IsSuccess = false;
}
return new AdapterResponseInfo(true);
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Web;
namespace EpochSoft.CostController.Inteface.VoucherCommonAdapter
{
///描述:此类用于通过OleDB对Excel进行操作
///创建者:Lixzh
///最后更改日期:2010.3.26
///
/// <summary>
/// 此枚举用来声明,Excel第一行是否作为表头
/// </summary>
public enum HDR
{
No = 0,//第一行不作为表头
Yes = 1//第一行作为表头
}
/// <summary>
/// 此枚举用来告诉驱动程序使用Excel文件的模式
/// </summary>
public enum IMEX
{
Export = 0,//导出
Import = 1,//导入
Mix = 2//混合
}
/// <summary>
/// 此类用于通过OleDB对Excel进行操作
/// </summary>
public class BizExcel
{
#region 字段
/// <summary>
/// 连接字符串
/// </summary>
private readonly string OleDBConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR={1};IMEX={2}\"";
private string filePath = string.Empty;
private string oleDbConnection = string.Empty;
private string hdr_yes = "Yes";
private string hdr_no = "No";
#endregion
#region 构造函数
public BizExcel() : this(DefaultFilePath) { }
public BizExcel(string filePath) : this(filePath, HDR.No) { }
public BizExcel(string filePath, HDR hdr) : this(filePath, hdr, IMEX.Export) { }
public BizExcel(HDR hdr, IMEX imex) : this(DefaultFilePath, hdr, imex) { }
public BizExcel(string filePath, HDR hdr, IMEX imex)
{
this.filePath = filePath;
this.oleDbConnection = string.Format(this.OleDBConnection, filePath, this.GetHDRString(hdr), this.GetIMEXString(imex));
}
#endregion
#region 公有方法
public DataSet Read()
{
return this.Read(false);
}
public DataSet Read(bool deleteTmpFile)
{
this.EnsurePath();
DataSet ds = new DataSet();
using (OleDbConnection conn = this.CurrentConnection)
{
conn.Open();
this.CreateDataSet(ds, conn);
}
if (deleteTmpFile)
{
this.Dispose();
}
return ds;
}
public void Write(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
this.Write(dt);
}
}
public void Write(DataTable dt)
{
using (OleDbConnection conn = this.CurrentConnection)
{
conn.Open();
string createSql = this.GetCreateSql(dt);
this.ExecuteNonQuery(conn, createSql);
List<string> columns = this.GetColumns(dt);
foreach (DataRow dr in dt.Rows)
{
string insertSql = this.GetInsertSql(dt, columns, dr);
this.ExecuteNonQuery(conn, insertSql);
}
}
}
public void Dispose()
{
File.Delete(this.FilePath);
}
#endregion
#region 私有方法
private string GetInsertSql(DataTable dt, List<string> columns, DataRow dr)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("INSERT INTO [{0}] VALUES(", dt.TableName));
foreach (string columnName in columns)
{
object o = dr[columnName];
sb.Append(string.Format("\t'{0}',", o == null ? string.Empty : o.ToString()));
}
string insertSql = sb.ToString();
insertSql = (insertSql.EndsWith(",") ? insertSql.Substring(0, insertSql.LastIndexOf(",")) : insertSql) + ")";
return insertSql;
}
private void ExecuteNonQuery(OleDbConnection conn, string createSql)
{
OleDbCommand command = this.GetCommand(conn, createSql);
command.ExecuteNonQuery();
}
private string GetCreateSql(DataTable dt)
{
string dtName = dt.TableName;
List<string> columns = this.GetColumns(dt);
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("CREATE TABLE [{0}] (", dtName));
foreach (string columnName in columns)
{
sb.Append(string.Format(" [{0}] string,", columnName));
}
string createSql = sb.ToString();
createSql = (createSql.EndsWith(",") ? createSql.Substring(0, createSql.LastIndexOf(",")) : createSql) + ")";
return createSql;
}
/// <summary>
/// 创建数据集,把Excel文件读取到数据集中,并且每个Sheet都是一张表
/// </summary>
/// <param name="ds">数据集对象</param>
/// <param name="conn">连接对象</param>
private void CreateDataSet(DataSet ds, OleDbConnection conn)
{
List<string> sheets = this.GetExcelTables(conn);
foreach (string sheetName in sheets)
{
this.ReadSheetToTable(conn, sheetName, ds);
}
}
/// <summary>
/// 把Excel的Sheet读到DataTable中
/// </summary>
/// <param name="conn">连接对象</param>
/// <param name="sheetName">SheetName</param>
/// <returns>DataTable</returns>
private void ReadSheetToTable(OleDbConnection conn, string sheetName, DataSet ds)
{
OleDbCommand command = this.GetCommand(conn, string.Format(" SELECT * FROM [{0}$] ", sheetName));
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
ds.Tables.Add(new DataTable(sheetName));
adapter.Fill(ds, sheetName);
}
private OleDbCommand GetCommand(OleDbConnection conn, string sqlString)
{
OleDbCommand command = new OleDbCommand(sqlString, conn);
return command;
}
/// <summary>
/// 验证路径是否合法
/// </summary>
private void ValidatePath()
{
if (!File.Exists(this.filePath))
{
throw new FileNotFoundException();
}
}
/// <summary>
/// 验证路径是否合法
/// </summary>
private void EnsurePath()
{
this.ValidatePath();
}
private string GetHDRString()
{
return this.GetHDRString(HDR.No);
}
private string GetHDRString(HDR hdr)
{
return hdr == HDR.Yes ? hdr_yes : hdr_no;
}
private string GetIMEXString(IMEX imex)
{
return ((int)imex).ToString();
}
/// <summary>
/// 获取指定表名的所有列
/// </summary>
/// <param name="oConn">连接对象</param>
/// <param name="tableName">表名</param>
/// <returns>列名列表</returns>
private List<string> GetColumns(OleDbConnection oConn, string tableName)
{
DataTable columnTable = this.GetColumnTable(oConn, tableName);
List<string> colList = new List<string>();
foreach (DataRow dr in columnTable.Rows)
{
colList.Add(dr["Column_Name"].ToString());
}
return colList;
}
private List<string> GetColumns(DataTable dt)
{
List<string> result = new List<string>();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName);
}
return result;
}
private DataTable GetColumnTable(OleDbConnection oConn, string tableName)
{
DataTable columnTable = oConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName, null });
return columnTable;
}
/// <summary>
/// 获取指定Excel的所有列名
/// </summary>
/// <param name="oConn">连接对象</param>
/// <returns>表名列表</returns>
private List<string> GetExcelTables(OleDbConnection oConn)
{
DataTable t = this.GetTables(oConn);
List<string> tableNames = new List<string>();
foreach (DataRow dr in t.Rows)
{
string tableName = dr["Table_Name"].ToString();
string _name = string.Empty;
if (tableName.EndsWith("$"))
{
_name = dr["Table_Name"].ToString();
_name = _name.Substring(0, _name.Length - 1);
if (!tableNames.Contains(_name))
{
tableNames.Add(_name);
}
}
}
return tableNames;
}
private DataTable GetTables(OleDbConnection oConn)
{
DataTable t = oConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
return t;
}
#endregion
#region 属性
private OleDbConnection CurrentConnection
{
get
{
return new OleDbConnection(this.oleDbConnection);
}
}
public string FilePath
{
get
{
return this.filePath;
}
}
private static string DefaultFilePath
{
get
{
Guid newid = new Guid();
// return newid+".xls";// HttpContext.Current.Server.MapPath(BizCommon.TemplateFolder) + SysShared.GetNewGuid() + ".xls";
return HttpContext.Current.Server.MapPath("TemplateFolder") + System.Guid.NewGuid() + ".xls";
}
}
#endregion
}
}
posted @ 2011-11-17 12:33 liufei 阅读(11) 评论(0)
编辑
示例环境:VS2010
要求:
重写前:http://localhost:13275/Default.aspx?username=wilson
重写后:http://localhost:13275/wilson
第一步:下载相关DLL(ActionlessForm.dll和UrlRewriter.dll)
第二步:VS2010创建测试网站应用程序,并添加以上DLL的引用
PS: 操作步骤省略,我想都会
第三步:在项目中添加asp.net文件(App_Browsers)
App_Browsers这个我们比较少用
App_Browsers文件夹包含.browser文件,.browser文件是XML文件,可以标识向应用程序发出请求的浏览器,并理解这些浏览器的功能。
在C:\Windows\Microsoft.NET\ Framework\v2.0.50727\CONFIG\Browsers中有一个可全局访问的.browser文件列表。另外,如果要
修改这些默认的浏览器定义文件,只需将Browsers文件夹中的对应.browser文件复制到应用程序的\App_Browsers文件夹,修改其定义即可。
如果对这些Asp.Net文件夹了解不多可以看看这篇文章,相信很有帮助
1.选择项目--->右键添加--->添加asp.net文件夹--->App_Browsers
2.在App_Browsers下创建Form.browser文件
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
adapterType="URLRewriter.Form.FormRewriterControlAdapter"/>
</controlAdapters>
</browser>
</browsers>
PS: refID:不可以与ID和arentID同时存在
第四步:配置web.config
1 .在configuration节点下添加
<configSections>
<section name="CustomConfiguration" type="URLRewriter.Config.UrlsSection, URLRewriter"/>
</configSections>
<CustomConfiguration>
<urls>
<!--([\w]+)表示,1到n个字母或数字或下划线或汉字组成-->
<add virtualUrl="~/([\w]+)*" destinationUrl="~/Default.aspx?username=$1"/>
</urls>
</CustomConfiguration>
PS:正则的部分,要根据不同的规则去写,如果有不会的,可以留下详细规则,我看到后会尽快回复!!
2.在System.web节点下添加
<httpModules>
<add type="URLRewriter.RewriterModule, URLRewriter" name="RewriterModule"/>
</httpModules>
解释一下httpModules的的Add节点属性:
type:HttpModule的标识号和类库名称
name:取一个较为友好的名称
用MSDN的截图来解释一下
第五步:测式
1.在项目Default.aspx.cs文件Load事件中加入
if (!IsPostBack)
{
StringBuilder sb = new StringBuilder();
sb.Append("当前所在位置:Default.aspx<br/>");
if (!string.IsNullOrEmpty(Request.Params["username"]))
{
sb.Append("所接收到的参数username:" + Request.Params["username"]);
}
Response.Write(sb.ToString());
}
这里的测试主要是测试直接用重写后规则访问,看是否访问成功,并测试是否能够接收到username参数
还有输入重写前的地址,是否能访问成功
测试一:找开----->http://localhost:13275/Default.aspx
结果(aspx页输出)------>当前所在位置:Default.aspx
测试二:找开----->http://localhost:13275/wilson
结果(aspx页输出)------>当前所在位置:Default.aspx
所接收到的参数username:wilson
第六步:在IIS7.5里配置
完成前五步后,直接运行VS可以重写成功,但发布在IIS中时就会有相应的错误,这样需要配置一下IIS,详情请看下面博客地址
posted @ 2011-11-08 15:12 liufei 阅读(8) 评论(0)
编辑
在实际开发中,在数据库表设计中,我们往往习惯于用一个Int类型的State字段去表示数据的状态,这个字段很方便去表示这条数据的状态,但是又不愿意去建一张这个State字段的外键表去解释状态。(这一类型表状态的字段可能还会有很多,这里只是举个例)
我们一般会把这个State字段当成一个约定,去在项目中应用(比如:0:启用,1:禁用)
在后台管理或其它地方显示Int类型对应的实际状态时,再到公共类中去写一个方法,里面用一个switch...case去返回对应的中文解释。
但是我习惯于用一个Enum枚举去规范数据库去所有的State字段,Enum的使用,也更利于开发,可以分别对枚举注释,约定可以呈现在开发人员眼前,而不是直接凭空约定。下面分享一下我对Enum类的使用。
1.首先,我们可以对枚举类型建立一个实体类:ReadEnum
public class ReadEnum
{
public string Name { get; set; }
public int Value { get; set; }
}
2.第二步,创建State字段对应的枚举
#region##状态枚举(数据库里所有State枚举)
///<summary>
/// 状态枚举(数据库里所有State枚举)
/// 创建人:Porschev
/// 创建时间:2011-7-19
///</summary>
public enum ssnState
{
///<summary>
/// 启用
///</summary>
[Description("启用")]
Enabled = 0,
///<summary>
/// 禁用
///</summary>
[Description("禁用")]
Disable = 1
}
#endregion
如上面创建的枚举,开发者在使用枚举时一般都不会用到红色部分Description属性,它在System.ComponentModel命名空间下
有了它,我们完全可以不用以前使用的switch...case方法去释义或显示中文。
第三步:对所有Enum写一些应用方法
#region##获得Enum类型description
///<summary>
/// 获得Enum类型description
/// 创建人:Porschev
/// 创建时间:2011-7-19
///</summary>
///<param name="enumType">枚举的类型</param>
///<param name="val">枚举值</param>
///<returns>string</returns>
public static string GetEnumDesc(Type enumType, object val)
{
string enumvalue = System.Enum.GetName(enumType, val);
if (string.IsNullOrEmpty(enumvalue))
{
return "";
}
System.Reflection.FieldInfo finfo = enumType.GetField(enumvalue);
object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
if (enumAttr.Length > 0)
{
System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute;
if (desc != null)
{
return desc.Description;
}
}
return enumvalue;
}
#endregion
#region##获取某个枚举的全部信息
///<summary>
/// 获取某个枚举的全部信息
/// 创建人:Porschev
/// 创建时间:2011-7-19
///</summary>
///<typeparam name="T">枚举</typeparam>
///<returns>枚举的全部信息</returns>
public static List<ReadEnum> GetEnumList<T>()
{
List<ReadEnum> list = new List<ReadEnum>();
ReadEnum re = null;
Type type = typeof(T);
foreach (int enu in System.Enum.GetValues(typeof(T)))
{
re = new ReadEnum();
re.Name = GetEnumDesc(type, enu);
re.Value = enu;
list.Add(re);
}
return list;
}
#endregion
#region##根据值返回枚举对应的内容
///<summary>
/// 根据值返回枚举对应的内容
/// 创建人:Porschev
/// 创建时间:2011-7-19
///</summary>
///<typeparam name="T">枚举</typeparam>
///<param name="value">值(int)</param>
///<returns></returns>
public static T GetModel<T>(int value)
{
T myEnum = (T)System.Enum.Parse(typeof(T), value.ToString(), true);
return myEnum;
}
#endregion
#region##根据值返回枚举对应的内容
///<summary>
/// 根据值返回枚举对应的内容
/// 创建人:Porschev
/// 创建时间:2011-7-19
///</summary>
///<typeparam name="T">枚举</typeparam>
///<param name="value">值(string)</param>
///<returns></returns>
public static T GetModel<T>(string value)
{
T myEnum = (T)System.Enum.Parse(typeof(T), value, true);
return myEnum;
}
#endregion
这几个方法完全可以满足在项目中对Enum枚举的使用。
第四步:测式代码
string str = GetEnumDesc(typeof(ssnState), 0);
//结果:启用
List<ReadEnum> list = GetEnumList<ssnState>();
//结果:list.Count=2
// 第一个元素:Name:启用;Value:0
// 第二个元素:Name:禁用;Value:1
ssnState re = GetModel<ssnState>(0);
//结果:ssnState.Enabled
ssnState re1 = GetModel<ssnState>("0");
//结果:ssnState.Enabled
posted @ 2011-11-08 15:09 liufei 阅读(10) 评论(0)
编辑
采用Jquery无刷新分页插件jquery.pagination.js 实现无刷新分页效果
友情提示:本示例Handler中采用StringBuilder的append方法追加HTML,小数据量可以,但是大数据或是布局常变,建议返回JSON格式的数据,性能和灵活性更好!
1.插件参数列表

2.页面内容:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%>
<!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>Porschev----无刷新翻页</title>
<script src="Script/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Script/jquery.pagination.js" type="text/javascript"></script>
<script src="Script/tablecloth.js" type="text/javascript"></script>
<link href="Style/tablecloth.css" rel="stylesheet" type="text/css"/>
<link href="Style/pagination.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
var pageIndex =0; //页面索引初始值
var pageSize =10; //每页显示条数初始化,修改显示条数,修改这里即可
$(function() {
InitTable(0); //Load事件,初始化表格数据,页面索引为0(第一页)
//分页,PageCount是总条目数,这是必选参数,其它参数都是可选
$("#Pagination").pagination(<%=pageCount %>, {
callback: PageCallback,
prev_text: '上一页', //上一页按钮里text
next_text: '下一页', //下一页按钮里text
items_per_page: pageSize, //显示条数
num_display_entries: 6, //连续分页主体部分分页条目数
current_page: pageIndex, //当前页索引
num_edge_entries: 2//两侧首尾分页条目数
});
//翻页调用
function PageCallback(index, jq) {
InitTable(index);
}
//请求数据
function InitTable(pageIndex) {
$.ajax({
type: "POST",
dataType: "text",
url: 'Handler/PagerHandler.ashx', //提交到一般处理程序请求数据
data: "pageIndex="+ (pageIndex +1) +"&pageSize="+ pageSize, //提交两个参数:pageIndex(页面索引),pageSize(显示条数)
success: function(data) {
$("#Result tr:gt(0)").remove(); //移除Id为Result的表格里的行,从第二行开始(这里根据页面布局不同页变)
$("#Result").append(data); //将返回的数据追加到表格
}
});
}
});
</script>
</head>
<body>
<div align="center">
<h1>Posrchev----无刷新分页</h1>
</div>
<div id="container">
<table id="Result" cellspacing="0" cellpadding="0">
<tr>
<th>编号</th>
<th>名称</th>
</tr>
</table>
<div id="Pagination"></div>
</div>
</body>
</html>
3.页面.cs文件内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public string pageCount = string.Empty; //总条目数
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageCount = new PagerTestBLL.PersonManager().GetPersonCount().ToString();
}
}
}
4.Handler中的内容:
<%@ WebHandler Language="C#" Class="PagerHandler" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
public class PagerHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string str = string.Empty;
//具体的页面数
int pageIndex;
int.TryParse(context.Request["pageIndex"], out pageIndex);
//页面显示条数
int size = Convert.ToInt32(context.Request["pageSize"]);
if (pageIndex == 0)
{
pageIndex = 1;
}
int count;
List<PagerTestModels.Person> list = new PagerTestBLL.PersonManager().GetAllPerson(size, pageIndex, "", out count);
StringBuilder sb = new StringBuilder();
foreach (PagerTestModels.Person p in list)
{
sb.Append("<tr><td>");
sb.Append(p.Id.ToString());
sb.Append("</td><td>");
sb.Append(p.Name);
sb.Append("</td></tr>");
}
str = sb.ToString();
context.Response.Write(str);
}
public bool IsReusable {
get {
return false;
}
}
}
5.实现效果图:

6.源码下载地址一:http://download.csdn.net/source/2959451
下载地址二:http://files.cnblogs.com/zhongweiv/Pager.rar
posted @ 2011-11-08 14:54 liufei 阅读(36) 评论(0)
编辑
很多人提问,不知道C#位移,可能有些人在面试中也遇到过
其实很简单。。。
C#位移运算符:
左移:<<
右移:>>
位移理解可能简单一些:其实就是数据转换成二进制的左右移动;右移左补0,左移右补0,后面多出来的部分去掉。
用乘除法去理解位移也可以:
左位移:相当于乘
左移1位相当于乘2,左移2位相当于乘4,左移3位相当于乘8,左移4位相当于乘16...类推
右位移:相当于除
右移1位相当于除2,右移2位相当于除4,右移3位相当于除8,右移4位相当于除16...类推
下面用一个曾经回答一个网友的提问来理解一下位移的运算
题目:把89右位移一位:
string flag = Convert.ToString(89, 2); //这是把你的89转为2进制数。。
//flag结果:1011001
//你要右位移,左边补个0,后面多出来一位去掉
int j = Convert.ToInt32("0101100", 2); //再把2进制转化了10进制数。。
//结果:44
//位移就是这么简单
这样理解位移运算就很容易...
posted @ 2011-11-08 14:53 liufei 阅读(8) 评论(0)
编辑
1.添加cookies(用cookies方式去做sso,用户信息保存,修改都会依赖cookies)
HttpCookie cookies = new HttpCookie("Porschev"); |
cookies["name"] = "Zhong Wei"; |
cookies.Expires = DateTime.Now.AddMinutes(20); |
Response.Cookies.Add(cookies); |
添加cookies一般不会有人出错的。。。记得添加Expires就行
2.修改cookies( 在程序中难免会操作,对用户信息的修改,更新数据库后,也会修改cookies,为了修改后的显示)
方法一:
#region##修改cookies
///<summary>
/// 修改cookies
///</summary>
public void ModCookies()
{
HttpCookie cookies = Request.Cookies["Porschev"];
cookies["name"] = "wilson Z";
}
#endregion
新建个测式页。。再取cookies中的name,结果:wilson Z;
这是这次项目中遇到的“杯具”事件之一,当这样修改cookies时,在更新方法中再取这个名为Porschev的cookies,
name的值还为Zhong Wei而非wilson Z,页面显示也不对(己排除页面缓存原因,更新也确实没有成功)
修改方法一:
#region##修改cookies
///<summary>
/// 修改cookies
///</summary>
public void ModCookies()
{
HttpCookie cookies = Request.Cookies["Porschev"];
cookies["name"] = "wilson Z";
//加上下面一句
Response.Cookies["Porschev"].Expires = DateTime.Now.AddMinutes(-1);
}
#endregion
再次测式,结果正确,取出name的值为:wilson Z,页面显示也正确
自己理解:得让以前存入过期时间为20min的cookies失效
3.得到cookies (这个最简单,为求方法完整,还是写上吧)
#region##得到cookies
///<summary>
/// 得到cookies
///</summary>
public void GetCookies()
{
HttpCookie cookies = Request.Cookies["Porschev"];
string name = cookies["name"]; //通过key取出对应value,多key同理取
}
#endregion
4.删除cookies (删除cookies网上有很多方法,但是删除不是都能管用)
方法一:(最常用的一个删除cookies方法)
#region##删除cookies
///<summary>
/// 删除cookies
///</summary>
public void DelCookeis()
{
if (Request.Cookies["Porschev"] != null)
{
HttpCookie cookies = new HttpCookie("Porschev");
cookies.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookies);
}
}
#endregion
在项目中测式,删除部分cookies失败,很无语,于是换一种方法
#region##删除cookies
///<summary>
/// 删除cookies
///</summary>
public void DelCookeis()
{
foreach (string cookiename in Request.Cookies.AllKeys)
{
HttpCookie cookies = Request.Cookies[cookiename];
if (cookies != null)
{
cookies.Expires = DateTime.Today.AddDays(-1);
Response.Cookies.Add(cookies);
Request.Cookies.Remove(cookiename);
}
}
}
#endregion
测式:删除成功
自己理解:方法一只能删除提当前Response中的cookies,不对完成删除掉客端的cookies,用遍历cookies的方式可以
posted @ 2011-11-08 14:52 liufei 阅读(9) 评论(0)
编辑
VoucherDetailInfoPanel 是div 的ID
TextBox1 是临时存放值得控件
75 是指减去头标题高度
前台脚本如下:
function GetPostion(e)
{
var element = document.getElementById("<%=VoucherDetailInfoPanel.ClientID %>");
if( document.selection)
{
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText( element );
stored_range.setEndPoint( 'EndToEnd', range );
element.selectionStart = stored_range.text.length - range.text.length;
element.selectionEnd = element.selectionStart + range.text.length;
document.getElementById("<%=TextBox1.ClientID %>").value=element.selectionStart;
}
}
function GetScrollTop() {
//debugger;
var div = document.getElementById("<%=VoucherDetailInfoPanel.ClientID %>");
div.scrollTop =document.getElementById("<%=TextBox1.ClientID %>").value-75;
}
脚本或者这样也可以 Begin
function GetPostion()
{ //debugger;
var element = document.getElementById("<%=VoucherDetailInfoPanel.ClientID %>");
if( document.selection)
{
document.getElementById("<%=TextBox1.ClientID %>").value=element.scrollTop+75;
}
}
function GetScrollTop() {
//debugger;
var div = document.getElementById("<%=VoucherDetailInfoPanel.ClientID %>");
div.scrollTop =document.getElementById("<%=TextBox1.ClientID %>").value-75;
}
End
后台代码
VoucherDetailGrid 列表控件 是GridView控件
protected void VoucherDetailGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
if (e.NewEditIndex != VoucherDetailGrid.EditIndex)
{
int newEditRow = e.NewEditIndex;
EditRow(newEditRow);
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script language='javascript'>GetScrollTop();</script>", false);// 这是调用前台的脚本
}
}
protected void VoucherDetailGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
int finSetCode = 0;
int j = 0;
if (ViewState[VIEWSTATE_FINSETCODE] != null)
{
finSetCode = Int32.Parse(ViewState[VIEWSTATE_FINSETCODE].ToString());
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
VoucherDetailGrid.Attributes.Add("onclick", "GetPostion(event);"); // 这是调用前台的脚本
for (int i = 1; i < VoucherDetailGrid.Columns.Count; i++)
{
DataControlField dgc = VoucherDetailGrid.Columns[i];
if (dgc.HeaderText != String.Empty)
{
TCcVoucherSettingInfo tCcVoucherSettingInfo = BizVoucherSetting.GetVoucherItemByName(finSetCode, dgc.HeaderText);
if (tCcVoucherSettingInfo != null)
{
string voucherSettingId = tCcVoucherSettingInfo.VoucherSettingID;
string itemValue = String.Empty;
if (tCcVoucherSettingInfo.ItemType == (int)VoucherItemType.Dimension)
{
if (e.Row.FindControl(dgc.HeaderText + EDITTEXTBOX) != null)
{
bool isNo = BizFromAccount.IsFromAccountType(Convert.ToInt32(tCcVoucherSettingInfo.TypeValue),Convert.ToInt32(tCcVoucherSettingInfo.FinSetCode));
TextBox txb = (TextBox)e.Row.FindControl(dgc.HeaderText + EDITTEXTBOX);
string txbClient = txb.ClientID;
txb.Attributes.Add("onclick", "rowAccount(\'" + e.Row.RowIndex + "\',\'" + isNo + "\');__showDivContainer(\'" + txbClient + "\',\'" + tCcVoucherSettingInfo.FinSetCode + "\',\'" + tCcVoucherSettingInfo.TypeValue + "\');__DropDownClick(\'" + this.cc_MemberSelector.ClientID + "_divContainer\',\'150px\',\'" + txbClient + "\'); __setPosition(\'" + this.cc_MemberSelector.ClientID + "_divContainer\')");
txb.Attributes.Add("isAccount", "true");
txb.Attributes.Add("TypeValue", tCcVoucherSettingInfo.TypeValue);
}
}
}
}
}
}
}
posted @ 2011-11-08 11:54 liufei 阅读(15) 评论(0)
编辑
select cast(cast('1.526207675E7'as float)as numeric(20,2))
字符型先转float,再转numeric
posted @ 2011-11-07 15:36 liufei 阅读(9) 评论(0)
编辑
在事件里调用 this.Export("application/ms-excel", "凭证导出" + DateTime.Now.ToString("yyyyMMddhhmmss")); 即可
private void Export(string FileType, string FileName)
{
switch (FileType)
{
case "application/ms-excel":
ExportExcel(GetOutHtml(), FileName);
break;
default:
break;
}
}
private string GetOutHtml()
{
StringBuilder str = new StringBuilder();
this.ddlexportStarteHide.Value = this.ddlExportState.SelectedValue.ToString();
DataTable dt = this.GetGridViewDataSource();
if (dt != null && dt.Rows.Count > 0)
{
this.nodatainfo1.Visible = false;
}
else
{
this.nodatainfo1.Visible = true;
}
str.Append("<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"");
str.Append("<tr class=\"rbsListcss\" style=\"color:Black;background-color:#ABCBF5;font-weight:normal;height:24px;white-space:nowrap;\">");
string rowHeaderColumn = VoucherDetailGrid.RowHeaderColumn;
for (int ii = 1; ii < VoucherDetailGrid.Columns.Count; ii++)
{
str.Append("<th scope=\"col\">" + VoucherDetailGrid.HeaderRow.Cells[ii].Text + "</th>");
}
str.Append("</tr>");
if (dt != null && dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
str.Append("<tr class=\"rbsListRowcss\" align=\"left\" style=\"color:#333333;background-color:White;height:22px;\">");
for (int i = 2; i < dt.Columns.Count; i++)
{
str.Append("<td>");
str.Append(dt.Rows[j][i].ToString());
str.Append("</td>");
}
str.Append("</tr>");
}
}
str.Append("</table>");
return str.ToString();
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="outHtml"></param>
/// <param name="fileName"></param>
private void ExportExcel(string outHtml, string fileName)
{
StringBuilder sw = new StringBuilder();
sw.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
sw.Append("<head>");
sw.Append("<!--[if gte mso 9]>");
sw.Append("<xml>");
sw.Append(" <x:ExcelWorkbook>");
sw.Append(" <x:ExcelWorksheets>");
sw.Append(" <x:ExcelWorksheet>");
sw.Append(" <x:Name>" + "sheet1" + "</x:Name>");
sw.Append(" <x:WorksheetOptions>");
sw.Append(" <x:Print>");
sw.Append(" <x:ValidPrinterInfo />");
sw.Append(" </x:Print>");
sw.Append(" </x:WorksheetOptions>");
sw.Append(" </x:ExcelWorksheet>");
sw.Append(" </x:ExcelWorksheets>");
sw.Append("</x:ExcelWorkbook>");
sw.Append("</xml>");
sw.Append("<![endif]-->");
sw.Append("</head>");
sw.Append("<body>");
sw.Append(outHtml);
sw.Append("</body>");
sw.Append("</html>");
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
string s = HttpUtility.UrlEncode(System.Text.UTF8Encoding.UTF8.GetBytes(fileName));
Response.AppendHeader("Content-Disposition", "attachment; filename=" + s + ".xls");
Response.Write(sw.ToString());
}
posted @ 2011-09-27 21:45 liufei 阅读(26) 评论(0)
编辑
public void ListFiles(FileSystemInfo info)
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
//不是目录
if (dir == null) return;
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
//Console.WriteLine(file.FullName + "\t " + file.Length);
if (file.FullName.Substring(file.FullName.LastIndexOf(".")) == ".jpg")
//此处为显示JPG格式,不加IF可遍历所有格式的文件
{
this.list1.Items.Add(file);
//MessageBox.Show(file.FullName.Substring(file.FullName.LastIndexOf(".")));
}
}
//对于子目录,进行递归调用
else
{
ListFiles(files[i]);
}
}
}
调用:
string dir;
ListFiles(new DirectoryInfo(dir));
过滤项目中含有中文的地方 除注释 以外
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.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Data.SqlClient;
namespace SearchChina
{
public partial class SearchChinaStr : System.Web.UI.Page
{
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = "";
string dir;
ListFiles(new DirectoryInfo(TextBox1.Text.Trim()));
}
private int j = 0;
public void ListFiles(FileSystemInfo info)
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
//不是目录
if (dir == null) return;
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
bool aspxcs = file.Name.ToString().Contains(".aspx.cs");//要查找的文件类型
bool cs = file.Name.ToString().Contains(".cs");
bool ascxcs = file.Name.ToString().Contains(".ascx.cs");
bool designercs = file.Name.ToString().Contains(".designer.cs");
bool aspx = file.Name.ToString().Contains(".aspx");
bool ascx = file.Name.ToString().Contains(".ascx");
bool resx = file.Name.ToString().Contains(".resx");
if ((aspxcs || cs || ascxcs) && (!designercs))
{
string strLine = "";
try
{
StreamReader sr = new StreamReader(file.FullName, Encoding.GetEncoding("GB2312"));
strLine = sr.ReadLine();
string tempstr = "";
while (strLine != null)
{
if (ChZNfilter(strLine))
{
if (IsHasChZN(strLine))
{
j++;
TextBox2.Text += "第" + Convert.ToString(j) + "行 文件路径 " + file.FullName+ " " + Convert.ToString(i) + "行 " + "\r\n" + strLine + "\r\n\r\n";
// string SqlText = null;
// SqlText = @"Insert into SearchFileTable (lineNum,filePath,fileName,searchChinaRemark,state) VALUES
// ('" + "第" + Convert.ToString(i) + "行" + "','" + file.FullName + "','" + file.Name.ToString() + "','" + strLine + "','0')";
// if (PublicClass.ExecSQL(SqlText))
// {
// TextBox2.Text = "添加成功!";
// }
// else
// {
// TextBox2.Text = "添加失败!";
// }
}
}
strLine = sr.ReadLine();
}
sr.Dispose();
sr.Close();
}
catch
{
}
}
}
//对于子目录,进行递归调用
else
{
ListFiles(files[i]);
}
}
}
/// <summary>
/// 要过滤的 标识汉字
/// </summary>
/// <param name="strLine"></param>
/// <returns>true 不过滤,false 要过滤</returns>
private bool ChZNfilter(string strLine)
{
bool rvalue = true;
if (strLine.Contains("//"))
{
rvalue = false;
}
if (strLine.Contains("///"))
{
rvalue = false;
}
if (strLine.Contains("#region"))
{
rvalue = false;
}
if (strLine.Contains("#endregion"))
{
rvalue = false;
}
if (strLine.Contains("meta:resourcekey"))
{
rvalue = false;
}
if (strLine.Contains("<title>"))
{
rvalue = false;
}
if (strLine.Contains("BizProjectLog.InsertProjectLog"))
{
rvalue = false;
}
if (strLine.Contains("this.RecordLog"))
{
rvalue = false;
}
if (strLine.Contains(".WriteLine("))
{
rvalue = false;
}
if (strLine.Contains("Exception("))
{
rvalue = false;
}
if (strLine.Contains("/*"))
{
rvalue = false;
}
if (strLine.Contains("<%--"))
{
rvalue = false;
}
if (strLine.Contains("<!--"))
{
rvalue = false;
}
return rvalue;
}
public static bool IsHasChZN(string InputText)
{
return RegCHZN.IsMatch(InputText);
}
}
}
posted @ 2011-09-23 15:58 liufei 阅读(14) 评论(0)
编辑