首页 > 开发 > 综合 > 正文

2004年最后一天的原创:C#通过HTTP操作数据的模块

2024-07-21 02:18:24
字体:
来源:转载
供稿:网友
// 本程序提供了一个通过http来操作数据库的类,这样少了本地安装乱七八糟的数据库驱动程序及复杂的设置,
// web 服务器可以是任意的类型的,可以为 asp , asp.net jsp 或其他,本模块提供了服务器的asp.net 的
// 例子
// 南京千里独行原创 请引用时勿删除本行 2004-12-31
using system;
using system.net ;
namespace myconnection
{
///
/// xmlhttp数据库连接操作事件处理委托
///
/// 数据库连接对象
/// 数据库命令对象
/// 总的数据字节数
/// 已完成的数据字节数
public delegate void xmlhttpdbexecutinghandler( xmlhttpconnection conn , xmlhttpcommand cmd , long contentlength , long contentcompleted );
///
/// xmlhttp类型的数据库数据读取对象
///
public class xmlhttpreader : system.data.idatareader
{
private string[] strhead = null;
private system.collections.arraylist myrows = new system.collections.arraylist();
private bool bolclosed = false;
private int introwindex = 0 ;
private const string c_nullflag = "[null]" ;

///
/// 根据字段名称获得字段序号,比较不区分大小写
///
/// 字段名称
/// 字段的从0开始的序号,若没找到则返回-1
public int getindexbyname( string strname )
{
if( strname == null ) return -1 ;
strname = strname.toupper().trim();
for( int icount = 0 ; icount < strhead.length ; icount ++ )
if( strname.equals( strhead[icount]))
return icount ;
return -1 ;
}

///
/// 从一个数据库读取对象加载对象数据
///
/// 数据库数据读取对象
/// 加载的记录的行数
public int fromreader(system.data.idatareader myreader)
{
if( myreader != null)
{
// 加载列头信息
strhead = new string[ myreader.fieldcount ];
for( int icount = 0 ; icount < myreader.fieldcount ; icount ++ )
strhead[icount] = myreader.getname(icount).tolower().trim();
// 加载数据
myrows.clear();
introwindex = -1 ;
while( myreader.read())
{
string[] strvalues = new string[ myreader.fieldcount];
myrows.add( strvalues );
for( int icount = 0 ; icount < myreader.fieldcount ;icount ++ )
{
if( myreader.isdbnull( icount ) == false)
{
if( myreader[icount] is byte[])
{
strvalues[icount] = convert.tobase64string( (byte[])myreader[icount]);
}
else
strvalues[icount] = myreader[icount].tostring();
}
}// for
}// while
return myrows.count ;
}// if
return -1;
}// fromreader
///
/// 保存对象数据到xml节点
///
/// 根xml节点
/// 保存的记录个数
public int toxml( system.xml.xmlelement rootelement )
{
system.xml.xmlelement rowelement = null;
system.xml.xmlelement fieldelement = null;
while( rootelement.firstchild != null)
rootelement.removechild( rootelement.firstchild);
// 保存列数据
if( strhead != null && strhead.length > 0 )
{
for( int icount = 0 ; icount < strhead.length ;icount ++ )
{
rootelement.setattribute("f" + icount.tostring() , strhead[icount]);
}
rootelement.setattribute("fieldcount" , strhead.length.tostring());
}
// 保存数据
if( myrows != null && myrows.count > 0 )
{
system.xml.xmldocument mydoc = rootelement.ownerdocument ;
for( int rowcount = 0 ; rowcount < myrows.count ; rowcount ++ )
{
string[] strvalue = ( string[] ) myrows[rowcount];
rowelement = mydoc.createelement("r");
rootelement.appendchild( rowelement );
for( int icount = 0 ; icount < strvalue.length ; icount ++ )
{
fieldelement = mydoc.createelement("f" + icount.tostring());
rowelement.appendchild( fieldelement );
if( strvalue[icount] == null )
fieldelement.innertext = c_nullflag ;
else
fieldelement.innertext = strvalue[icount];
}
}// for
return myrows.count ;
}
return -1 ;
}// toxml
///
/// 从xml元素加载对象数据
///
/// xml节点
/// 加载的数据的行数
public int fromxml( system.xml.xmlelement rootelement )
{
system.xml.xmlelement rowelement = null;
strhead = null;
myrows.clear();
introwindex = -1 ;
if( rootelement == null ) return -1 ;
// 获得列信息
system.collections.arraylist myheads = new system.collections.arraylist();
for( int icount = 0 ; icount < 255 ; icount ++ )
{
if( rootelement.hasattribute( "f" + icount.tostring()))
{
string strname = rootelement.getattribute("f" + icount.tostring());
myheads.add( strname.tolower().trim());
}
else
break;
}
//strhead = new string[ myheads.count ];
strhead = ( string[]) myheads.toarray( typeof(string));
// 获得数据
foreach( system.xml.xmlnode mynode in rootelement.childnodes )
{
if( mynode is system.xml.xmlelement )
{
rowelement = ( system.xml.xmlelement ) mynode ;
// 获得数据
string[] strvalues = new string[ strhead.length];
myrows.add( strvalues );
int ifieldcount = 0 ;
foreach(system.xml.xmlnode myfieldnode in rowelement.childnodes)
{
if( myfieldnode is system.xml.xmlelement )
{
strvalues[ifieldcount] = ( myfieldnode.innertext == c_nullflag ? null : myfieldnode.innertext ) ;
ifieldcount ++ ;
}
}// foreach
}// if
}// foreach
return myrows.count ;
}// fromxml
#region idatareader 成员
///
/// 未实现
///
public int recordsaffected
{
get {return 0; }
}
///
/// 已重载:关闭对象
///
public bool isclosed
{
get{ return bolclosed ; }
}
///
/// 未实现
///
///
public bool nextresult()
{
if( myrows == null || (introwindex+1) >= myrows.count )
return false;
else
return true;
}
///
/// 已重载:关闭对象
///
public void close()
{
bolclosed = true;
strhead = null;
myrows = null;
}
///
/// 移动当前记录到下一行
///
///
public bool read()
{
introwindex ++ ;
if( introwindex >= myrows.count )
return false;
else
return true;
}
///
/// 已重载:不支持
///
public int depth
{
get{ return 0; }
}
///
/// 已重载:不支持
///
///
public system.data.datatable getschematable()
{
// todo: 添加 xmlhttpreader.getschematable 实现
return null;
}
#endregion
#region idisposable 成员
public void dispose()
{
// todo: 添加 xmlhttpreader.dispose 实现
}
#endregion

#region idatarecord 成员
///
/// 已重载:获得指定列号的整数型数据
///
/// 从0开始的列号
/// 转换成功的整形数据
public int getint32(int i)
{
return convert.toint32( this.getstring(i));
}
///
/// 获得指定列名的数据
///
public object this[string name]
{
get
{
return this.getstring( this.getindexbyname( name));
}
}
///
/// 获得指定列号的数据
///
object system.data.idatarecord.this[int i]
{
get
{
return this.getstring(i);
}
}
///
/// 获得指定列号的数据
///
/// 从0开始的列号
/// 获得的数据
public object getvalue(int i)
{
return getstring(i);
}
///
/// 判断指定列号的数据是否为空
///
/// 从0开始的列号
/// 是否为空
public bool isdbnull(int i)
{
return getstring(i) == null;
}
public long getbytes(int i, long fieldoffset, byte[] buffer, int bufferoffset, int length)
{
byte[] bytdata = convert.frombase64string( getstring(i));
int icount = 0 ;
for( ; icount < length && ( icount + fieldoffset < bytdata.length ) ; icount ++ )
buffer[icount + bufferoffset ] = bytdata[ icount + fieldoffset];
return icount ;
}
///
/// 获得指定列的字节数据
///
///
///
public byte getbyte(int i)
{
return convert.tobyte( getstring(i));
}
///
/// 未实现
///
///
///
public type getfieldtype(int i)
{
return null;
}
///
/// 获得数值数据
///
///
///
public decimal getdecimal(int i)
{
return convert.todecimal( this.getstring( i));
}
///
/// 未实现
///
///
///
public int getvalues(object[] values)
{
// todo: 添加 xmlhttpreader.getvalues 实现
return 0;
}
///
/// 已重载:返回指定列的名称
///
///
///
public string getname(int i)
{
if( i >= 0 && i < strhead.length )
return strhead[i];
else
return null;
}
///
/// 已重载:返回列数
///
public int fieldcount
{
get
{
return strhead.length ;
}
}
///
/// 获得长整形数据
///
///
///
public long getint64(int i)
{
return convert.toint64( getstring(i));
}
///
/// 获得双精度浮点数
///
///
///
public double getdouble(int i)
{
return convert.todouble( getstring(i));
}
///
/// 获得布尔类型数据
///
///
///
public bool getboolean(int i)
{
return convert.toboolean( getstring(i));
}
///
/// 未实现
///
///
///
public guid getguid(int i)
{
// todo: 添加 xmlhttpreader.getguid 实现
return new guid ();
}
///
/// 获得时间类型数据
///
///
///
public datetime getdatetime(int i)
{
return convert.todatetime( getstring(i));
}
///
/// 未实现
///
///
///
public int getordinal(string name)
{
return 0;
}
///
/// 未实现
///
///
///
public string getdatatypename(int i)
{
return null;
}
///
/// 获得单精度浮点数
///
///
///
public float getfloat(int i)
{
return convert.tosingle( getstring(i));
}
///
/// 未实现
///
///
///
public system.data.idatareader getdata(int i)
{
return null;
}
///
/// 未实现
///
///
///
///
///
///
///
public long getchars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
return 0;
}
///
/// 获得字符串类型数据
///
///
///
public string getstring(int i)
{
if( introwindex >= 0 && introwindex < myrows.count && i >= 0 && i < strhead.length )
{
string[] strvalues = ( string[] ) myrows[introwindex];
return strvalues[i];
}
else
throw new system.indexoutofrangeexception("记录表错误:行数或列数越界,row:" + introwindex.tostring() + " col:" + i.tostring() );
}
///
/// 获得字符类型数据
///
///
///
public char getchar(int i)
{
return convert.tochar( getstring(i));
}
///
/// 获得短整型数据
///
///
///
public short getint16(int i)
{
return convert.toint16( getstring(i));
}
#endregion
}// class xmlhttpreader
//*******************************************************************************************
//*******************************************************************************************
///
/// xmlhttp数据库处理对象使用的参数集合
///
public class xmlhttpparametercollection : system.data.idataparametercollection
{
private system.collections.arraylist myparams = new system.collections.arraylist();
#region idataparametercollection 成员
///
/// 返回指定名称的参数对象
///
public object this[string parametername]
{
get
{
foreach( xmlhttpparameter myparam in myparams )
if( myparam.parametername == parametername )
return myparam ;
return null;
}
set
{
// todo: 添加 xmlhttpparametercollection.this setter 实现
}
}
public void removeat(string parametername)
{
object obj = this[parametername];
if( obj != null)
myparams.remove( obj );
}
public bool contains(string parametername)
{
return ( this[parametername] != null);
}
public int indexof(string parametername)
{
foreach( xmlhttpparameter myparam in myparams )
if( myparam.parametername == parametername )
return myparams.indexof( myparam ) ;
return -1 ;
}
#endregion
#region ilist 成员
public bool isreadonly
{
get
{
// todo: 添加 xmlhttpparametercollection.isreadonly getter 实现
return false;
}
}
object system.collections.ilist.this[int index]
{
get
{
return myparams[index];
}
set
{
myparams[index] = value;
}
}
void system.collections.ilist.removeat(int index)
{
myparams.removeat( index );
}
public void insert(int index, object obj)
{
myparams.insert( index , obj );
// todo: 添加 xmlhttpparametercollection.insert 实现
}
int system.collections.ilist.indexof( object obj)
{
return myparams.indexof( obj );
}
public void remove(object obj)
{
myparams.remove( obj );
}
bool system.collections.ilist.contains(object obj)
{
return myparams.contains( obj );
}
public void clear()
{
myparams.clear();
}

public int add(object obj)
{
myparams.add( obj );
return 0 ;
}
public bool isfixedsize
{
get
{
// todo: 添加 xmlhttpparametercollection.isfixedsize getter 实现
return false;
}
}
#endregion
#region icollection 成员
public bool issynchronized
{
get
{
// todo: 添加 xmlhttpparametercollection.issynchronized getter 实现
return false;
}
}
public int count
{
get
{
return myparams.count ;
}
}
public void copyto(array array, int index)
{
// todo: 添加 xmlhttpparametercollection.copyto 实现
}
public object syncroot
{
get
{
// todo: 添加 xmlhttpparametercollection.syncroot getter 实现
return null;
}
}
#endregion
#region ienumerable 成员
public system.collections.ienumerator getenumerator()
{
return myparams.getenumerator();
}
#endregion
}
//********************************************************************************
//********************************************************************************
///
/// xmlhttp数据库连接对象使用的参数类型
///
public class xmlhttpparameter : system.data.idataparameter
{
private system.data.parameterdirection intdirection = system.data.parameterdirection.input ;
private system.data.datarowversion intsourceversion = system.data.datarowversion.default ;
private system.data.dbtype intdbtype = system.data.dbtype.string ;

private object objvalue = null;
private string strparametername = null;
private string strsourcecolumn = null;

///
/// 用指定字符串数据初始化对象
///
///
public xmlhttpparameter( string strvalue)
{
objvalue = strvalue ;
}
///
/// 无参数的初始化对象
///
public xmlhttpparameter()
{}
#region idataparameter 成员
///
/// 获取或设置一个值,该值指示参数是只可输入、只可输出、双向还是存储过程返回值参数。
///
public system.data.parameterdirection direction
{
get{ return intdirection ;}
set{ intdirection = value;}
}
///
/// 获取或设置参数的 system.data.dbtype
///
public system.data.dbtype dbtype
{
get{ return intdbtype ;}
set{ intdbtype = value ;}
}
///
/// 获取或设置该参数的值
///
public object value
{
get{ return objvalue ;}
set{ objvalue = value;}
}
public bool isnullable
{
get
{
return false;
}
}
public system.data.datarowversion sourceversion
{
get{ return intsourceversion ;}
set{ intsourceversion = value;}
}
///
/// 参数名称
///
public string parametername
{
get{ return strparametername ;}
set{ strparametername = value;}
}
///
/// 参数栏目名称
///
public string sourcecolumn
{
get{ return strsourcecolumn ;}
set{ strsourcecolumn = value;}
}
#endregion
}
//*************************************************************************************
//*************************************************************************************
///
/// 使用xmlhttp进行数据库访问的命令对象
///
public class xmlhttpcommand : system.data.idbcommand
{
private system.data.commandtype intcommandtype = system.data.commandtype.text ;
private system.data.commandbehavior intcmdbehavior = system.data.commandbehavior.default ;
private system.data.updaterowsource intupdatedrowsource = system.data.updaterowsource.both ;
private int intcommandtimeout = 0 ;
private bool bolcancel = false;
private string strcommandtext = null;
///
/// 对象执行类型 0:查询数据库 1:更新数据库
///
private int intexecutetype = 0 ;
private xmlhttpconnection myconnection = null;
private xmlhttpparametercollection myparameters = new xmlhttpparametercollection();
private int intexecutestate = 0 ;
private system.xml.xmldocument myxmldoc = new system.xml.xmldocument();
private const string c_nullflag = "[null]" ;


///
/// 正在执行命令事件处理
///
public xmlhttpdbexecutinghandler executeevent = null;
private string strhttpmethod = "post";
///
/// 正在执行的状态 0:没有执行 1:正在发送数据 2:正在接受数据 3:正在解析数据
///
public int executestate
{
get{ return intexecutestate ;}
}
///
/// 向http服务器提交数据的方法
///
public string httpmethod
{
get{ return strhttpmethod ;}
set{ strhttpmethod = value;}
}
///
/// 保存对象数据到一个xml节点中
///
///
///
public bool fromxml(system.xml.xmlelement myelement )
{
if( myelement != null)
{
intexecutetype = stringcommon.toint32value( myelement.getattribute("type"),0);
strcommandtext = myelement.getattribute("text");
myparameters.clear();
foreach( system.xml.xmlnode mynode in myelement.childnodes)
{
if( mynode.name == "param" )
{
system.xml.xmlelement mypelement = mynode as system.xml.xmlelement ;
xmlhttpparameter myparam = new xmlhttpparameter();
myparam.parametername = mypelement.getattribute("name");
myparam.value = mypelement.innertext ;
myparameters.add( myparam );
}
}
}
return true;
}
///
/// 从一个xml节点加载对象数据
///
///
///
public bool toxml( system.xml.xmlelement myelement )
{
if( myelement != null)
{
myelement.setattribute("text", strcommandtext);
myelement.setattribute("type", intexecutetype.tostring());
foreach( xmlhttpparameter myparam in myparameters )
{
system.xml.xmlelement mypelement = myelement.ownerdocument.createelement("param");
myelement.appendchild( mypelement );
mypelement.setattribute("name" , myparam.parametername );
mypelement.innertext =( myparam.value == null ? c_nullflag : myparam.value.tostring());
}
}
return true;
}

///
/// 发送并接受二进制数据
///
///
///
internal byte[] sendbytedata( byte[] bytsend)
{
// 发送数据
system.net.httpwebrequest myreq = myconnection.createhttprequest();
system.io.stream mystream = myreq.getrequeststream();
int icount = 0 ;
bolcancel = false;
intexecutestate = 1 ;
while( icount < bytsend.length )
{
if( icount + 1024 > bytsend.length)
{
mystream.write(bytsend, icount , bytsend.length - icount );
icount = bytsend.length ;
}
else
{
mystream.write(bytsend , icount , 1024);
icount += 1024;
}
if( executeevent != null)
{
executeevent( myconnection , this , bytsend.length , icount );
}
if( bolcancel )
{
mystream.close();
myreq.abort();
return null;
}
}
mystream.close();
// 接受数据
intexecutestate = 2 ;
system.net.httpwebresponse myres = null;
myres = (system.net.httpwebresponse) myreq.getresponse();
mystream = myres.getresponsestream();
system.io.memorystream mybuf = new system.io.memorystream(1024);
byte[] bytbuf = new byte[1024];
while(true)
{
int ilen = mystream.read(bytbuf,0,1024);
if(ilen ==0)
break;
mybuf.write(bytbuf,0,ilen);
if( executeevent != null)
{
executeevent( myconnection , this , myres.contentlength , mybuf.length );
}
if( bolcancel )
{
mystream.close();
myres.close();
myreq.abort();
return null ;
}
}
mystream.close();
myres.close();
myreq.abort();
byte[] bytreturn = mybuf.toarray();
mybuf.close();
return bytreturn ;
}

///
/// 执行命令
///
///
private bool executecommand()
{
myxmldoc.loadxml("");
this.toxml( myxmldoc.documentelement);
string strsend = myxmldoc.documentelement.outerxml ;
byte[] bytsend = myconnection.sendencod.getbytes( strsend );
byte[] bytreturn = sendbytedata(bytsend);
if( bytreturn == null)
return false;
// 解析数据
intexecutestate = 3 ;
char[] chrreturn = myconnection.reserveencod.getchars(bytreturn);
string strreserve =new string(chrreturn);
strreserve = strreserve.trim();
myxmldoc.preservewhitespace = true;
//try {
myxmldoc.loadxml( strreserve );
//}catch( exception ext){system.console.writeline( ext.tostring());}
intexecutestate = 0 ;
if( myxmldoc.documentelement.getattribute("error")=="1")
{
throw new system.exception("远程web数据库操作错误/n" + myxmldoc.documentelement.innertext );
}
return true;
}// executecommand

public string executestring()
{
if( this.executecommand())
return myxmldoc.documentelement.innertext ;
else
return null;
}
#region idbcommand 成员
public void cancel()
{
bolcancel = true;
}
public void prepare()
{
// todo: 添加 xmlhttpcommand.prepare 实现
}
///
/// 指示或指定如何解释 system.data.idbcommand.commandtext 属性。
///
public system.data.commandtype commandtype
{
get{ return intcommandtype ;}
set{ intcommandtype = value;}
}
public system.data.idatareader executereader(system.data.commandbehavior behavior)
{
intcmdbehavior = behavior ;
intexecutetype = 0 ;
if( this.executecommand())
{
xmlhttpreader myreader = new xmlhttpreader();
myreader.fromxml( myxmldoc.documentelement );
return myreader;
}
return null;
}
system.data.idatareader system.data.idbcommand.executereader()
{
intexecutetype = 0 ;
if( this.executecommand())
{
xmlhttpreader myreader = new xmlhttpreader();
myreader.fromxml( myxmldoc.documentelement );
return myreader;
}
return null;
}
public object executescalar()
{
// todo: 添加 xmlhttpcommand.executescalar 实现
return null;
}
public int executenonquery()
{
intexecutetype = 1 ;
if( this.executecommand())
return convert.toint32( myxmldoc.documentelement.innertext );
return -1;
}
///
/// 执行命令的超时时间
///
public int commandtimeout
{
get{ return intcommandtimeout ;}
set{ intcommandtimeout = value;}
}
public system.data.idbdataparameter createparameter()
{
return (system.data.idbdataparameter) ( new xmlhttpparameter());
}
///
/// 数据库连接对象
///
public system.data.idbconnection connection
{
get{ return myconnection ;}
set{ myconnection = (xmlhttpconnection)value;}
}
public system.data.updaterowsource updatedrowsource
{
get{ return intupdatedrowsource ;}
set{ intupdatedrowsource = value;}
}
public string commandtext
{
get{ return strcommandtext ;}
set{ strcommandtext = value;}
}
public system.data.idataparametercollection parameters
{
get{ return myparameters ; }
}
///
/// 未支持
///
public system.data.idbtransaction transaction
{
get
{
// todo: 添加 xmlhttpcommand.transaction getter 实现
return null;
}
set
{
// todo: 添加 xmlhttpcommand.transaction setter 实现
}
}
#endregion
#region idisposable 成员
public void dispose()
{
// todo: 添加 xmlhttpcommand.dispose 实现
}
#endregion
}
///
/// 通过http使用xml来操作数据的数据库连接对象
///
public class xmlhttpconnection : system.data.idbconnection
{

private string strconnectionstring = null;
private system.data.connectionstate intstate = system.data.connectionstate.closed ;
private string strdatabase = null;
private int intconnectiontimeout = 0 ;
private string striecookies = null;

///
/// 初始化对象
///
public xmlhttpconnection( )
{
}
///
/// 初始化对象
///
///
public xmlhttpconnection( string strconn )
{
strconnectionstring = strconn ;
}
///
/// 发送数据使用的编码
///
public system.text.encoding sendencod = system.text.encoding.utf8 ;
///
/// 接受数据使用的编码
///
public system.text.encoding reserveencod = system.text.encoding.getencoding(936);
private system.net.cookie mysessioncookie = null;

///
/// 正在执行命令事件处理
///
public xmlhttpdbexecutinghandler executeevent = null;
private string strhttpmethod = "post";
///
/// 设置,返回ie浏览器使用的cookie字符串
///
public string iecookies
{
get{ return striecookies ;}
set{ striecookies = value;}
}

///
/// 向http服务器提交数据的方法
///
public string httpmethod
{
get{ return strhttpmethod ;}
set{ strhttpmethod = value;}
}
///
/// 创建一个http服务器连接对象
///
///
internal system.net.httpwebrequest createhttprequest()
{
system.net.httpwebrequest myreq =(system.net.httpwebrequest) system.net.webrequest.create(strconnectionstring);
// 添加用于标示用户的cookie对象
if( mysessioncookie != null)
{
myreq.cookiecontainer = new system.net.cookiecontainer();
myreq.cookiecontainer.add( mysessioncookie );
}
myreq.contenttype = "application/x-www-form-urlencoded";
myreq.method = strhttpmethod ;
return myreq ;
}
#region idbconnection 成员
///
/// 更换数据库
///
///
public void changedatabase(string databasename)
{
strdatabase = databasename ;
}
///
/// 未支持
///
///
///
public system.data.idbtransaction begintransaction(system.data.isolationlevel il)
{
return null;
}
///
/// 未支持
///
///
system.data.idbtransaction system.data.idbconnection.begintransaction()
{
return null;
}
///
/// 返回数据库连接状态
///
public system.data.connectionstate state
{
get{return intstate ;}
}
///
/// 数据库连接字符串
///
public string connectionstring
{
get{ return strconnectionstring ; }
set{ strconnectionstring = value ; intstate = system.data.connectionstate.closed ;}
}
///
/// 创建一个数据库命令对象
///
///
public system.data.idbcommand createcommand()
{
xmlhttpcommand newcmd = new xmlhttpcommand();
newcmd.connection = this ;
newcmd.executeevent = this.executeevent ;
newcmd.httpmethod = this.httpmethod ;
return newcmd ;
}

///
/// 打开数据库连接,本函数用于测试服务器是否可用,并设置正确的输入输出编码格式
///
public void open()
{
intstate = system.data.connectionstate.connecting ;
//custombasic custombasicmodule = new custombasic();

// unregister the standard basic authentication module.
authenticationmanager.unregister("basic");
// register the custom basic authentication module.
//authenticationmanager.register(custombasicmodule);

// 试图获得服务的标志用户身份的cookie对象
mysessioncookie = null;
if( striecookies != null && striecookies.length > 0 )
{
string[] stritems = stringcommon.analysestringlist( striecookies , ';' , '=' , false);
if( stritems != null)
{
string strname = null;
string strvalue = null;
// 根据传入的ie的cookie值来判断用于标志用户的cookie值
// 此处认为标志用户的cookie的名称中含有 session
for(int icount = 0 ; icount < stritems.length ; icount +=2)
{
string stritemname = stritems[icount].toupper();
if( stritemname.indexof("session") >= 0 )
{
strname = stritems[icount].trim();
strvalue = stritems[icount+1] ;
break;
}
}
if( strname != null)
{
// 向服务器发送请求,获得标示用户的cookie对象
system.net.httpwebrequest myreq = this.createhttprequest();
myreq.cookiecontainer = new system.net.cookiecontainer();
system.io.stream mystream = myreq.getrequeststream();
byte[] bytsend = system.text.encoding.ascii.getbytes("");
mystream.write( bytsend,0 , bytsend.length );
mystream.close();
system.net.httpwebresponse myres = myreq.getresponse() as system.net.httpwebresponse ;
for(int icount = 0 ;icount < myres.cookies.count ;icount ++ )
{
if( myres.cookies[icount].name == strname )
{
mysessioncookie = myres.cookies[0];
mysessioncookie.value = strvalue ;
break;
}
}// for
}// if
}
}
// 测试数据库连接,自动判断数据的输入和输出编码格式
system.collections.arraylist myencods = new system.collections.arraylist();
myencods.add( system.text.encoding.getencoding(936));
myencods.add( system.text.encoding.utf8 );
myencods.add( system.text.encoding.unicode );
myencods.add( system.text.encoding.utf7 );
myencods.add( system.text.encoding.ascii );
const string c_testcommand = "[testconnection]";
const string c_testokflag = "test_ok_中文测试";
system.xml.xmldocument myxmldoc = new system.xml.xmldocument();
myxmldoc.loadxml("");
myxmldoc.documentelement.setattribute("text", c_testcommand );
myxmldoc.documentelement.setattribute("data", c_testokflag );
string strsend = myxmldoc.documentelement.outerxml ;
using(xmlhttpcommand mycmd = (xmlhttpcommand) this.createcommand())
{
for(int icount1 = 0 ; icount1 < myencods.count ; icount1 ++ )
{
byte[] bytsend = ( myencods[icount1] as system.text.encoding ).getbytes( strsend );
byte[] bytreturn = mycmd.sendbytedata( bytsend );
for( int icount2 = 0 ; icount2 < myencods.count ; icount2 ++ )
{
system.text.encoding myencode = (system.text.encoding ) myencods[icount2];
char[] chrreturn = myencode.getchars(bytreturn);
string strreturn = new string( chrreturn );
if( strreturn.indexof(c_testokflag) >= 0 )
{
this.sendencod = (system.text.encoding) myencods[icount1];
this.reserveencod = ( system.text.encoding ) myencods[icount2];
intstate = system.data.connectionstate.open ;
return ;
}
}
}
}
intstate = system.data.connectionstate.closed ;
}// void open()

public void close()
{
// todo: 添加 xmlhttpconnection.close 实现
}
public string database
{
get
{
return strdatabase;
}
}
public int connectiontimeout
{
get
{
return intconnectiontimeout ;
}
}
#endregion
#region idisposable 成员
public void dispose()
{
// todo: 添加 xmlhttpconnection.dispose 实现
authenticationmanager.unregister("basic");
}
#endregion
}
//
//
// // the custombasic class creates a custom basic authentication by implementing the
// // iauthenticationmodule interface. it performs the following
// // tasks:
// // 1) defines and initializes the required properties.
// // 2) implements the authenticate method.
//
// internal class custombasic : iauthenticationmodule
// {
//
// private string m_authenticationtype ;
// private bool m_canpreauthenticate ;
//
// // the custombasic constructor initializes the properties of the customized
// // authentication.
// public custombasic()
// {
// m_authenticationtype = "basic";
// m_canpreauthenticate = false;
// }
//
// // define the authentication type. this type is then used to identify this
// // custom authentication module. the default is set to basic.
// public string authenticationtype
// {
// get
// {
// return m_authenticationtype;
// }
// }
//
// // define the pre-authentication capabilities for the module. the default is set
// // to false.
// public bool canpreauthenticate
// {
// get
// {
// return m_canpreauthenticate;
// }
// }
//
// // the checkchallenge method checks whether the challenge sent by the httpwebrequest
// // contains the correct type (basic) and the correct domain name.
// // note: the challenge is in the form basic realm="domainname";
// // the internet web site must reside on a server whose
// // domain name is equal to domainname.
// public bool checkchallenge(string challenge, string domain)
// {
// bool challengepasses = false;
//
// string tempchallenge = challenge.toupper();
//
// // verify that this is a basic authorization request and that the requested domain
// // is correct.
// // note: when the domain is an empty string, the following code only checks
// // whether the authorization type is basic.
//
// if (tempchallenge.indexof("basic") != -1)
// if (domain != string.empty)
// if (tempchallenge.indexof(domain.toupper()) != -1)
// challengepasses = true;
// else
// // the domain is not allowed and the authorization type is basic.
// challengepasses = false;
// else
// // the domain is a blank string and the authorization type is basic.
// challengepasses = true;
//
// return challengepasses;
// }
//
// // the preauthenticate method specifies whether the authentication implemented
// // by this class allows pre-authentication.
// // even if you do not use it, this method must be implemented to obey to the rules
// // of interface implementation.
// // in this case it always returns false.
// public authorization preauthenticate(webrequest request, icredentials credentials)
// {
// return null;
// }
//
// // authenticate is the core method for this custom authentication.
// // when an internet resource requests authentication, the webrequest.getresponse
// // method calls the authenticationmanager.authenticate method. this method, in
// // turn, calls the authenticate method on each of the registered authentication
// // modules, in the order in which they were registered. when the authentication is
// // complete an authorization object is returned to the webrequest.
// public authorization authenticate(string challenge, webrequest request, icredentials credentials)
// {
// system.text.encoding ascii = system.text.encoding.ascii ;
//
// // get the username and password from the credentials
// networkcredential mycreds = credentials.getcredential(request.requesturi, "basic");
//
// if (preauthenticate(request, credentials) == null)
// console.writeline("/n pre-authentication is not allowed.");
// else
// console.writeline("/n pre-authentication is allowed.");
//
// // verify that the challenge satisfies the authorization requirements.
// bool challengeok = checkchallenge(challenge, mycreds.domain);
//
// if (!challengeok)
// return null;
//
// // create the encrypted string according to the basic authentication format as
// // follows:
// // a)concatenate the username and password separated by colon;
// // b)apply ascii encoding to obtain a stream of bytes;
// // c)apply base64 encoding to this array of bytes to obtain the encoded
// // authorization.
// string basicencrypt = mycreds.username + ":" + mycreds.password;
//
// string basictoken = "basic " + convert.tobase64string(ascii.getbytes(basicencrypt));
//
// // create an authorization object using the encoded authorization above.
// authorization resourceauthorization = new authorization(basictoken);
//
// // get the message property, which contains the authorization string that the
// // client returns to the server when accessing protected resources.
// console.writeline("/n authorization message:{0}",resourceauthorization.message);
//
// // get the complete property, which is set to true when the authentication process
// // between the client and the server is finished.
// console.writeline("/n authorization complete:{0}",resourceauthorization.complete);
//
// console.writeline("/n authorization connectiongroupid:{0}",resourceauthorization.connectiongroupid);
//
//
// return resourceauthorization;
// }
// }
///
/// xmlhttp数据库连接服务器端模块,在某个asp.net页面中使用该模块就可以向 xmlhttpconnection 提供数据了
///
public class xmlhttpserver
{
private system.data.idbconnection myconnection ;
///
/// 数据库连接对象
///
public system.data.idbconnection connection
{
get{ return myconnection ;}
set{ myconnection = value;}
}
///
/// 执行操作
///
///
///
public string execute(system.xml.xmldocument inputxmldoc )
{
const string c_testcommand = "[testconnection]";
const string c_testokflag = "test_ok_中文测试";
const string c_nullflag = "[null]";
if( inputxmldoc.documentelement.name == "null")
return "";
system.xml.xmldocument myoutxml = new system.xml.xmldocument();
myoutxml.preservewhitespace = true;
myoutxml.loadxml("");
myoutxml.documentelement.setattribute("version","1.0");
try
{
string strtext = inputxmldoc.documentelement.getattribute("text");
string strtype = inputxmldoc.documentelement.getattribute("type");
system.console.writeline("收到命令" + inputxmldoc.documentelement.outerxml );
if( strtext == c_testcommand )
{
if( inputxmldoc.documentelement.getattribute("data") == c_testokflag )
return c_testokflag ;
else
return "错误的输入编码";
}
else
{
if( myconnection != null && myconnection.state == system.data.connectionstate.open )
{
using(system.data.idbcommand mycmd = myconnection.createcommand())
{
// 设置查询命令对象
mycmd.commandtext = strtext ;
foreach( system.xml.xmlnode mynode in inputxmldoc.documentelement.childnodes )
{
if( mynode.name == "param" && mynode is system.xml.xmlelement )
{
system.data.idbdataparameter newparam = mycmd.createparameter();
string strvalue = mynode.innertext ;
if( strvalue == c_nullflag )
newparam.value = "";
else
newparam.value = strvalue;
mycmd.parameters.add( newparam );
}
}
if( strtype == "0")
{
// 查询数据库
system.data.idatareader myreader = mycmd.executereader();
system.xml.xmlelement recordelement = null;
system.xml.xmlelement fieldelement = null;
// 添加字段信息
for( int icount = 0 ; icount < myreader.fieldcount ; icount ++ )
{
myoutxml.documentelement.setattribute("f" + icount.tostring(), myreader.getname(icount).tolower());
}
// 添加查询所得数据
while( myreader.read())
{
recordelement = myoutxml.createelement("r");
myoutxml.documentelement.appendchild( recordelement );
for(int icount = 0 ; icount < myreader.fieldcount ; icount ++ )
{
fieldelement = myoutxml.createelement("f" + icount.tostring());
recordelement.appendchild( fieldelement );
fieldelement.innertext = ( myreader.isdbnull( icount ) ? c_nullflag : myreader[icount].tostring());
}
}
myreader.close();
}
if( strtype == "1")
{
// 更新数据库
int introwcount = mycmd.executenonquery();
myoutxml.documentelement.innertext = introwcount.tostring();
}
}// using
}
}
return myoutxml.documentelement.outerxml ;
}// try
catch( exception ext)
{
return xmlhttpserver.createerrormessage(ext);
}
}// execute
///
/// 生成用于保存错误的字符串
///
///
///
public static string createerrormessage(exception ext)
{
system.xml.xmldocument myxmldoc = new system.xml.xmldocument();
myxmldoc.loadxml("");
myxmldoc.documentelement.setattribute("error","1");
myxmldoc.documentelement.innertext = ext.tostring();
return myxmldoc.documentelement.outerxml ;
}// createerrormessage
}// class xmlhttpserver
public class stringcommon
{
///
/// 分析一个保存列表数据的字符串并将分析结果保存在一个字符串数组中
/// 该字符串格式为 项目名 值分隔字符 项目值 项目分隔字符 项目名 值分隔字符 项目值 ...
/// 例如 若值分隔字符为 ; 项目分隔字符为 = 则该输入字符串格式为 a=1;b=2;c=33
/// 则本函数将生成一个字符串数组 {a,1,b,2,c,33},数组元素为偶数个
///
/// 保存列表数据的字符串
/// 项目分隔字符串
/// 值分隔字符串
/// 分析的项目是否允许重名
/// 返回的依次保存项目名称和项目值的字符串,元素个数必为偶数个,参数不正确则返回空引用
public static string[] analysestringlist( string strlist ,char itemsplit ,char valuesplit ,bool allowsamename)
{
// 判断参数的正确性
if( strlist == null || strlist.length == 0 )
return null;
system.collections.arraylist mylist = new system.collections.arraylist();
string stritem = null;
string strname = null;
string strvalue = null;
int index1 = 0 ;
while( index1 < strlist.length )
{
int index2 = strlist.indexof( itemsplit , index1 );
if( index2 < 0 )
index2 = strlist.length ;
if( index2 > index1 + 1 )
{
// 获得单个项目
stritem = strlist.substring( index1 , index2 - index1 );
// 获得西项目名和项目值
int index3 = stritem.indexof( valuesplit );
if( index3 > 0 )
{
strname = stritem.substring(0 , index3 );
strvalue = stritem.substring(index3 + 1 );
}
else
{
strname = stritem ;
strvalue = "";
}
// 注册新的项目
bool boladd = true;
if( allowsamename == false)
{
foreach( namevalueitem myitem in mylist)
{
if( myitem.name == strname )
{
boladd = false;
break;
}
}
}
if( boladd)
{
namevalueitem newitem = new namevalueitem();
newitem.name = strname ;
newitem.value = strvalue ;
mylist.add( newitem );
}
}
index1 = index2 + 1 ;
}
// 输出结果
string[] strreturn = new string[ mylist.count * 2] ;
int icount = 0 ;
foreach(namevalueitem myitem in mylist)
{
strreturn[icount ] = myitem.name ;
strreturn[icount+1] = myitem.value ;
icount += 2 ;
}
return strreturn ;
}// string[] analysestringlist
///
/// 内部使用的名称和值的项目对
///
private class namevalueitem
{
public string name ;
public string value ;
}
///
/// 将一个字符串转换为整数
///
/// 字符串
/// 默认值
/// 转换结果
public static int toint32value(string strdata , int defaultvalue)
{
try
{
if(strdata == null || strdata.length == 0)
return defaultvalue;
return convert.toint32( strdata);
// char[] mychars = strdata.tochararray();
// int ivalue = 0 ;
// int icount = 0 ;
// bool bolnegative = false ;
// foreach( char mychar in mychars)
// {
// ivalue = (int)mychar ;
// if( ivalue >= 48 && ivalue <= 57)
// icount = icount * 10 + ivalue - 48 ;
// else
// break;
// }
// return icount ;
}
catch
{
return defaultvalue;
}
}
}
}


,欢迎访问网页设计爱好者web开发。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表