ASP.NET(C#)_asp.net教程-查字典教程网
ASP.NET(C#)
ASP.NET(C#)
发布时间:2016-12-29 来源:查字典编辑
摘要:一个生成不重复随机数的方法//生成不重复随机数算法privateintGetRandomNum(inti,intlength,intup,i...

一个生成不重复随机数的方法

//生成不重复随机数算法

privateintGetRandomNum(inti,intlength,intup,intdown)

{

intiFirst=0;

Randomro=newRandom(i*length*unchecked((int)DateTime.Now.Ticks));

iFirst=ro.Next(up,down);

returniFirst;

}

发表于@2005年12月30日3:44PM|评论(0)

ASP.NET多文件上传方法

前台代码

<scriptlanguage="Javascript">

functionaddFile()

{

varstr='<INPUTtype="file"size="30"NAME="File"><br>'

document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)

}

</script>

<formid="form1"method="post"runat="server"enctype="multipart/form-data">

<divalign="center">

<h3>多文件上传</h3>

<Pid="MyFile"><INPUTtype="file"size="30"NAME="File"><br></P>

<P>

<inputtype="button"value="增加(Add)"onclick="addFile()"><inputonclick="this.form.reset()"type="button"value="重置(ReSet)">

<asp:ButtonRunat="server"Text="开始上传"ID="UploadButton">

</asp:Button>

</P>

<P>

<asp:Labelid="strStatus"runat="server"Font-Names="宋体"Font-Bold="True"Font-Size="9pt"Width="500px"

BorderBorderColor="White"></asp:Label>

</P>

</div>

</form>

后台代码

protectedSystem.Web.UI.WebControls.ButtonUploadButton;

protectedSystem.Web.UI.WebControls.LabelstrStatus;

privatevoidPage_Load(objectsender,System.EventArgse)

{

///在此处放置用户代码以初始化页面

if(this.IsPostBack)this.SaveImages();

}

privateBooleanSaveImages()

{

///'遍历File表单元素

HttpFileCollectionfiles=HttpContext.Current.Request.Files;

///'状态信息

System.Text.StringBuilderstrMsg=newSystem.Text.StringBuilder();

strMsg.Append("上传的文件分别是:<hrcolor=red>");

try

{

for(intiFile=0;iFile<files.Count;iFile++)

{

///'检查文件扩展名字

HttpPostedFilepostedFile=files[iFile];

stringfileName,fileExtension,file_id;

//取出精确到毫秒的时间做文件的名称

intyear=System.DateTime.Now.Year;

intmonth=System.DateTime.Now.Month;

intday=System.DateTime.Now.Day;

inthour=System.DateTime.Now.Hour;

intminute=System.DateTime.Now.Minute;

intsecond=System.DateTime.Now.Second;

intmillisecond=System.DateTime.Now.Millisecond;

stringmy_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();

returntrue;

}

catch(System.ExceptionEx)

{

strStatus.Text=Ex.Message;

returnfalse;

}

}

发表于@2005年12月30日3:37PM|评论(0)

邮件系统使用的上传附件方法

前台HTML代码

<formid="mail"method="post"runat="server">

<tableborder="0"cellpadding="0"cellspacing="0"bordercolor="#111111"

width="39%"id="AutoNumber1"height="75">

<tr>

<tdwidth="100%"height="37"><INPUTid="myFile"type="file"size="30"name="myFile"

runat="server">

<asp:buttonid="Upload"runat="server"Text="上传附件"></asp:button></td>

</tr>

<tr>

<tdwidth="100%"height="38">

共计

<asp:textboxid="P_size"runat="server"Width="65px"></asp:textbox>KB

<asp:dropdownlistid="dlistBound"runat="server"></asp:dropdownlist>

<asp:buttonid="btnDel"runat="server"Text="删除附件"></asp:button></td>

</tr>

</table>

</form>

后台CS代码

publicclassUpload_Mail:System.Web.UI.Page

{

protectedSystem.Web.UI.WebControls.ButtonUpload;

protectedSystem.Web.UI.WebControls.DropDownListdlistBound;

protectedSystem.Web.UI.WebControls.TextBoxP_size;

protectedSystem.Web.UI.WebControls.ButtonbtnDel;

protectedSystem.Web.UI.HtmlControls.HtmlInputFilemyFile;

privatevoidPage_Load(objectsender,System.EventArgse)

{

if(!IsPostBack)

{

//没有附件的状态

dlistBound.Items.Clear();

ArrayListarr=newArrayList();

arr.Add("--没有附件--");

dlistBound.DataSource=arr;

dlistBound.DataBind();

P_size.Text="0";

}

}

privatevoidUpload_Click(objectsender,System.EventArgse)

{

if(myFile.PostedFile!=null)

{

HttpFileCollectionfiles=HttpContext.Current.Request.Files;

HttpPostedFilepostedFile=files[0];

stringfileName=System.IO.Path.GetFileName(postedFile.FileName);

stringpath=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('|');

ArrayListlist=newArrayList(udMail);

list.Reverse();

udMail=(string[])list.ToArray(typeof(string));

dlistBound.Items.Clear();

longdirsize=0;

for(inti=0;i<udMail.Length;i++)

{

stringIndexItem=udMail[i];

stringVauleItem=Request.PhysicalApplicationPath+@"UploadMail"+udMail[i];

dlistBound.Items.Add(newListItem(IndexItem,VauleItem));

System.IO.FileInfomysize=newSystem.IO.FileInfo(@VauleItem);

dirsize+=System.Convert.ToInt32(mysize.Length/1024)+1;

}

P_size.Text=dirsize.ToString();

}

}

privatevoidbtnDel_Click(objectsender,System.EventArgse)

{

stringtrueDelfile=dlistBound.SelectedValue.ToString();

stringDelfile=dlistBound.SelectedItem.ToString();

usageIO.DeletePath(trueDelfile);

if(Session["udMail"]!=null)

{

intindex=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('|');

ArrayListvalues=newArrayList(udMail);

values.Remove(Delfile);

strings=null;

for(inti=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('|');

ArrayListlist=newArrayList(uMail);

list.Reverse();

uMail=(string[])list.ToArray(typeof(string));

dlistBound.Items.Clear();

longdirsize=0;

for(inti=0;i<uMail.Length;i++)

{

stringIndexItem=uMail[i];

stringVauleItem=Request.PhysicalApplicationPath+@"UploadMail"+uMail[i];

dlistBound.Items.Add(newListItem(IndexItem,VauleItem));

System.IO.FileInfomysize=newSystem.IO.FileInfo(@VauleItem);

dirsize+=System.Convert.ToInt32(mysize.Length/1024)+1;

}

P_size.Text=dirsize.ToString();

}

}

}

Web窗体设计器生成的代码#regionWeb窗体设计器生成的代码

overrideprotectedvoidOnInit(EventArgse)

{

//

//CODEGEN:该调用是ASP.NETWeb窗体设计器所必需的。

//

InitializeComponent();

base.OnInit(e);

}

/**////<summary>

///设计器支持所需的方法-不要使用代码编辑器修改

///此方法的内容。

///</summary>

privatevoidInitializeComponent()

{

this.Upload.Click+=newSystem.EventHandler(this.Upload_Click);

this.btnDel.Click+=newSystem.EventHandler(this.btnDel_Click);

this.Load+=newSystem.EventHandler(this.Page_Load);

}

#endregion

}

发表于@2005年12月30日3:29PM|评论(0)

上传图片并且生成可以控制大小图片清晰度的方法

privatevoidUpload_Click(objectsender,System.EventArgse)

{

if(myFile.PostedFile!=null)

{

//检查文件扩展名字

HttpFileCollectionfiles=HttpContext.Current.Request.Files;

HttpPostedFilepostedFile=files[0];

stringfileName,fileExtension,file_id,file_path;

//取出精确到毫秒的时间做文件的名称

intyear=System.DateTime.Now.Year;

intmonth=System.DateTime.Now.Month;

intday=System.DateTime.Now.Day;

inthour=System.DateTime.Now.Hour;

intminute=System.DateTime.Now.Minute;

intsecond=System.DateTime.Now.Second;

intmillisecond=System.DateTime.Now.Millisecond;

stringmy_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+@"imagesarticle_images"+file_id);

//处理图片大小

intwidth,height,level;

width=120;

height=90;

level=100;//从1-100

GetThumbnailImage(width,height,level,file_id);

}

}

//生成缩略图函数

publicvoidGetThumbnailImage(intwidth,intheight,intlevel,stringfile_id)

{

stringnewfile=Request.PhysicalApplicationPath+"images/article_images/"+"top_"+file_id;

System.Drawing.Imageoldimage=System.Drawing.Image.FromFile(Request.PhysicalApplicationPath+"images/article_images/"+file_id);

System.Drawing.ImagethumbnailImage=oldimage.GetThumbnailImage(width,height,newSystem.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),IntPtr.Zero);

Bitmapoutput=newBitmap(thumbnailImage);

//处理JPG质量的函数

ImageCodecInfo[]codecs=ImageCodecInfo.GetImageEncoders();

ImageCodecInfoici=null;

foreach(ImageCodecInfocodecincodecs){if(codec.MimeType=="image/jpeg")ici=codec;}

EncoderParametersep=newEncoderParameters();

ep.Param[0]=newEncoderParameter(Encoder.Quality,(long)level);

output.Save(newfile,ici,ep);

//释放所有使用对象

ep.Dispose();

output.Dispose();

oldimage.Dispose();

thumbnailImage.Dispose();

//删除源图片

stringfile_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>");

}

boolThumbnailCallback()

{

returnfalse;

}

发表于@2005年12月30日3:25PM|评论(0)

生成高清晰度的缩略图[方法1]

publicvoidpic_zero(stringsourcepath,stringaimpath,intscale)

{

stringoriginalFilename=sourcepath;

//生成的高质量图片名称

stringstrGoodFile=aimpath;

//从文件取得图片对象

System.Drawing.Imageimage=System.Drawing.Image.FromFile(originalFilename);

intiImgWidth=image.Width;

intiImgHeight=image.Height;

intiScale=(iImgWidth/scale)>(iImgHeight/scale)?(iImgWidth/scale):(iImgHeight/scale);

//取得图片大小

System.Drawing.Sizesize=newSize(image.Width/iScale,image.Height/iScale);

//新建一个bmp图片

System.Drawing.Imagebitmap=newSystem.Drawing.Bitmap(size.Width,size.Height);

//新建一个画板

System.Drawing.Graphicsg=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,newSystem.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height),

newSystem.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:23PM|评论(0)

比较完美的图片验证码

需要引用的名字空间

usingSystem.IO;

usingSystem.Drawing.Imaging;

usingSystem.Drawing.Drawing2D;

publicclassValidationCodeImg:System.Web.UI.Page

{

privatevoidPage_Load(objectsender,System.EventArgse)

{

this.CreateCheckCodeImage(GenerateCheckCode());

}

privatestringGenerateCheckCode()

{

intnumber;

charcode;

stringcheckCode=String.Empty;

System.Randomrandom=newRandom();

for(inti=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(newHttpCookie("CheckCode",checkCode));

returncheckCode;

}

privatevoidCreateCheckCodeImage(stringcheckCode)

{

if(checkCode==null||checkCode.Trim()==String.Empty)

return;

System.Drawing.Bitmapimage=newSystem.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*12.5)),24);

Graphicsg=Graphics.FromImage(image);

try

{

//生成随机生成器

Randomrandom=newRandom();

//清空图片背景色

g.Clear(Color.White);

//画图片的背景噪音线

for(inti=0;i<2;i++)

{

intx1=random.Next(image.Width);

intx2=random.Next(image.Width);

inty1=random.Next(image.Height);

inty2=random.Next(image.Height);

g.DrawLine(newPen(Color.Silver),x1,y1,x2,y2);

}

Fontfont=newSystem.Drawing.Font("Tahoma",12,(System.Drawing.FontStyle.Bold|System.Drawing.FontStyle.Italic));

System.Drawing.Drawing2D.LinearGradientBrushbrush=newSystem.Drawing.Drawing2D.LinearGradientBrush(newRectangle(0,0,image.Width,image.Height),Color.Black,Color.Black,1.2f,true);

g.DrawString(checkCode,font,brush,2,2);

//画图片的前景噪音点

for(inti=0;i<100;i++)

{

intx=random.Next(image.Width);

inty=random.Next(image.Height);

image.SetPixel(x,y,Color.FromArgb(random.Next()));

}

//画图片的边框线

g.DrawRectangle(newPen(Color.Silver),0,0,image.Width-1,image.Height-1);

System.IO.MemoryStreamms=newSystem.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:09PM|评论(0)

IE订单的打印处理办法

在一个商城项目应用中我需要把客户在网上下的订单使用IE打印出来

首先必须控制订单不能出现IE的页眉页脚(需要使用ScriptX)

<OBJECTid="factory"codeBase="http://www.meadroid.com/scriptx/ScriptX.cab#Version=5,60,0,360"

classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"viewastext>

</OBJECT>

<SCRIPTdefer>

functionprintln(){

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>

然后主要是控制订单数据输出用什么办法显示出来,为了灵活的控制输出效果,我这里使用的是循环读入数据(定购的商品)的办法(下面的代码是我使用的)

publicstringmyOrder(stringB_No)

{

doData.conn.Open();

stringstrFirstMenu=null;

stringstrSql="selectItems_Type,Items_Name,Items_Unit,Items_Count,Items_Pricefrom[OrderItems]whereOrder_No='"+B_No+"'orderbyIDdesc";

SqlDataAdapterda=newSqlDataAdapter(strSql,doData.conn);

DataSetds=newDataSet();

da.Fill(ds,"myOrder");

intcount=ds.Tables[0].Rows.Count;

stringItems_Type,Items_Name,Items_Price,Items_Count,Items_Unit,Items_TotalPrice;

DoubleItems_AllTotalPrice=0;

intItems_TotalCount=0;

stringbegin="<tableid="inc"borderColor="#111111"height="35"cellSpacing="0"cellPadding="0"width="95%"border="1"><tr><tdalign="center"width="14%"height="35">商品编号</td><tdalign="center"width="25%"height="35">商品名称</td><tdalign="center"width="10%"height="35">单位</td><tdalign="center"width="10%"height="35">数量</td><tdalign="center"width="20%"height="35">单价(元)</td><tdalign="center"width="21%"height="35">金额(元)</td></tr>";

for(intrb=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><tdwidth="14%"height="20">"+Items_Type+"</td><tdwidth="25%"height="20">"+Items_Name+"</td><tdwidth="10%"height="20">"+Items_Unit+"</td><tdwidth="10%"height="20">"+Items_Count+"</td><tdwidth="20%"height="20">"+Items_Price+"</td><tdwidth="21%"height="20">"+Items_TotalPrice+"</td></tr>";

}

stringFirstMenu=begin+strFirstMenu+"</table>";

doData.conn.Close();

returnFirstMenu;

}

发表于@2005年12月30日3:06PM|评论(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};

publicstringEncrypt(stringstrText)

{

try

{

DESCryptoServiceProviderdes=newDESCryptoServiceProvider();

Byte[]inputByteArray=Encoding.UTF8.GetBytes(strText);

MemoryStreamms=newMemoryStream();

CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(byKey64,Iv64),CryptoStreamMode.Write);

cs.Write(inputByteArray,0,inputByteArray.Length);

cs.FlushFinalBlock();

returnConvert.ToBase64String(ms.ToArray());

}

catch(Exceptionex)

{

returnex.Message;

}

}

privatevoidbtnLogin_Click(objectsender,System.Web.UI.ImageClickEventArgse)

{

DateTimenowTime=DateTime.Now;

stringpostUser=txtUser.Text.ToString();

stringpostPass=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};

publicstringDecrypt(stringstrText)

{

Byte[]inputByteArray=newbyte[strText.Length];

try

{

DESCryptoServiceProviderdes=newDESCryptoServiceProvider();

inputByteArray=Convert.FromBase64String(strText);

MemoryStreamms=newMemoryStream();

CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(byKey64,Iv64),CryptoStreamMode.Write);

cs.Write(inputByteArray,0,inputByteArray.Length);

cs.FlushFinalBlock();

System.Text.Encodingencoding=System.Text.Encoding.UTF8;

returnencoding.GetString(ms.ToArray());

}

catch(Exceptionex)

{

returnex.Message;

}

}

privatevoidPage_Load(objectsender,System.EventArgse)

{

if(Request.Params["clubID"]!=null)

{

stringoriginalValue=Request.Params["clubID"];

originalValue=originalValue.Replace("","+");

//+号通过url传递变成了空格。

stringdecryptResult=Decrypt(originalValue);

//DecryptString(string)解密字符串

stringdelimStr=",";

char[]delimiterArray=delimStr.ToCharArray();

string[]userInfoArray=null;

userInfoArray=decryptResult.Split(delimiterArray);

stringuserName=userInfoArray[0];

UseruserToLogin=newUser();

userToLogin.Username=userInfoArray[0];

userToLogin.Password=userInfoArray[1];

......

}

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新asp.net教程学习
    热门asp.net教程学习
    编程开发子分类