ASP.NET(C#)
程序员文章站
2022-07-22 10:50:12
一个生成不重复随机数的方法 //生成不重复随机数算法 private int getrandomnum(int i,int&nbs...
一个生成不重复随机数的方法
//生成不重复随机数算法
private int getrandomnum(int i,int length,int up,int down)
{
int ifirst=0;
random ro=new random(i*length*unchecked((int)datetime.now.ticks));
ifirst=ro.next(up,down);
return ifirst;
}
发表于 @ 2005年12月30日 3:44 pm | 评论 (0)
asp.net多文件上传方法
前台代码
<script language="javascript">
function addfile()
{
var str = '<input type="file" size="30" name="file"><br>'
document.getelementbyid('myfile').insertadjacenthtml("beforeend",str)
}
</script>
<form id="form1" method="post" runat="server" enctype="multipart/form-data">
<div align="center">
<h3>多文件上传</h3>
<p id="myfile"><input type="file" size="30" name="file"><br></p>
<p>
<input type="button" value="增加(add)" onclick="addfile()"> <input onclick="this.form.reset()" type="button" value="重置(reset)">
<asp:button runat="server" text="开始上传" id="uploadbutton">
</asp:button>
</p>
<p>
<asp:label id="strstatus" runat="server" font-names="宋体" font-bold="true" font-size="9pt" width="500px"
borderstyle="none" bordercolor="white"></asp:label>
</p>
</div>
</form>
后台代码
protected system.web.ui.webcontrols.button uploadbutton;
protected system.web.ui.webcontrols.label strstatus;
private void page_load(object sender, system.eventargs e)
{
/// 在此处放置用户代码以初始化页面
if (this.ispostback) this.saveimages();
}
private boolean saveimages()
{
///'遍历file表单元素
httpfilecollection files = httpcontext.current.request.files;
/// '状态信息
system.text.stringbuilder strmsg = new system.text.stringbuilder();
strmsg.append("上传的文件分别是:<hr color=red>");
try
{
for(int ifile = 0; ifile < files.count; ifile++)
{
///'检查文件扩展名字
httppostedfile postedfile = files[ifile];
string filename,fileextension,file_id;
//取出精确到毫秒的时间做文件的名称
int year = system.datetime.now.year;
int month = system.datetime.now.month;
int day = system.datetime.now.day;
int hour = system.datetime.now.hour;
int minute = system.datetime.now.minute;
int second = system.datetime.now.second;
int millisecond = system.datetime.now.millisecond;
string my_file_id = year.tostring() + month.tostring() + day.tostring() + hour.tostring() + minute.tostring() + second.tostring() + millisecond.tostring()+ifile.tostring();
filename = system.io.path.getfilename(postedfile.filename);
fileextension = system.io.path.getextension(filename);
file_id = my_file_id+fileextension;
if (filename != "")
{
fileextension = system.io.path.getextension(filename);
strmsg.append("上传的文件类型:" + postedfile.contenttype.tostring() + "<br>");
strmsg.append("客户端文件地址:" + postedfile.filename + "<br>");
strmsg.append("上传文件的文件名:" + file_id + "<br>");
strmsg.append("上传文件的扩展名:" + fileextension + "<br><hr>");
postedfile.saveas(system.web.httpcontext.current.request.mappath("images/") + file_id);
}
}
strstatus.text = strmsg.tostring();
return true;
}
catch(system.exception ex)
{
strstatus.text = ex.message;
return false;
}
}
发表于 @ 2005年12月30日 3:37 pm | 评论 (0)
邮件系统使用的上传附件方法
前台html代码
<form id="mail" method="post" runat="server">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111"
width="39%" id="autonumber1" height="75">
<tr>
<td width="100%" height="37"><input id="myfile" style="width: 297px; height: 22px" type="file" size="30" name="myfile"
runat="server">
<asp:button id="upload" runat="server" text="上传附件"></asp:button></td>
</tr>
<tr>
<td width="100%" height="38">
共计
<asp:textbox id="p_size" runat="server" width="65px"></asp:textbox>kb
<asp:dropdownlist id="dlistbound" runat="server"></asp:dropdownlist>
<asp:button id="btndel" runat="server" text="删除附件"></asp:button></td>
</tr>
</table>
</form>
后台cs代码
public class upload_mail : system.web.ui.page
{
protected system.web.ui.webcontrols.button upload;
protected system.web.ui.webcontrols.dropdownlist dlistbound;
protected system.web.ui.webcontrols.textbox p_size;
protected system.web.ui.webcontrols.button btndel;
protected system.web.ui.htmlcontrols.htmlinputfile myfile;
private void page_load(object sender, system.eventargs e)
{
if (!ispostback)
{
//没有附件的状态
dlistbound.items.clear();
arraylist arr = new arraylist();
arr.add("--没有附件--");
dlistbound.datasource = arr ;
dlistbound.databind();
p_size.text = "0";
}
}
private void upload_click(object sender, system.eventargs e)
{
if(myfile.postedfile !=null)
{
httpfilecollection files = httpcontext.current.request.files;
httppostedfile postedfile = files[0];
string filename = system.io.path.getfilename(postedfile.filename);
string path = request.physicalapplicationpath+@"uploadmail\"+ filename;
postedfile.saveas(path);
//数组对上存附件进行实时绑定
if((string)session["udmail"]==null)
{
session["udmail"] = filename;
}
else
{
session["udmail"] = (string)session["udmail"]+"|"+filename;
}
string[] udmail = session["udmail"].tostring().split('|');
arraylist list = new arraylist(udmail);
list.reverse();
udmail=(string[])list.toarray(typeof(string));
dlistbound.items.clear();
long dirsize=0;
for(int i = 0;i<udmail.length;i++)
{
string indexitem = udmail[i];
string vauleitem = request.physicalapplicationpath+@"uploadmail\"+udmail[i];
dlistbound.items.add(new listitem(indexitem,vauleitem));
system.io.fileinfo mysize = new system.io.fileinfo(@vauleitem);
dirsize += system.convert.toint32(mysize.length/1024)+1;
}
p_size.text = dirsize.tostring();
}
}
private void btndel_click(object sender, system.eventargs e)
{
string truedelfile = dlistbound.selectedvalue.tostring();
string delfile = dlistbound.selecteditem.tostring();
usageio.deletepath(truedelfile);
if(session["udmail"] != null)
{
int index = session["udmail"].tostring().indexof("|");
if(index == -1)
{
session["udmail"] = null;
dlistbound.items.clear();
dlistbound.items.add("--没有附件--");
p_size.text = "0";
}
else
{
string[] udmail = session["udmail"].tostring().split('|');
arraylist values = new arraylist(udmail);
values.remove(delfile);
string s = null;
for(int i=0;i<values.count;i++)
{
if(values.count!=0)
{
s += values[i].tostring()+"|";
}
}
if(s!=""||s!=null)
{
s = s.trimend('|');
}
session["udmail"] = s;
string[] umail = session["udmail"].tostring().split('|');
arraylist list = new arraylist(umail);
list.reverse();
umail=(string[])list.toarray(typeof(string));
dlistbound.items.clear();
long dirsize=0;
for(int i = 0;i<umail.length;i++)
{
string indexitem = umail[i];
string vauleitem = request.physicalapplicationpath+@"uploadmail\"+umail[i];
dlistbound.items.add(new listitem(indexitem,vauleitem));
system.io.fileinfo mysize = new system.io.fileinfo(@vauleitem);
dirsize += system.convert.toint32(mysize.length/1024)+1;
}
p_size.text = dirsize.tostring();
}
}
}
web 窗体设计器生成的代码#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.upload.click += new system.eventhandler(this.upload_click);
this.btndel.click += new system.eventhandler(this.btndel_click);
this.load += new system.eventhandler(this.page_load);
}
#endregion
}
发表于 @ 2005年12月30日 3:29 pm | 评论 (0)
上传图片并且生成可以控制大小图片清晰度的方法
private void upload_click(object sender, system.eventargs e)
{
if(myfile.postedfile !=null)
{
// 检查文件扩展名字
httpfilecollection files = httpcontext.current.request.files;
httppostedfile postedfile = files[0];
string filename,fileextension,file_id,file_path;
//取出精确到毫秒的时间做文件的名称
int year = system.datetime.now.year;
int month = system.datetime.now.month;
int day = system.datetime.now.day;
int hour = system.datetime.now.hour;
int minute = system.datetime.now.minute;
int second = system.datetime.now.second;
int millisecond = system.datetime.now.millisecond;
string my_file_id = year.tostring() + month.tostring() + day.tostring() + hour.tostring() + minute.tostring() + second.tostring() + millisecond.tostring();
//获得文件类型
filename = system.io.path.getfilename(postedfile.filename);
fileextension = system.io.path.getextension(filename);
//重新命名文件,防止重复
file_id = "topnews_"+my_file_id+fileextension;
file_path = "images/article_images/"+file_id;
//文件上传到服务器的根目录
postedfile.saveas(request.physicalapplicationpath+@"images\article_images\"+ file_id);
//处理图片大小
int width,height,level;
width=120;
height=90;
level=100;//从1-100
getthumbnailimage(width,height,level,file_id);
}
}
//生成缩略图函数
public void getthumbnailimage(int width,int height,int level,string file_id)
{
string newfile= request.physicalapplicationpath+"images/article_images/"+"top_"+ file_id;
system.drawing.image oldimage = system.drawing.image.fromfile(request.physicalapplicationpath+"images/article_images/"+ file_id);
system.drawing.image thumbnailimage = oldimage.getthumbnailimage(width, height,new system.drawing.image.getthumbnailimageabort(thumbnailcallback), intptr.zero);
bitmap output=new bitmap(thumbnailimage);
//处理jpg质量的函数
imagecodecinfo[] codecs=imagecodecinfo.getimageencoders();
imagecodecinfo ici=null;
foreach(imagecodecinfo codec in codecs){if(codec.mimetype=="image/jpeg")ici=codec;}
encoderparameters ep=new encoderparameters();
ep.param[0]=new encoderparameter(encoder.quality,(long)level);
output.save(newfile,ici,ep);
//释放所有使用对象
ep.dispose();
output.dispose();
oldimage.dispose();
thumbnailimage.dispose();
//删除源图片
string file_path = "images/article_images/"+"top_"+file_id;
usageio.deletepath(request.physicalapplicationpath+"images/article_images/"+ file_id);
response.write("<script >parent.form1.a_simg.value ='"+file_path+"';location.replace('upload_img.aspx')</script>");
}
bool thumbnailcallback()
{
return false;
}
发表于 @ 2005年12月30日 3:25 pm | 评论 (0)
生成高清晰度的缩略图[方法1]
public void pic_zero(string sourcepath,string aimpath,int scale)
{
string originalfilename =sourcepath;
//生成的高质量图片名称
string strgoodfile =aimpath;
//从文件取得图片对象
system.drawing.image image = system.drawing.image.fromfile(originalfilename);
int iimgwidth = image.width;
int iimgheight = image.height;
int iscale = (iimgwidth / scale)>(iimgheight/scale) ? (iimgwidth / scale) : (iimgheight / scale);
//取得图片大小
system.drawing.size size = new size(image.width / iscale , image.height / iscale);
//新建一个bmp图片
system.drawing.image bitmap = new system.drawing.bitmap(size.width,size.height);
//新建一个画板
system.drawing.graphics g = system.drawing.graphics.fromimage(bitmap);
//设置高质量插值法
g.interpolationmode = system.drawing.drawing2d.interpolationmode.high;
//设置高质量,低速度呈现平滑程度
g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality;
//清空一下画布
g.clear(color.blue);
//在指定位置画图
g.drawimage(image, new system.drawing.rectangle(0, 0, bitmap.width, bitmap.height),
new system.drawing.rectangle(0, 0, image.width,image.height),
system.drawing.graphicsunit.pixel);
//保存高清晰度的缩略图
bitmap.save(strgoodfile, system.drawing.imaging.imageformat.jpeg);
g.dispose();
}
发表于 @ 2005年12月30日 3:23 pm | 评论 (0)
比较完美的图片验证码
需要引用的名字空间
using system.io;
using system.drawing.imaging;
using system.drawing.drawing2d;
public class validationcodeimg : system.web.ui.page
{
private void page_load(object sender, system.eventargs e)
{
this.createcheckcodeimage(generatecheckcode());
}
private string generatecheckcode()
{
int number;
char code;
string checkcode = string.empty;
system.random random = new random();
for(int i=0; i<5; i++)
{
number = random.next();
if(number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('0' + (char)(number % 10));
checkcode += code.tostring();
}
response.cookies.add(new httpcookie("checkcode", checkcode));
return checkcode;
}
private void createcheckcodeimage(string checkcode)
{
if(checkcode == null || checkcode.trim() == string.empty)
return;
system.drawing.bitmap image = new system.drawing.bitmap((int)math.ceiling((checkcode.length * 12.5)), 24);
graphics g = graphics.fromimage(image);
try
{
//生成随机生成器
random random = new random();
//清空图片背景色
g.clear(color.white);
//画图片的背景噪音线
for(int i=0; i<2; i++)
{
int x1 = random.next(image.width);
int x2 = random.next(image.width);
int y1 = random.next(image.height);
int y2 = random.next(image.height);
g.drawline(new pen(color.silver), x1, y1, x2, y2);
}
font font = new system.drawing.font("tahoma", 12, (system.drawing.fontstyle.bold | system.drawing.fontstyle.italic));
system.drawing.drawing2d.lineargradientbrush brush = new system.drawing.drawing2d.lineargradientbrush(new rectangle(0, 0, image.width, image.height), color.black, color.black, 1.2f, true);
g.drawstring(checkcode, font, brush, 2, 2);
//画图片的前景噪音点
for(int i=0; i<100; i++)
{
int x = random.next(image.width);
int y = random.next(image.height);
image.setpixel(x, y, color.fromargb(random.next()));
}
//画图片的边框线
g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);
system.io.memorystream ms = new system.io.memorystream();
image.save(ms, system.drawing.imaging.imageformat.gif);
response.clearcontent();
response.contenttype = "image/gif";
response.binarywrite(ms.toarray());
}
finally
{
g.dispose();
image.dispose();
}
}
发表于 @ 2005年12月30日 3:09 pm | 评论 (0)
ie订单的打印处理办法
在一个商城项目应用中我需要把客户在网上下的订单使用ie打印出来
首先必须控制订单不能出现ie的页眉页脚(需要使用scriptx)
<object id="factory" style="display: none" codebase="http://www.meadroid.com/scriptx/scriptx.cab#version=5,60,0,360"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814" viewastext>
</object>
<script defer>
function println() {
factory.printing.header = ""
factory.printing.footer = ""
factory.printing.print(true)
factory.printing.leftmargin = 0.2
factory.printing.topmargin = 0.5
factory.printing.rightmargin = 0.2
factory.printing.bottommargin = 1.5
window.print();
}
</script>
然后主要是控制订单数据输出用什么办法显示出来,为了灵活的控制输出效果,我这里使用的是循环读入数据(定购的商品)的办法(下面的代码是我使用的)
public string myorder(string b_no)
{
dodata.conn.open();
string strfirstmenu =null;
string strsql = "select items_type,items_name,items_unit,items_count,items_price from [orderitems] where order_no = '"+b_no+"' order by id desc";
sqldataadapter da = new sqldataadapter(strsql,dodata.conn);
dataset ds = new dataset();
da.fill(ds,"myorder");
int count = ds.tables[0].rows.count;
string items_type,items_name,items_price,items_count,items_unit,items_totalprice;
double items_alltotalprice = 0;
int items_totalcount = 0;
string begin = "<table id =\"inc\"style=\"border-collapse: collapse\" bordercolor=\"#111111\" height=\"35\" cellspacing=\"0\" cellpadding=\"0\" width=\"95%\" border=\"1\"><tr><td align=\"center\" width=\"14%\" height=\"35\">商品编号</td><td align=\"center\" width=\"25%\" height=\"35\">商品名称</td><td align=\"center\" width=\"10%\" height=\"35\">单位</td><td align=\"center\" width=\"10%\" height=\"35\">数量</td><td align=\"center\" width=\"20%\" height=\"35\">单价(元)</td><td align=\"center\" width=\"21%\" height=\"35\">金额(元)</td></tr>";
for(int rb = 0; rb < count;rb++)
{
items_type = ds.tables[0].rows[rb][0].tostring();
items_name = ds.tables[0].rows[rb][1].tostring();
items_unit = ds.tables[0].rows[rb][2].tostring();
items_count = ds.tables[0].rows[rb][3].tostring();
items_price = double.parse(ds.tables[0].rows[rb][4].tostring()).tostring("0.00");
items_totalprice = (double.parse(items_price)*double.parse(items_count)).tostring("0.00");
items_alltotalprice += double.parse(items_totalprice);
items_totalcount += int32.parse(items_count);
strfirstmenu += "<tr><td width=\"14%\" height=\"20\"> "+items_type+"</td><td width=\"25%\" height=\"20\">"+items_name+"</td><td width=\"10%\" height=\"20\">"+items_unit+"</td><td width=\"10%\" height=\"20\">"+items_count+"</td><td width=\"20%\" height=\"20\">"+items_price+"</td><td width=\"21%\" height=\"20\">"+items_totalprice+"</td></tr>";
}
string firstmenu = begin+strfirstmenu+"</table>";
dodata.conn.close();
return firstmenu;
}
发表于 @ 2005年12月30日 3:06 pm | 评论 (0)
url传输参数加密解密
最近做一个论坛入口时要实现帐号和密码不在ie地址栏出现而做的
index.aspx.cs (加密处理)
byte[] iv64={11, 22, 33, 44, 55, 66, 77, 85};
byte[] bykey64={10, 20, 30, 40, 50, 60, 70, 80};
public string encrypt(string strtext)
{
try
{
descryptoserviceprovider des = new descryptoserviceprovider();
byte[] inputbytearray = encoding.utf8.getbytes(strtext);
memorystream ms = new memorystream();
cryptostream cs = new cryptostream(ms, des.createencryptor(bykey64, iv64), cryptostreammode.write);
cs.write(inputbytearray, 0, inputbytearray.length);
cs.flushfinalblock();
return convert.tobase64string(ms.toarray());
}
catch(exception ex)
{
return ex.message;
}
}
private void btnlogin_click(object sender, system.web.ui.imageclickeventargs e)
{
datetime nowtime = datetime.now;
string postuser = txtuser.text.tostring();
string postpass = txtpassword.text.tostring();
response.redirect("login.aspx?clubid="+encrypt(postuser+","+postpass+","+nowtime.tostring()));
}
login.aspx.cs (解密处理)
//随机选8个字节既为密钥也为初始向量
byte[] bykey64={10, 20, 30, 40, 50, 60, 70, 80};
byte[] iv64={11, 22, 33, 44, 55, 66, 77, 85};
public string decrypt(string strtext)
{
byte[] inputbytearray = new byte[strtext.length];
try
{
descryptoserviceprovider des = new descryptoserviceprovider();
inputbytearray = convert.frombase64string(strtext);
memorystream ms = new memorystream();
cryptostream cs = new cryptostream(ms, des.createdecryptor(bykey64, iv64), cryptostreammode.write);
cs.write(inputbytearray, 0, inputbytearray.length);
cs.flushfinalblock();
system.text.encoding encoding = system.text.encoding.utf8;
return encoding.getstring(ms.toarray());
}
catch(exception ex)
{
return ex.message;
}
}
private void page_load(object sender, system.eventargs e)
{
if(request.params["clubid"]!=null)
{
string originalvalue = request.params["clubid"];
originalvalue = originalvalue.replace(" ","+");
//+号通过url传递变成了空格。
string decryptresult = decrypt(originalvalue);
//decryptstring(string)解密字符串
string delimstr = ",";
char[] delimiterarray = delimstr.tochararray();
string [] userinfoarray = null;
userinfoarray = decryptresult.split(delimiterarray);
string username = userinfoarray[0];
user usertologin = new user();
usertologin.username = userinfoarray[0];
usertologin.password = userinfoarray[1];
......
}
}
上一篇: 红薯和紫薯有什么区别