asp.net

位置:IT落伍者 >> asp.net >> 浏览文章

ASP.NET(C#)


发布日期:2021年04月26日
 
ASP.NET(C#)
一个生成不重复随机数的方法

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

private int GetRandomNum(int iint lengthint upint down)

{

int iFirst=;

Random ro=new Random(i*length*unchecked((int)DateTimeNowTicks))

iFirst=roNext(updown)

return iFirst;

}

发表于 @ : PM | 评论 (

ASPNET多文件上传方法

前台代码

<script language=Javascript>

function addFile()

{

var str = <INPUT type=file size= NAME=File><br>

documentgetElementById(MyFileinsertAdjacentHTML(beforeEndstr)

}

</script>

<form id=form method=post runat=server enctype=multipart/formdata>

<div align=center>

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

<P id=MyFile><INPUT type=file size= NAME=File><br></P>

<P>

<input type=button value=增加(Add) onclick=addFile()> <input onclick=thisformreset() type=button value=重置(ReSet)>

<asp:Button Runat=server Text=开始上传 ID=UploadButton>

</asp:Button>

</P>

<P>

<asp:Label id=strStatus runat=server FontNames=宋体 FontBold=True FontSize=pt Width=px

BorderStyle=None BorderColor=White></asp:Label>

</P>

</div>

</form>

后台代码

protected SystemWebUIWebControlsButton UploadButton;

protected SystemWebUIWebControlsLabel strStatus;

private void Page_Load(object sender SystemEventArgs e)

{

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

if (thisIsPostBack) thisSaveImages()

}

private Boolean SaveImages()

{

///遍历File表单元素

HttpFileCollection files = HttpContextCurrentRequestFiles;

/// 状态信息

SystemTextStringBuilder strMsg = new SystemTextStringBuilder()

strMsgAppend(上传的文件分别是<hr color=red>

try

{

for(int iFile = ; iFile < filesCount; iFile++)

{

///检查文件扩展名字

HttpPostedFile postedFile = files[iFile];

string fileNamefileExtensionfile_id;

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

int year = SystemDateTimeNowYear;

int month = SystemDateTimeNowMonth;

int day = SystemDateTimeNowDay;

int hour = SystemDateTimeNowHour;

int minute = SystemDateTimeNowMinute;

int second = SystemDateTimeNowSecond;

int millisecond = SystemDateTimeNowMillisecond;

string my_file_id = yearToString() + monthToString() + dayToString() + hourToString() + minuteToString() + secondToString() + millisecondToString()+iFileToString()

fileName = SystemIOPathGetFileName(postedFileFileName)

fileExtension = SystemIOPathGetExtension(fileName)

file_id = my_file_id+fileExtension;

if (fileName !=

{

fileExtension = SystemIOPathGetExtension(fileName)

strMsgAppend(上传的文件类型 + postedFileContentTypeToString() + <br>

strMsgAppend(客户端文件地址 + postedFileFileName + <br>

strMsgAppend(上传文件的文件名 + file_id + <br>

strMsgAppend(上传文件的扩展名 + fileExtension + <br><hr>

postedFileSaveAs(SystemWebHttpContextCurrentRequestMapPath(images/) + file_id)

}

}

strStatusText = strMsgToString()

return true;

}

catch(SystemException Ex)

{

strStatusText = ExMessage;

return false;

}

}

发表于 @ : PM | 评论 (

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

前台HTML代码

<form id=mail method=post runat=server>

<table border= cellpadding= cellspacing=  bordercolor=#

width=% id=AutoNumber height=>

<tr>

<td width=% height=><INPUT id=myFile  type=file size= name=myFile

runat=server>

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

</tr>

<tr>

<td width=% height=>

共计

<asp:textbox id=P_size runat=server Width=px></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 : SystemWebUIPage

{

protected SystemWebUIWebControlsButton Upload;

protected SystemWebUIWebControlsDropDownList dlistBound;

protected SystemWebUIWebControlsTextBox P_size;

protected SystemWebUIWebControlsButton btnDel;

protected SystemWebUIHtmlControlsHtmlInputFile myFile;

private void Page_Load(object sender SystemEventArgs e)

{

if (!IsPostBack)

{

//没有附件的状态

dlistBoundItemsClear()

ArrayList arr = new ArrayList()

arrAdd(没有附件

dlistBoundDataSource = arr ;

dlistBoundDataBind()

P_sizeText = ;

}

}

private void Upload_Click(object sender SystemEventArgs e)

{

if(myFilePostedFile !=null)

{

HttpFileCollection files = HttpContextCurrentRequestFiles;

HttpPostedFile postedFile = files[];

string fileName = SystemIOPathGetFileName(postedFileFileName)

string path = RequestPhysicalApplicationPath+@UploadMail\+ fileName;

postedFileSaveAs(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)

listReverse()

udMail=(string[])listToArray(typeof(string))

dlistBoundItemsClear()

long dirsize=;

for(int i = ;i<udMailLength;i++)

{

string IndexItem = udMail[i];

string VauleItem = RequestPhysicalApplicationPath+@UploadMail\+udMail[i];

dlistBoundItemsAdd(new ListItem(IndexItemVauleItem))

SystemIOFileInfo mysize = new SystemIOFileInfo(@VauleItem)

dirsize += SystemConvertToInt(mysizeLength/)+;

}

P_sizeText = dirsizeToString()

}

}

private void btnDel_Click(object sender SystemEventArgs e)

{

string trueDelfile = dlistBoundSelectedValueToString()

string Delfile = dlistBoundSelectedItemToString()

usageIODeletePath(trueDelfile)

if(Session[udMail] != null)

{

int index = Session[udMail]ToString()IndexOf(|

if(index ==

{

Session[udMail] = null;

dlistBoundItemsClear()

dlistBoundItemsAdd(没有附件

P_sizeText = ;

}

else

{

string[] udMail = Session[udMail]ToString()Split(|

ArrayList values = new ArrayList(udMail)

valuesRemove(Delfile)

string s = null;

for(int i=;i<valuesCount;i++)

{

if(valuesCount!=

{

s += values[i]ToString()+|;

}

}

if(s!=||s!=null)

{

s = sTrimEnd(|

}

Session[udMail] = s;

string[] uMail = Session[udMail]ToString()Split(|

ArrayList list = new ArrayList(uMail)

listReverse()

uMail=(string[])listToArray(typeof(string))

dlistBoundItemsClear()

long dirsize=;

for(int i = ;i<uMailLength;i++)

{

string IndexItem = uMail[i];

string VauleItem = RequestPhysicalApplicationPath+@UploadMail\+uMail[i];

dlistBoundItemsAdd(new ListItem(IndexItemVauleItem))

SystemIOFileInfo mysize = new SystemIOFileInfo(@VauleItem)

dirsize += SystemConvertToInt(mysizeLength/)+;

}

P_sizeText = dirsizeToString()

}

}

}

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

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: 该调用是 ASPNET Web 窗体设计器所必需的

//

InitializeComponent()

baseOnInit(e)

}

/**//// <summary>

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

/// 此方法的内容

/// </summary>

private void InitializeComponent()

{

thisUploadClick += new SystemEventHandler(thisUpload_Click)

thisbtnDelClick += new SystemEventHandler(thisbtnDel_Click)

thisLoad += new SystemEventHandler(thisPage_Load)

}

#endregion

}

发表于 @ : PM | 评论 (

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

private void Upload_Click(object sender SystemEventArgs e)

{

if(myFilePostedFile !=null)

{

// 检查文件扩展名字

HttpFileCollection files = HttpContextCurrentRequestFiles;

HttpPostedFile postedFile = files[];

string fileNamefileExtensionfile_idfile_path;

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

int year = SystemDateTimeNowYear;

int month = SystemDateTimeNowMonth;

int day = SystemDateTimeNowDay;

int hour = SystemDateTimeNowHour;

int minute = SystemDateTimeNowMinute;

int second = SystemDateTimeNowSecond;

int millisecond = SystemDateTimeNowMillisecond;

string my_file_id = yearToString() + monthToString() + dayToString() + hourToString() + minuteToString() + secondToString() + millisecondToString()

//获得文件类型

fileName = SystemIOPathGetFileName(postedFileFileName)

fileExtension = SystemIOPathGetExtension(fileName)

//重新命名文件防止重复

file_id = topnews_+my_file_id+fileExtension;

file_path = images/article_images/+file_id;

//文件上传到服务器的根目录

postedFileSaveAs(RequestPhysicalApplicationPath+@images\article_images\+ file_id)

//处理图片大小

int widthheightlevel;

width=;

height=;

level=;//从

GetThumbnailImage(widthheightlevelfile_id)

}

}

//生成缩略图函数

public void GetThumbnailImage(int widthint heightint levelstring file_id)

{

string newfile= RequestPhysicalApplicationPath+images/article_images/+top_+ file_id;

SystemDrawingImage oldimage = SystemDrawingImageFromFile(RequestPhysicalApplicationPath+images/article_images/+ file_id)

SystemDrawingImage thumbnailImage = oldimageGetThumbnailImage(width heightnew SystemDrawingImageGetThumbnailImageAbort(ThumbnailCallback) IntPtrZero)

Bitmap output=new Bitmap(thumbnailImage)

//处理JPG质量的函数

ImageCodecInfo[] codecs=ImageCodecInfoGetImageEncoders()

ImageCodecInfo ici=null;

foreach(ImageCodecInfo codec in codecs){if(codecMimeType==image/jpeg)ici=codec;}

EncoderParameters ep=new EncoderParameters()

epParam[]=new EncoderParameter(EncoderQuality(long)level)

outputSave(newfileiciep)

//释放所有使用对象

epDispose()

outputDispose()

oldimageDispose()

thumbnailImageDispose()

//删除源图片

string file_path = images/article_images/+top_+file_id;

usageIODeletePath(RequestPhysicalApplicationPath+images/article_images/+ file_id)

ResponseWrite(<script >parentFormA_Simgvalue =+file_path+;locationreplace(Upload_Imgaspx)</script>

}

bool ThumbnailCallback()

{

return false;

}

发表于 @ : PM | 评论 (

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

public void pic_zero(string sourcepathstring aimpathint scale)

{

string originalFilename =sourcepath;

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

string strGoodFile =aimpath;

//从文件取得图片对象

SystemDrawingImage image = SystemDrawingImageFromFile(originalFilename)

int iImgWidth = imageWidth;

int iImgHeight = imageHeight;

int iScale = (iImgWidth / scale)>(iImgHeight/scale) ? (iImgWidth / scale) : (iImgHeight / scale)

//取得图片大小

SystemDrawingSize size = new Size(imageWidth / iScale imageHeight / iScale)

//新建一个bmp图片

SystemDrawingImage bitmap = new SystemDrawingBitmap(sizeWidthsizeHeight)

//新建一个画板

SystemDrawingGraphics g = SystemDrawingGraphicsFromImage(bitmap)

//设置高质量插值法

gInterpolationMode = SystemDrawingDrawingDInterpolationModeHigh;

//设置高质量低速度呈现平滑程度

gSmoothingMode = SystemDrawingDrawingDSmoothingModeHighQuality;

//清空一下画布

gClear(ColorBlue)

//在指定位置画图

gDrawImage(image new SystemDrawingRectangle( bitmapWidth bitmapHeight)

new SystemDrawingRectangle( imageWidthimageHeight)

SystemDrawingGraphicsUnitPixel)

//保存高清晰度的缩略图

bitmapSave(strGoodFile SystemDrawingImagingImageFormatJpeg)

gDispose()

}

发表于 @ : PM | 评论 (

比较完美的图片验证码

需要引用的名字空间

using SystemIO;

using SystemDrawingImaging;

using SystemDrawingDrawingD;

public class ValidationCodeImg : SystemWebUIPage

{

private void Page_Load(object sender SystemEventArgs e)

{

thisCreateCheckCodeImage(GenerateCheckCode())

}

private string GenerateCheckCode()

{

int number;

char code;

string checkCode = StringEmpty;

SystemRandom random = new Random()

for(int i=; i<; i++)

{

number = randomNext()

if(number % ==

code = (char)( + (char)(number % ))

else

code = (char)( + (char)(number % ))

checkCode += codeToString()

}

ResponseCookiesAdd(new HttpCookie(CheckCode checkCode))

return checkCode;

}

private void CreateCheckCodeImage(string checkCode)

{

if(checkCode == null || checkCodeTrim() == StringEmpty)

return;

SystemDrawingBitmap image = new SystemDrawingBitmap((int)MathCeiling((checkCodeLength * ))

Graphics g = GraphicsFromImage(image)

try

{

//生成随机生成器

Random random = new Random()

//清空图片背景色

gClear(ColorWhite)

//画图片的背景噪音线

for(int i=; i<; i++)

{

int x = randomNext(imageWidth)

int x = randomNext(imageWidth)

int y = randomNext(imageHeight)

int y = randomNext(imageHeight)

gDrawLine(new Pen(ColorSilver) x y x y

}

Font font = new SystemDrawingFont(Tahoma (SystemDrawingFontStyleBold | SystemDrawingFontStyleItalic))

SystemDrawingDrawingDLinearGradientBrush brush = new SystemDrawingDrawingDLinearGradientBrush(new Rectangle( imageWidth imageHeight) ColorBlack ColorBlack f true)

gDrawString(checkCode font brush

//画图片的前景噪音点

for(int i=; i<; i++)

{

int x = randomNext(imageWidth)

int y = randomNext(imageHeight)

imageSetPixel(x y ColorFromArgb(randomNext()))

}

//画图片的边框线

gDrawRectangle(new Pen(ColorSilver) imageWidth imageHeight

SystemIOMemoryStream ms = new SystemIOMemoryStream()

imageSave(ms SystemDrawingImagingImageFormatGif)

ResponseClearContent()

ResponseContentType = image/Gif;

ResponseBinaryWrite(msToArray())

}

finally

{

gDispose()

imageDispose()

}

}

发表于 @ : PM | 评论 (

IE订单的打印处理办法

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

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

<OBJECT id=factory  codeBase=

classid=clsid:edebdbffdd viewastext>

</OBJECT>

<SCRIPT defer>

function println() {

factoryprintingheader =

factoryprintingfooter =

factoryprintingPrint(true)

factoryprintingleftMargin =

factoryprintingtopMargin =

factoryprintingrightMargin =

factoryprintingbottomMargin =

windowprint()

}

</SCRIPT>

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

public string myOrder(string B_No)

{

nnOpen()

string strFirstMenu =null;

string strSql = select Items_TypeItems_NameItems_UnitItems_CountItems_Price from [OrderItems] where Order_No = +B_No+ order by ID desc;

SqlDataAdapter da = new SqlDataAdapter(strSqlnn)

DataSet ds = new DataSet()

daFill(dsmyOrder

int count = dsTables[]RowsCount;

string Items_TypeItems_NameItems_PriceItems_CountItems_UnitItems_TotalPrice;

Double Items_AllTotalPrice = ;

int Items_TotalCount = ;

string begin = <table id =\inc\style=\BORDERCOLLAPSE: collapse\ borderColor=\#\ height=\\ cellSpacing=\\ cellPadding=\\ width=\%\ border=\\><tr><td align=\center\ width=\%\ height=\\>商品编号</td><td align=\center\ width=\%\ height=\\>商品名称</td><td align=\center\ width=\%\ height=\\>单位</td><td align=\center\ width=\%\ height=\\>数量</td><td align=\center\ width=\%\ height=\\>单价(元)</td><td align=\center\ width=\%\ height=\\>金额(元)</td></tr>;

for(int rb = ; rb < count;rb++)

{

Items_Type = dsTables[]Rows[rb][]ToString()

Items_Name = dsTables[]Rows[rb][]ToString()

Items_Unit = dsTables[]Rows[rb][]ToString()

Items_Count = dsTables[]Rows[rb][]ToString()

Items_Price = DoubleParse(dsTables[]Rows[rb][]ToString())ToString(

Items_TotalPrice = (DoubleParse(Items_Price)*DoubleParse(Items_Count))ToString(

Items_AllTotalPrice += DoubleParse(Items_TotalPrice)

Items_TotalCount += IntParse(Items_Count)

strFirstMenu += <tr><td width=\%\ height=\\> +Items_Type+</td><td width=\%\ height=\\>+Items_Name+</td><td width=\%\ height=\\>+Items_Unit+</td><td width=\%\ height=\\>+Items_Count+</td><td width=\%\ height=\\>+Items_Price+</td><td width=\%\ height=\\>+Items_TotalPrice+</td></tr>;

}

string FirstMenu = begin+strFirstMenu+</table>;

nnClose()

return FirstMenu;

}

发表于 @ : PM | 评论 (

URL传输参数加密解密

最近做一个论坛入口时要实现帐号和密码不在IE地址栏出现而做的

indexaspxcs (加密处理)

Byte[] Iv={ };

Byte[] byKey={ };

public string Encrypt(string strText)

{

try

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider()

Byte[] inputByteArray = EncodingUTFGetBytes(strText)

MemoryStream ms = new MemoryStream()

CryptoStream cs = new CryptoStream(ms desCreateEncryptor(byKey Iv CryptoStreamModeWrite)

csWrite(inputByteArray inputByteArrayLength)

csFlushFinalBlock()

return ConvertToBaseString(msToArray())

}

catch(Exception ex)

{

return exMessage;

}

}

private void btnLogin_Click(object sender SystemWebUIImageClickEventArgs e)

{

DateTime nowTime = DateTimeNow;

string postUser = txtUserTextToString()

string postPass = txtPasswordTextToString()

ResponseRedirect(Loginaspx?clubID=+Encrypt(postUser++postPass++nowTimeToString()))

}

loginaspxcs (解密处理)

//随机选个字节既为密钥也为初始向量

Byte[] byKey={ };

Byte[] Iv={ };

public string Decrypt(string strText)

{

Byte[] inputByteArray = new byte[strTextLength];

try

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider()

inputByteArray = ConvertFromBaseString(strText)

MemoryStream ms = new MemoryStream()

CryptoStream cs = new CryptoStream(ms desCreateDecryptor(byKey Iv CryptoStreamModeWrite)

csWrite(inputByteArray inputByteArrayLength)

csFlushFinalBlock()

SystemTextEncoding encoding = SystemTextEncodingUTF;

return encodingGetString(msToArray())

}

catch(Exception ex)

{

return exMessage;

}

}

private void Page_Load(object sender SystemEventArgs e)

{

if(RequestParams[clubID]!=null)

{

string originalValue = RequestParams[clubID];

originalValue = originalValueReplace( +

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

string decryptResult = Decrypt(originalValue)

//DecryptString(string)解密字符串

string delimStr = ;

char[] delimiterArray = delimStrToCharArray()

string [] userInfoArray = null;

userInfoArray = decryptResultSplit(delimiterArray)

string userName = userInfoArray[];

User userToLogin = new User()

userToLoginUsername = userInfoArray[];

userToLoginPassword = userInfoArray[];

……

}

}

               

上一篇:ASP.NET 新特性之工程模板支持

下一篇:ASP.NET2.0中数据源控件之异步数据访问