2012年4月23日 星期一

[ASP] 常用函數表

Abs(number) 取得數值的絕對值。 
Asc(String) 取得字串運算式的第一個字元ASCII 碼。 
Atn(number) 取得一個角度的反正切值。 
CallByName (object, procname, usecalltype,[args()]) 執行一個物件的方法、設定或傳回物件的屬性。 
CBool(expression) 轉換運算式為Boolean 型態。 
CByte(expression) 轉換運算式為Byte 型態。 
CChar(expression) 轉換運算式為字元型態。 


CDate(expression) 轉換運算式為Date 型態。 

CDbl(expression) 轉換運算式為Double 型態。 
CDec(expression) 轉換運算式為Decimal 型態。 
CInt(expression) 轉換運算式為Integer 型態。 
CLng(expression) 轉換運算式為Long 型態。 
CObj(expression) 轉換運算式為Object 型態。 
CShort(expression) 轉換運算式為Short 型態。 
CSng(expression) 轉換運算式為Single 型態。 
CStr(expression) 轉換運算式為String 型態。 
Choose (index, choice-1[, choice-2, ... [, choice-n]) 以索引值來選擇並傳回所設定的參數。 
Chr(charcode) 以ASCII 碼來取得字元內容。 
Close(filenumberlist) 結束使用Open 開啟的檔案。 
Cos(number) 取得一個角度的余弦值。 
Ctype(expression, typename) 轉換運算式的型態。 
DateAdd(dateinterval, number, datetime) 對日期或時間作加減。 
DateDiff(dateinterval, date1, date2) 計算兩個日期或時間間的差值。 
DatePart (dateinterval, date) 依接收的日期或時間參數傳回年、月、日或時間。 
DateSerial(year, month, day) 將接收的參數合併為一個只有日期的Date 型態的資料。 
Datevalue(datetime) 取得符合國別設定樣式的日期值,並包含時間。
Day(datetime) 依接收的日期參數傳回日。 
Eof(filenumber) 當抵達一個被開啟的檔案結尾時會傳回True。 
Exp(number) 依接收的參數傳回e 的次方值。 
FileDateTime(pathname) 傳回檔案建立時的日期、時間。 
FileLen(pathname) 傳回檔案的長度,單位是Byte。 
Filter(sourcearray, match[, include[, compare]) 搜尋字串陣列中的指定字串,凡是陣列元素中含有指定字串,會將它們結合成新的字串陣列並傳回。若是要傳回不含指定字串的陣列元素,則include 參數設為False。compare 參數則是設定搜尋時是否區分大小寫,此時只要給TextCompare 常數或1 即可。 
Fix(number) 去掉參數的小數部分並傳回。 
Format(expression[, style[, firstdayofweek[, firstweekofyear]]) 將日期、時間和數值資料轉為每個國家都可以接受的格式。 
FormatCurrency(expression[,numdigitsafterdecimal [,includeleadingdigit]) 將數值輸出為金額型態。 
numdigitsafterdecimal 參數為小數字數,includeleadingdigit 參數為當整數為0 時是否補至整數字數。 
FormatDateTime(date[,namedformat]) 傳回格式化的日期或時間資料。 
FormatNumber(expression[,numdigitsafterdecimal [,includeleadingdigit]) 傳回格式化 
的數值資料。Numdigitsafterdecimal 參數為小數字數,includeleadingdigit 參數為當整數為0 時是否補至整數字數。 
FormatPercent(expression[,numdigitsafterdecimal [,includeleadingdigit]) 傳回轉換為百分比格式的數值資料。numdigitsafterdecimal 參數為小數字數,includeleadingdigit 參數為當整數為0 時是否補至整數字數。
GetAttr(filename) 傳回檔案或目錄的屬性值。 
Hex(number) 將數值參數轉換為16 進制值。 
Hour(time) 傳回時間的小時欄位,型態是Integer。 
Iif(expression, truepart, falsepart) 當運算式的傳回值為True 時執行truepart 欄位的程式,反之則執行falsepart 欄位。 
InStr([start, ]string1, string2) 搜尋string2 參數設定的字元出現在字串的第幾個字元,start 為由第幾個字元開始尋找,string1 為欲搜尋的字串,string2 為欲搜尋的字元。 
Int(number) 傳回小於或等於接收參數的最大整數值。 
IsArray(varname) 判斷一個變數是否為陣列型態,若為陣列則傳回True,反之則為False。
IsDate(expression) 判斷運算式內容是否為DateTime 型態,若是則傳回True,反之則為False。 
IsDbNull(expression) 判斷運算式內容是否為Null,若是則傳回True,反之則為False。 
IsNumeric(expression) 判斷運算式內容是否為數值型態,若是則傳回True,反之則為False。 
Join(sourcearray[, delimiter]) 將字串陣列合併唯一個字串,delimiter 參數是設定在各個元素間加入新的字串。 
Lcase(string) 將字串轉換為小寫字體。 
Left(string, length) 由字串左邊開始取得length 參數設定長度的字元。 
Len(string) 取得字串的長度。 
Log(number) 取得數值的自然對數。 
Ltrim(string) 去掉字串的左邊空白部分。 
Mid(string, start[, length]) 取出字串中strat 參數設定的字元後length 長度的字串,若length 參數沒有設定,則取回start 以後全部的字元。 
Minute(time) 取得時間內容的分部分,型態為Integer。 
MkDir(path) 建立一個新的目錄。 
Month(date) 取得日期的月部分,型態為Integer。
MonthName(month) 依接收的月份數值取得該月份的完整寫法。 
Now() 取得目前的日期和時間。 
Oct(number) 將數值參數轉換為8 進制值。 
Replace(expression, find, replace) 將字串中find 參數指定的字串轉換為replace 參數指定的字串。 
Right(string,length) 由字串右邊開始取得length 參數設定長度的字元。 
RmDir(path) 移除一個空的目錄。 
Rnd() 取得介於0 到1 之間的小數,如果每次都要取得不同的值,使用前需加上Randomize    



2012年4月20日 星期五

[ASP] 用Asp隱藏檔案路徑實現防盜鏈

如果我們知道一個靜態檔案的實際路徑如:http://www.xxxx.com/download/51windows.pdf,如果伺服器沒有作特別的限制設定,我們就可以毫不費力的把它下載下來!當網站提供51windows.pdf下載時,怎麼樣才能讓下載者無法得到他的實際路徑呢!本文就來介紹如何使用Asp來隱藏檔案的實際下載路徑。
  我們在管理網站檔案時,可以把附檔名一樣的檔案放在同一個目錄下,起一個比較特別名字,例如放pdf檔案目錄為the_pdf_file_s,把下面程式碼另存為down.asp,他的網上路徑為http://www.xx.com/down.asp,我們就可以用http://www.xx.com/down.asp?FileName=51windows.pdf來下載這個檔案了,而且下載者無法看到這個檔案實際下載路徑的!在down.asp中我們還可以設定下載檔案是否需要登入,判斷下載的來源頁是否為外部網站,從而可以做到防止檔案被盜鏈。
示例程式碼:

<%
From_url = Cstr(Request.ServerVariables("HTTP_REFERER"))
Serv_url = Cstr(Request.ServerVariables("SERVER_NAME"))

if mid(From_url,8,len(Serv_url)) <> Serv_url then
response.write "非法連結!" '防止盜鏈
response.end
end if
if Request.Cookies("Logined")="" then
response.redirect "/login.asp" '需要登入!
end if

Function GetFileName(longname)'/folder1/folder2/file.asp=>file.asp
while instr(longname,"/")
  longname = right(longname,len(longname)-1)
wend
GetFileName = longname
End Function

Dim Stream
Dim Contents
Dim FileName
Dim TrueFileName
Dim FileExt

Const adTypeBinary = 1
FileName = Request.QueryString("FileName")

if FileName = "" Then
    Response.Write "無效檔案名!"
    Response.End
End if

FileExt = Mid(FileName, InStrRev(FileName, ".") + 1)

Select Case UCase(FileExt)
    Case "ASP", "ASA", "ASPX", "ASAX", "MDB"
        Response.Write "非法操作!"
        Response.End
End Select

Response.Clear

if lcase(right(FileName,3))="gif" or lcase(right(FileName,3))="jpg" or lcase(right(FileName,3))="png" then
Response.ContentType = "image/*" '對圖像檔案不出現下載對話框
else
Response.ContentType = "application/ms-download"
end if

Response.AddHeader "content-disposition", "attachment; filename=" & GetFileName(Request.QueryString("FileName"))

Set Stream = server.CreateObject("ADODB.Stream")
Stream.Type = adTypeBinary
Stream.Open

if lcase(right(FileName,3))="pdf" then '設定pdf類型檔案目錄
TrueFileName = "/the_pdf_file_s/"&FileName
end if

if lcase(right(FileName,3))="doc" then '設定DOC類型檔案目錄
TrueFileName = "/my_D_O_C_file/"&FileName
end if

if lcase(right(FileName,3))="gif" or lcase(right(FileName,3))="jpg" or lcase(right(FileName,3))="png" then
TrueFileName = "/all_images_/"&FileName '設定圖像檔案目錄
end if

Stream.LoadFromFile Server.MapPath(TrueFileName)

While Not Stream.EOS
    Response.BinaryWrite Stream.Read(1024 * 64)
Wend

Stream.Close
Set Stream = Nothing
Response.Flush
Response.End
%>



2012年4月9日 星期一

[ASP.NET] asp.net中Bind和Eval的有什麼區別

TemplateField模組中Bind和Eval的有什麼區別 
eval()方法在運行時使用反射執行後期綁定計算,因此與標準的ASP.NET數據綁定方法bind相比,會導致性能明顯下降。它一般用在綁定時需要格式化字符串的情況下。多數情況盡量少用此方法
   
   
  Eval 方法是靜態(只讀)方法,該方法採用數據字段的值作為參數並將其作為字符串返回。 Bind 方法支持讀/寫功能,可以檢索數據綁定控件的值並將任何更改提交回數據庫。
   
  使用 Eval 方法
  Eval 方法可計算數據綁定控件(如GridView、DetailsView 和FormView 控件)的模板中的後期綁定數據表達式。在運行時,Eval 方法調用DataBinder 對象的Eval 方法,同時引用命名容器的當前數據項。命名容器通常是包含完整記錄的數據綁定控件的最小組成部分,如GridView 控件中的一行。因此,只能對數據綁定控件的模板內的綁定使用Eval 方法。
   
  Eval 方法以數據字段的名稱作為參數,從數據源的當前記錄返回一個包含該字段值的字符串。可以提供第二個參數來指定返回字符串的格式,該參數為可選參數。字符串格式參數使用為String 類的Format 方法定義的語法。
   
  使用 Bind 方法
  Bind 方法與Eval 方法有一些相似之處,但也存在很大的差異。雖然可以像使用Eval 方法一樣使用Bind 方法來檢索數據綁定字段的值,但當數據可以被修改時,還是要使用Bind 方法。
   
  在ASP.NET 中,數據綁定控件(如GridView、DetailsView 和FormView 控件)可自動使用數據源控件的更新、刪除和插入操作。例如,如果已為數據源控件定義了SQL Select、Insert、Delete 和Update 語句,則通過使用GridView、DetailsView 或FormView 控件模板中的Bind 方法,就可以使控件從模板中的子控件中提取值,並將這些值傳遞給數據源控件。然後數據源控件將執行適當的數據庫命令。出於這個原因,在數據綁定控件的EditItemTemplate 或InsertItemTemplate 中要使用Bind 函數。
   
  Bind 方法通常與輸入控件一起使用,例如由編輯模式中的GridView 行所呈現的TextBox 控件。當數據綁定控件將這些輸入控件作為自身呈現的一部分創建時,該方法便可提取輸入值。
   
  Bind 方法採用數據字段的名稱作為參數,從而與綁定屬性關聯,如下面的示例所示:
<EditItemTemplate>
   <table>
   <tr>
   <td align=right>
   <b>Employee ID:</b>
   </td>
   <td>
   <%# Eval("EmployeeID") %>
   </td>
   </tr>
   <tr>
   <td align=right>
   <b>First Name:</b>
   </td>
   <td>
   <asp:TextBox ID="EditFirstNameTextBox" RunAt="Server"
   Text='<%# Bind("FirstName") %>' />
   </td>
   </tr>
   <tr>
   <td align=right>
   <b>Last Name:</b>
   </td>
   <td>
   <asp:TextBox ID="EditLastNameTextBox" RunAt="Server"
   Text='<%# Bind("LastName") %>' />
   </td>
   </tr>
   <tr>
   <td colspan="2">
   <asp:LinkButton ID="UpdateButton" RunAt="server"
   Text="Update" CommandName="Update" />
  
   <asp:LinkButton ID="CancelUpdateButton" RunAt="server"
   Text="Cancel" CommandName="Cancel" />
   </td>
   </tr>
   </table>
  </EditItemTemplate>
單擊行的Update 按鈕時,使用Bind 語法綁定的每個控件屬性值都會被提取出來,並傳遞給數據源控件以執行更新操作。
   
   
  使用 DataBinder.Eval
  ASP.NET 提供了一個名為DataBinder.Eval 的靜態方法,該方法計算後期綁定的數據綁定表達式,並將結果格式化為字符串(可選)。利用此方法,可以避免許多在將值強制為所需數據類型時必須執行的顯式強制轉換操作。
   
  例如,在下面的代碼片段中,一個整數顯示為貨幣字符串。使用標準的ASP.NET 數據綁定語法,必須首先強制轉換數據行的類型以便檢索數據字段IntegerValue。然後,這將作為參數傳遞到String.Format 方法:
   
   
  <%# String.Format("{0:c}", ((DataRowView)Container.DataItem)["IntegerValue"]) %>
   
   
  將此語法與DataBinder.Eval 的語法進行比較,後者只有三個參數:數據項的命名容器、數據字段名稱和格式字符串。在模板化列表中(如DataList 類、DataGrid 類或Repeater 類),命名容器始終是Container.DataItem。
   
   
  <%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %>
   
   
  格式字符串參數是可選的。如果它被忽略,DataBinder.Eval 將返回類型對象的值,如下面的示例所示:
   
   
  <%# (bool)DataBinder.Eval(Container.DataItem, "BoolValue") %>
   
   
  當對模板化列表中的控件進行數據綁定時,DataBinder.Eval 特別有用,因為數據行和數據字段通常都必須強制轉換。 

C#加密算法匯總


方法一:
 //須添加對System.Web的引用 
 using System.Web.Security; 
 
 ... 
 
 /// <summary> 
 /// SHA1加密字符串 
 /// </summary> 
 /// <param name="source">源字符串</param> 
 /// <returns>加密後的字符串</returns> 
 public string SHA1(string source) 
 { 
     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1"); 
 } 


 /// <summary> 
 /// MD5加密字符串 
 /// </summary> 
 /// <param name="source">源字符串</param> 
 /// <returns>加密後的字符串</returns> 
 public string MD5(string source) 
 { 
     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");; 
 } 



方法二(可逆加密解密):
 using System.Security.Cryptography; 
 
 ... 
 
 public string Encode(string data) 
 { 
     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); 
     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); 
 
     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
     int i = cryptoProvider.KeySize; 
     MemoryStream ms = new MemoryStream(); 
     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); 
 
     StreamWriter sw = new StreamWriter(cst); 
     sw.Write(data); 
     sw.Flush(); 
     cst.FlushFinalBlock(); 
     sw.Flush(); 
     return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); 
 
 } 
 
 public string Decode(string data) 
 { 
     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); 
     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); 
 
     byte[] byEnc; 
     try 
     { 
         byEnc = Convert.FromBase64String(data); 
     } 
     catch 
     { 
         return null; 
     } 
 
     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
     MemoryStream ms = new MemoryStream(byEnc); 
     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read); 
     StreamReader sr = new StreamReader(cst); 
     return sr.ReadToEnd(); 
 } 
方法三(MD5不可逆):
 using System.Security.Cryptography; 
 
 ... 
 
 //MD5不可逆加密 
 
 //32位加密 
 
 public string GetMD5_32(string s, string _input_charset) 
 { 
     MD5 md5 = new MD5CryptoServiceProvider(); 
     byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s)); 
     StringBuilder sb = new StringBuilder(32); 
     for (int i = 0; i < t.Length; i++) 
     { 
         sb.Append(t[i].ToString("x").PadLeft(2, '0')); 
     } 
     return sb.ToString(); 
 } 
 
 //16位加密 
 public static string GetMd5_16(string ConvertString) 
 { 
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
     string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); 
     t2 = t2.Replace("-", ""); 
     return t2; 
 } 
方法四(對稱加密):
 using System.IO; 
 using System.Security.Cryptography; 
 
 ... 
 
 private SymmetricAlgorithm mobjCryptoService; 
 private string Key; 
 /// <summary>    
 /// 對稱加密類的構造函數    
 /// </summary>    
 public SymmetricMethod() 
 { 
     mobjCryptoService = new RijndaelManaged(); 
     Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7"; 
 } 
 /// <summary>    
 /// 獲得密鑰    
 /// </summary>    
 /// <returns>密鑰</returns>    
 private byte[] GetLegalKey() 
 { 
     string sTemp = Key; 
     mobjCryptoService.GenerateKey(); 
     byte[] bytTemp = mobjCryptoService.Key; 
     int KeyLength = bytTemp.Length; 
     if (sTemp.Length > KeyLength) 
         sTemp = sTemp.Substring(0, KeyLength); 
     else if (sTemp.Length < KeyLength) 
         sTemp = sTemp.PadRight(KeyLength, ' '); 
     return ASCIIEncoding.ASCII.GetBytes(sTemp); 
 } 
 /// <summary>    
 /// 獲得初始向量IV    
 /// </summary>    
 /// <returns>初試向量IV</returns>    
 private byte[] GetLegalIV() 
 { 
     string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; 
     mobjCryptoService.GenerateIV(); 
     byte[] bytTemp = mobjCryptoService.IV; 
     int IVLength = bytTemp.Length; 
     if (sTemp.Length > IVLength) 
         sTemp = sTemp.Substring(0, IVLength); 
     else if (sTemp.Length < IVLength) 
         sTemp = sTemp.PadRight(IVLength, ' '); 
     return ASCIIEncoding.ASCII.GetBytes(sTemp); 
 } 
 /// <summary>    
 /// 加密方法    
 /// </summary>    
 /// <param name="Source">待加密的串</param>    
 /// <returns>經過加密的串</returns>    
 public string Encrypto(string Source) 
 { 
     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); 
     MemoryStream ms = new MemoryStream(); 
     mobjCryptoService.Key = GetLegalKey(); 
     mobjCryptoService.IV = GetLegalIV(); 
     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); 
     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); 
     cs.Write(bytIn, 0, bytIn.Length); 
     cs.FlushFinalBlock(); 
     ms.Close(); 
     byte[] bytOut = ms.ToArray(); 
     return Convert.ToBase64String(bytOut); 
 } 
 /// <summary>    
 /// 解密方法    
 /// </summary>    
 /// <param name="Source">待解密的串</param>    
 /// <returns>經過解密的串</returns>    
 public string Decrypto(string Source) 
 { 
     byte[] bytIn = Convert.FromBase64String(Source); 
     MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length); 
     mobjCryptoService.Key = GetLegalKey(); 
     mobjCryptoService.IV = GetLegalIV(); 
     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor(); 
     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); 
     StreamReader sr = new StreamReader(cs); 
     return sr.ReadToEnd(); 
 } 
方法五:
 using System.IO; 
 using System.Security.Cryptography; 
 using System.Text; 
 
 ... 
 
 //默認密鑰向量 
 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 
 /// <summary> 
 /// DES加密字符串 
 /// </summary> 
 /// <param name="encryptString">待加密的字符串</param> 
 /// <param name="encryptKey">加密密鑰,要求為8位</param> 
 /// <returns>加密成功返回加密後的字符串,失敗返回源串</returns> 
 public static string EncryptDES(string encryptString, string encryptKey) 
 { 
     try 
     { 
         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); 
         byte[] rgbIV = Keys; 
         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 
         DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); 
         MemoryStream mStream = new MemoryStream(); 
         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 
         cStream.Write(inputByteArray, 0, inputByteArray.Length); 
         cStream.FlushFinalBlock(); 
         return Convert.ToBase64String(mStream.ToArray()); 
     } 
     catch 
     { 
         return encryptString; 
     } 
 } 
 
 /// <summary> 
 /// DES解密字符串 
 /// </summary> 
 /// <param name="decryptString">待解密的字符串</param> 
 /// <param name="decryptKey">解密密鑰,要求為8位,和加密密鑰相同</param> 
 /// <returns>解密成功返回解密後的字符串,失敗返源串</returns> 
 public static string DecryptDES(string decryptString, string decryptKey) 
 { 
     try 
     { 
         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); 
         byte[] rgbIV = Keys; 
         byte[] inputByteArray = Convert.FromBase64String(decryptString); 
         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); 
         MemoryStream mStream = new MemoryStream(); 
         CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 
         cStream.Write(inputByteArray, 0, inputByteArray.Length); 
         cStream.FlushFinalBlock(); 
         return Encoding.UTF8.GetString(mStream.ToArray()); 
     } 
     catch 
     { 
         return decryptString; 
     } 
 }  
方法六(文件加密):
 using System.IO; 
 using System.Security.Cryptography; 
 using System.Text; 
 
 ... 
 
 //加密文件 
 private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV) 
 { 
     //Create the file streams to handle the input and output files. 
     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); 
     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); 
     fout.SetLength(0); 
 
     //Create variables to help with read and write. 
     byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
     long rdlen = 0;              //This is the total number of bytes written. 
     long totlen = fin.Length;    //This is the total length of the input file. 
     int len;                     //This is the number of bytes to be written at a time. 
 
     DES des = new DESCryptoServiceProvider(); 
     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); 
 
     //Read from the input file, then encrypt and write to the output file. 
     while (rdlen < totlen) 
     { 
         len = fin.Read(bin, 0, 100); 
         encStream.Write(bin, 0, len); 
         rdlen = rdlen + len; 
     } 
 
     encStream.Close(); 
     fout.Close(); 
     fin.Close(); 
 } 
 
 //解密文件 
 private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV) 
 { 
     //Create the file streams to handle the input and output files. 
     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); 
     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); 
     fout.SetLength(0); 
 
     //Create variables to help with read and write. 
     byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
     long rdlen = 0;              //This is the total number of bytes written. 
     long totlen = fin.Length;    //This is the total length of the input file. 
     int len;                     //This is the number of bytes to be written at a time. 
 
     DES des = new DESCryptoServiceProvider(); 
     CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write); 
 
     //Read from the input file, then encrypt and write to the output file. 
     while (rdlen < totlen) 
     { 
         len = fin.Read(bin, 0, 100); 
         encStream.Write(bin, 0, len); 
         rdlen = rdlen + len; 
     } 
 
     encStream.Close(); 
     fout.Close(); 
     fin.Close(); 

}


using System;
using System.Security.Cryptography;//這個是處理文字編碼的前提
using System.Text;
using System.IO;
/// <summary>
/// DES加密方法
/// </summary>
/// <param name="strPlain">明文</param>
/// <param name="strDESKey">密鑰</param>
/// <param name="strDESIV">向量</param>
/// <returns>密文</returns>
public string DESEncrypt(string strPlain,string strDESKey,string strDESIV)
{
 //把密鑰轉換成字節數組
 byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
 //把向量轉換成字節數組
 byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
 //聲明1個新的DES對象
 DESCryptoServiceProvider desEncrypt=new DESCryptoServiceProvider();
 //開辟一塊內存流
 MemoryStream msEncrypt=new MemoryStream();
 //把內存流對象包裝成加密流對象
 CryptoStream csEncrypt=new CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write);
 //把加密流對象包裝成寫入流對象
 StreamWriter swEncrypt=new StreamWriter(csEncrypt);
 //寫入流對象寫入明文
 swEncrypt.WriteLine(strPlain);
 //寫入流關閉
 swEncrypt.Close();
 //加密流關閉
 csEncrypt.Close();
 //把內存流轉換成字節數組,內存流現在已經是密文了
 byte[] bytesCipher=msEncrypt.ToArray();
 //內存流關閉
 msEncrypt.Close();
 //把密文字節數組轉換為字符串,並返回
 return UnicodeEncoding.Unicode.GetString(bytesCipher);
}




/// <summary>
/// DES解密方法
/// </summary>
/// <param name="strCipher">密文</param>
/// <param name="strDESKey">密鑰</param>
/// <param name="strDESIV">向量</param>
/// <returns>明文</returns>
public string DESDecrypt(string strCipher,string strDESKey,string strDESIV)
{
 //把密鑰轉換成字節數組
 byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
 //把向量轉換成字節數組
 byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
 //把密文轉換成字節數組
 byte[] bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher);
 //聲明1個新的DES對象
 DESCryptoServiceProvider desDecrypt=new DESCryptoServiceProvider();
 //開辟一塊內存流,並存放密文字節數組
 MemoryStream msDecrypt=new MemoryStream(bytesCipher);
 //把內存流對象包裝成解密流對象
 CryptoStream csDecrypt=new CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read);
 //把解密流對象包裝成讀出流對象
 StreamReader srDecrypt=new StreamReader(csDecrypt);
 //明文=讀出流的讀出內容
 string strPlainText=srDecrypt.ReadLine();
 //讀出流關閉
 srDecrypt.Close();
 //解密流關閉
 csDecrypt.Close();
 //內存流關閉
 msDecrypt.Close();
 //返回明文
 return strPlainText;
}

asp.net中DataBinder.Eval的用法總結


DataBinder.Eval總結一、DataBinder.Eval的基本格式
在綁定數據時經常會用到這個句程序:<%# DataBinder.Eval(Container.DataItem,"xxxx")%>或者<%# DataBinder.Eval(Container,"DataItem.xxxx")%>
今天又學到一種,而且微軟也說這種方法的效率要比以上兩種高。
<%# ((DataRowView)Container.DataItem)["xxxx"]%>
很有用的,這樣可以在前臺頁面做好多事情了。
還要記住要這樣用必須要在前臺頁面導入名稱空間System.Data,否則會生成錯誤信息。
<%@ Import namespace="System.Data" %>
這種用法其實和<%# ((DictionaryEntry)Container.DataItem).Key%>是一個道理。
Text='<%# DataBinder.Eval(Container.DataItem, "字段") %>'
這樣的方法是最快的
Text='<%# GetPrice() %>'
也可以綁定方法,但方法要是public的
Text='<%# "CarDetails.aspx?CarID=" + DataBinder.Eval(Container.DataItem, "CarID") %>'
還可以連接多個字段
關鍵是Container這個東西,它比較神秘。它的名稱空間是System.ComponentModel。對於它我還需要進一步理解。
二、DataBinder.Eval實現判斷選擇
<asp:TemplateColumn HeaderText="性別">
<ItemTemplate>
<%# DGFormatSex(Convert.ToString(DataBinder.Eval(Container.DataItem,"xb"))) %>
</ItemTemplate>
</asp:TemplateColumn>
cs裏定義DGFormatSex方法
protected string DGFormatSex(string xb)
{
if(xb == "1")
return "男";
else
return "女";
}
DataBinder.Eval用法範例
//顯示二位小數
//<%# DataBinder.Eval(Container.DataItem, "UnitPrice", "${0:F2}") %>
//{0:G}代表顯示True或False
//<ItemTemplate>
// <asp:Image Width="12" Height="12" Border="0" runat="server"
// AlternateText='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "{0:G}") %>'
// ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "~/images/{0:G}.gif") %>' />
// </ItemTemplate>
//轉換類型
((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)
{0:d} 日期只顯示年月日
{0:yyyy-mm-dd} 按格式顯示年月日
{0:c} 貨幣樣式 

[ASP.NET]DataBinder.Eval用法

<%# Bind("Subject"%> //绑定字段
<%# Container.DataItemIndex + 1%> //实现自动编号
<%# DataBinder.Eval(Container.DataItem, "[n]"%>

通常使用的方法

<%# DataBinder.Eval(Container.DataItem, "ColumnName"%> 
<%# DataBinder.Eval(Container.DataItem, "ColumnName"null%> 
<%# DataBinder.Eval(Container, "DataItem.ColumnName"null%>

其他用法

<%# ((DataRowView)Container.DataItem)["ColumnName"%> 
<%# ((DataRowView)Container.DataItem).Row["ColumnName"%> 
<%# ((DataRowView)Container.DataItem)["adtitle"%> 
<%# ((DataRowView)Container.DataItem)[n] %> 
<%# ((DbDataRecord)Container.DataItem)[0%> 
<%# (((自定义类型)Container.DataItem)).属性.ToString() %>//如果属性为字符串类型就不用ToString()了

DataBinder.Eval用法范例

<%# DataBinder.Eval(Container.DataItem, "IntegerValue""{0:c}"%>
格式化字符串参数是可选的。如果忽略参数,DataBinder.Eval 返回对象类型的值,

//显示二位小数

<%# DataBinder.Eval(Container.DataItem, "UnitPrice""${0:F2}"%>
//{0:G}代表显示True或False
<ItemTemplate>
 
<asp:Image Width="12" Height="12" Border="0" runat="server"
 AlternateText
='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "{0:G}") %>'
 ImageUrl='
<%# DataBinder.Eval(Container.DataItem, "Discontinued""~/images/{0:G}.gif"%>' /></ItemTemplate>
//转换类型
((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)
{0:d} 日期只显示年月日
{0:yyyy-mm-dd} 按格式显示年月日
{0:c} 货币样式
<%#Container.DataItem("price","{0:¥#,##0.00}")%>
<%# DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>


Specifier Type     Format   Output (Passed Double 1.42)  Output (Passed Int -12400)
c  Currency        {0:c}     $1.42     -$12,400
d  Decimal         {0:d}    System.FormatException  -12400
e  Scientific      {0:e}    1.420000e+000    -1.240000e+004
f  Fixed point     {0:f}  1.42    -12400.00
g  General         {0:g}  1.42     -12400
n  Number with commas for thousands  {0:n}  1.42     -12,400
r  Round trippable    {0:r}  1.42     System.FormatException
x  Hexadecimal    {0:x4}  System.FormatException   cf90


{0:d} 日期只显示年月日
{0:yyyy-mm-dd} 按格式显示年月日


样式取决于 Web.config 中的设置

{0:c}  或 {0:£0,000.00} 货币样式  标准英国货币样式
<system.web>
      
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" uiCulture="en-US" />
</system.web>
显示为 £3,000.10

{0:c}  或 string.Format("{0:C}", price); 中国货币样式
<system.web>
      
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="zh-cn" uiCulture="zh-cn" />
</system.web>
显示为 ¥3,000.10

{0:c}  或 string.Format("{0:C}", price); 美国货币样式
<system.web>
      
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
显示为 $3,000.10



DataBinder.Eval(Container.DataItem,"Name")和Container.DataItem("Name")有什么区别?DataBinder是System.Web里面的一个静态类,它提供了Eval方法用于简化数据绑定表达式的编写,但是它使用的方式是通过Reflection等开销比较大的方法来达到易用性,因此其性能并不是最好的。而Container则根本不是任何一个静态的对象或方法,它是ASP.NET页面编译器在数据绑定事件处理程序内部声明的局部变量,其类型是可以进行数据绑定的控件的数据容器类型(如在Repeater内部的数据绑定容器叫RepeaterItem),在这些容器类中基本都有DataItem属性,因此你可以写Container.DataItem,这个属性返回的是你正在被绑定的数据源中的那个数据项。如果你的数据源是DataTable,则这个数据项的类型实际是DataRowView。





通常使用的方法(这三个性能最好)
<%# DataBinder.Eval(Container.DataItem, "ColumnName") %>
<%# DataBinder.Eval(Container.DataItem, "ColumnName", null) %>
<%# DataBinder.Eval(Container, "DataItem.ColumnName", null) %>
============
应该是最差的, 因为 DataBinder.Eval 内部使用反射
 


使用Eval()代替DataBinder.Eval()不是也可以实现同样的功能吗?