一個生成不重復隨機數的方法
//生成不重復隨機數算法
private int GetRandomNum(int i
int length
int up
int down)
{
int iFirst=
;
Random ro=new Random(i*length*unchecked((int)DateTime
Now
Ticks))
iFirst=ro
Next(up
down)
return iFirst;
}
發表於 @
年
月
日
:
PM | 評論 (
)
ASP
NET多文件上傳方法
前台代碼
<script language=
Javascript
>
function addFile()
{
var str =
<INPUT type=
file
size=
NAME=
File
><br>
document
getElementById(
MyFile
)
insertAdjacentHTML(
beforeEnd
str)
}
</script>
<form id=
form
method=
post
runat=
server
enctype=
multipart/form
data
>
<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=
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=
pt
Width=
px
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 =
; 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;
}
}
發表於 @
年
月
日
:
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 : 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 =
;
}
}
private void Upload_Click(object sender
System
EventArgs e)
{
if(myFile
PostedFile !=null)
{
HttpFileCollection files = HttpContext
Current
Request
Files;
HttpPostedFile postedFile = files[
];
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=
;
for(int i =
;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
ToInt
(mysize
Length/
)+
;
}
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 ==
)
{
Session[
udMail
] = null;
dlistBound
Items
Clear()
dlistBound
Items
Add(
沒有附件
)
P_size
Text =
;
}
else
{
string[] udMail = Session[
udMail
]
ToString()
Split(
|
)
ArrayList values = new ArrayList(udMail)
values
Remove(Delfile)
string s = null;
for(int i=
;i<values
Count;i++)
{
if(values
Count!=
)
{
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=
;
for(int i =
;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
ToInt
(mysize
Length/
)+
;
}
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
}
發表於 @
年
月
日
:
PM | 評論 (
)
上傳圖片並且生成可以控制大小圖片清晰度的方法
private void Upload_Click(object sender
System
EventArgs e)
{
if(myFile
PostedFile !=null)
{
// 檢查文件擴展名字
HttpFileCollection files = HttpContext
Current
Request
Files;
HttpPostedFile postedFile = files[
];
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=
;
height=
;
level=
;//從
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[
]=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
Form
A_Simg
value =
+file_path+
;location
replace(
Upload_Img
aspx
)</script>
)
}
bool ThumbnailCallback()
{
return false;
}
發表於 @
年
月
日
:
PM | 評論 (
)
生成高清晰度的縮略圖[方法
]
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
Drawing
D
InterpolationMode
High;
//設置高質量
低速度呈現平滑程度
g
SmoothingMode = System
Drawing
Drawing
D
SmoothingMode
HighQuality;
//清空一下畫布
g
Clear(Color
Blue)
//在指定位置畫圖
g
DrawImage(image
new System
Drawing
Rectangle(
bitmap
Width
bitmap
Height)
new System
Drawing
Rectangle(
image
Width
image
Height)
System
Drawing
GraphicsUnit
Pixel)
//保存高清晰度的縮略圖
bitmap
Save(strGoodFile
System
Drawing
Imaging
ImageFormat
Jpeg)
g
Dispose()
}
發表於 @
年
月
日
:
PM | 評論 (
)
比較完美的圖片驗證碼
需要引用的名字空間
using System
IO;
using System
Drawing
Imaging;
using System
Drawing
Drawing
D;
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=
; i<
; i++)
{
number = random
Next()
if(number %
==
)
code = (char)(
+ (char)(number %
))
else
code = (char)(
+ (char)(number %
))
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 *
))
)
Graphics g = Graphics
FromImage(image)
try
{
//生成隨機生成器
Random random = new Random()
//清空圖片背景色
g
Clear(Color
White)
//畫圖片的背景噪音線
for(int i=
; i<
; i++)
{
int x
= random
Next(image
Width)
int x
= random
Next(image
Width)
int y
= random
Next(image
Height)
int y
= random
Next(image
Height)
g
DrawLine(new Pen(Color
Silver)
x
y
x
y
)
}
Font font = new System
Drawing
Font(
Tahoma
(System
Drawing
FontStyle
Bold | System
Drawing
FontStyle
Italic))
System
Drawing
Drawing
D
LinearGradientBrush brush = new System
Drawing
Drawing
D
LinearGradientBrush(new Rectangle(
image
Width
image
Height)
Color
Black
Color
Black
f
true)
g
DrawString(checkCode
font
brush
)
//畫圖片的前景噪音點
for(int i=
; i<
; 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)
image
Width
image
Height
)
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()
}
}
發表於 @
年
月
日
:
PM | 評論 (
)
IE訂單的打印處理辦法
在一個商城項目應用中我需要把客戶在網上下的訂單使用IE打印出來
首先必須控制訂單不能出現IE的頁眉頁腳(需要使用ScriptX)
<OBJECT id=
factory
codeBase=
classid=
clsid:
ed
eb
d
b
f
fdd
viewastext>
</OBJECT>
<SCRIPT defer>
function println() {
factory
printing
header =
factory
printing
footer =
factory
printing
Print(true)
factory
printing
leftMargin =
factory
printing
topMargin =
factory
printing
rightMargin =
factory
printing
bottomMargin =
window
print()
}
</SCRIPT>
然後主要是控制訂單數據輸出用什麼辦法顯示出來
為了靈活的控制輸出效果
我這裡使用的是循環讀入數據(定購的商品)的辦法(下面的代碼是我使用的)
public string myOrder(string B_No)
{
nn
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
nn)
DataSet ds = new DataSet()
da
Fill(ds
myOrder
)
int count = ds
Tables[
]
Rows
Count;
string Items_Type
Items_Name
Items_Price
Items_Count
Items_Unit
Items_TotalPrice;
Double Items_AllTotalPrice =
;
int Items_TotalCount =
;
string begin =
<table id =\
inc\
style=\
BORDER
COLLAPSE: 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 = ds
Tables[
]
Rows[rb][
]
ToString()
Items_Name = ds
Tables[
]
Rows[rb][
]
ToString()
Items_Unit = ds
Tables[
]
Rows[rb][
]
ToString()
Items_Count = ds
Tables[
]
Rows[rb][
]
ToString()
Items_Price = Double
Parse(ds
Tables[
]
Rows[rb][
]
ToString())
ToString(
)
Items_TotalPrice = (Double
Parse(Items_Price)*Double
Parse(Items_Count))
ToString(
)
Items_AllTotalPrice += Double
Parse(Items_TotalPrice)
Items_TotalCount += Int
Parse(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>
;
nn
Close()
return FirstMenu;
}
發表於 @
年
月
日
:
PM | 評論 (
)
URL傳輸參數加密解密
最近做一個論壇入口時要實現帳號和密碼不在IE地址欄出現而做的
index
aspx
cs (加密處理)
Byte[] Iv
={
};
Byte[] byKey
={
};
public string Encrypt(string strText)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider()
Byte[] inputByteArray = Encoding
UTF
GetBytes(strText)
MemoryStream ms = new MemoryStream()
CryptoStream cs = new CryptoStream(ms
des
CreateEncryptor(byKey
Iv
)
CryptoStreamMode
Write)
cs
Write(inputByteArray
inputByteArray
Length)
cs
FlushFinalBlock()
return Convert
ToBase
String(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 (解密處理)
//隨機選
個字節既為密鑰也為初始向量
Byte[] byKey
={
};
Byte[] Iv
={
};
public string Decrypt(string strText)
{
Byte[] inputByteArray = new byte[strText
Length];
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider()
inputByteArray = Convert
FromBase
String(strText)
MemoryStream ms = new MemoryStream()
CryptoStream cs = new CryptoStream(ms
des
CreateDecryptor(byKey
Iv
)
CryptoStreamMode
Write)
cs
Write(inputByteArray
inputByteArray
Length)
cs
FlushFinalBlock()
System
Text
Encoding encoding = System
Text
Encoding
UTF
;
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[
];
User userToLogin = new User()
userToLogin
Username = userInfoArray[
];
userToLogin
Password = userInfoArray[
];
……
}
}
From:http://tw.wingwit.com/Article/program/net/201311/13020.html