顯示具有 [ASP.NET][C#] 標籤的文章。 顯示所有文章
顯示具有 [ASP.NET][C#] 標籤的文章。 顯示所有文章

2015年9月1日 星期二

[ASP.NET] 讓 Textbox 按 ENTER 時 postback 失效

So here is the neat and simple trick that does it. And the textbox below is the one that does not do a postback when enter key is pressed inside it
<asp:TextBox ID="TextBox1" runat="server"
   onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>

As you will notice above I wrote a simple condition on onkeydown event.
(event.keyCode!=13);
When enter key is pressed the above condition is false hence false is returned this the postback is disabled.
Note that Visual Studio will give a warning when you add onkeydown event and underline it with green.
It is just a warning and one can ignore that since Visual Studio searched for Server Side events and onkeydown is not in the list. Hence still it will work
But for those who do not want that warning can add this event from code behind

C#
TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);");

VB.Net
TextBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")

The above line will add the onkeydown event to the textbox. Make sure you add these lines to page load.

In order to disable the enter key form submission on all controls simply add it to the body tag in the following way
<body onkeydown = "return (event.keyCode!=13)">

2013年7月31日 星期三

[C#] String常用技巧整理(IndexOf、LastIndexOf、Substring、Split)


String.IndexOf

String.IndexOf 方法 (Char, Int32, Int32)
報告指定字符在此範例中的第一個匹配項的索引。搜索從指定字符位置開始,並檢查指定數量的字符位置。
String.IndexOf(value, startIndex, count)

參數
value:要查找的 Unicode 字符。
startIndex:搜索起始位置。
count:要檢查的字符位置數。
返回值(Int32):
如果找到該字符,則為value 的索引位置;否則如果未找到,則為-1。

範例:
string str = "深圳市盈基實業有限公司國際通鄧事文*深圳市盈基實業有限公司國際通鄧事文";
Label1.Text = str.IndexOf("中國").ToString();//返回-1
Label1.Text = str.IndexOf("盈基").ToString();//返回3
Label1.Text = str.IndexOf("盈基",10).ToString();//返回21 說明:這是從第10個字符開始查起。
Label1.Text = str.IndexOf("鄧",15,10).ToString();//返回-1
Label1.Text = str.IndexOf("鄧",15,20).ToString();//返回-32 說明:從第15個字符開始查找,
要查找的範圍是從第15個字符開始後20個字符,即從第15-35個字符中查找。

<---------------------------------------------------------------------------------------------------------->

String.LastIndexOf

String.LastIndexOf 方法
報告指定的Unicode 字符或String 在此實例中的最後一個匹配項的索引位置。


名稱 說明
String.LastIndexOf (Char)報告指定Unicode 字符在此實​​例中的最後一個匹配項的索引位置。
String.LastIndexOf (String)報告指定的String 在此實例內的最後一個匹配項的索引位置。
String.LastIndexOf (Char, Int32)報告指定Unicode 字符在此實​​例中的最後一個匹配項的索引位置。該搜索從指定字符位置開始。
String.LastIndexOf (String, Int32)報告指定的String 在此實例內的最後一個匹配項的索引位置。該搜索從指定字符位置開始。
String.LastIndexOf (String, StringComparison)報告指定字符串在當前String 對像中最後一個匹配項的索引。一個參數指定要用於指定字符串的搜索類型。
String.LastIndexOf (Char, Int32, Int32)報告指定的Unicode 字符在此實​​例內的子字符串中的最後一個匹配項的索引位置。搜索從指定字符位置開始,並檢查指定數量的字符位置。
String.LastIndexOf (String, Int32, Int32)報告指定的String 在此實例內的最後一個匹配項的索引位置。搜索從指定字符位置開始,並檢查指定數量的字符位置。
String.LastIndexOf (String, Int32, StringComparison)報告指定字符串在當前String 對像中最後一個匹配項的索引。參數指定當前字符串中的起始搜索位置,以及要用於指定字符串的搜索類型。
String.LastIndexOf (String, Int32, Int32, 
StringComparison)
報告指定的String 對像在此實例內的最後一個匹配項的索引位置。參數指定當前字符串中的起始搜索位置、要搜索的當前字符串中的字符數量,以及要用於指定字符串的搜索類型。



範例:
string str = "深圳市盈基實業有限公司國際通鄧事文*深圳市盈基實業有限公司國際通鄧事文";
Label1.Text = str.LastIndexOf("鄧文").ToString();//返回-1
Label1.Text = str.LastIndexOf("鄧").ToString();//返回32

Label1.Text = str.LastIndexOf("鄧",8).ToString();//返回-1
Label1.Text = str.LastIndexOf("鄧",20).ToString();//返回14
Label1.Text = str.LastIndexOf("鄧",33).ToString();//返回32
說明:在指定的範圍內查找字符,這個範圍是上面的輸入的參數,
理解為,從索引0開始到指定的數值位置範圍內查找最後一個匹配的的字符串的位置。示例中,0-8中沒有“鄧”字,
所以返回-1,0-20範圍中,有一個“鄧”字在索引14位置上,0-33範圍中有兩個“鄧”字,
因為LastIndexOf是返回最後一個匹配項索引位置,所以返32,而不是14。

PS : IndexOf、LastIndexOf都是返回一個位置,是個整數值;找不到都返回-1;
IndexOf是從左向右查,LastIndexOf是從右向左查,不管是IndexOf還是LastIndexOf,
索引序列都是從左到右的(起始值是0)
<---------------------------------------------------------------------------------------------------------->
String.Substring

String.Substring 方法
從此實例檢索子字符串。
名稱 說明
String.Substring (Int32) 從此實例檢索子字符串。子字符串從指定的字符位置開始。
String.Substring (Int32, Int32) 從此實例檢索子字符串。子字符串從指定的字符位置開始且具有指定的長度。

示例:
string str = "深圳市盈基實業有限公司國際通鄧事文*深圳市盈基實業有限公司國際通鄧事文";
Label1.Text = str.Substring(11);//返回“國際通鄧事文*深圳市盈基實業有限公司國際通鄧事文”
Label1.Text = str.Substring(11,7);//返回“國際通鄧事文*”

<---------------------------------------------------------------------------------------------------------->

String.Split



1,用字符串分隔:


using System.Text.RegularExpressions;

string str="aaajsbbbjsccc";

string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);

foreach (string i in sArray) Response.Write(i.ToString() + "<br>");


輸出結果:
aaa
bbb
ccc

2,用多個字符來分隔:


string str="aaajbbbscccjdddseee";

string[] sArray=str.Split(new char[2]{'j','s'});

foreach(string i in sArray) Response.Write(i.ToString() + "<br>");


輸出結果:
aaa
bbb
ccc
ddd
eee

3,用單個字符來分隔:

字符串str=“aaajbbbjccc”;

字符串[] sArray= str.Split(“J”);

的foreach(字符串sArray我)回复於(i.ToString()+“ - ”);

輸出結果:
aaa
bbb
ccc

轉自:http://a-jau.blogspot.tw/2012/01/cstringindexoflastindexofsubstringsplit.html

2012年6月20日 星期三

[Javascript][ASP.NET]Javascript編碼,解碼。ASP.NET(C#)對應之編碼,解碼


escape不編碼字符有69個:*,+,-,.,/,@,_,0-9,a-z,A-Z
encodeURI不編碼字符有82個:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent不編碼字符有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z
1.
JS: escape :
js使用數據時可以使用escape
例如:搜藏中history紀錄。
0-255以外的unicode值進行編碼時輸出%u****格式,其它情况下escape,encodeURI,encodeURIComponent編碼結果相同。
解碼使用:unescape
C#:
HttpUtility.UrlEncode 
HttpUtility.UrlDecode

2.
JS: encodeURI :
進行url跳轉時可以整體使用encodeURI
例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
解碼使用decodeURI();
C#: decodeURIComponent

3.
JS: encodeURIComponent :
傳遞參數時需要使用encodeURIComponent,這樣組合的url才不會被#等特殊字符截斷。 
例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7& u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a& gt;');</script>
解碼使用decodeURIComponent()
C#:
[HttpContext.Current.]Server.UrlDecode

[HttpContext.Current.]Server.UrlEncode

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()不是也可以实现同样的功能吗?

2011年12月27日 星期二

[ADO.NET] UPDATE - C#

string updatesql = "Update t_member Set ...........//你的sql語法

string connStr="server=xxxxxxx; uid=sa; password=xxxxxxx; initial catalog=xxxxxxx;" ;<--你的連線

SqlConnection oCn = new SqlConnection(connStr);
SqlCommand Comm = new SqlCommand(updatesql,oCn);
Comm.Connection.Open();
Comm.ExecuteNonQuery();
Comm.Connection.Close();

2011年12月26日 星期一

[asp.net] showModalDialog

asp:Button ID="btn_select" runat="server" Text="選擇權限/新增群組"
onclick="btnSelect_Click" Width="133px" OnClientClick="showModalDialog('select_group.aspx',window,'dialogWidth:400px; dialogHeight:300px; center:yes; status:0;')" />

2011年12月22日 星期四

[asp.net] [c#] session使用方法

//建立
Session.Add("sessionName", "123");
//or
Session["sessionName"] = "123";

//取值
string s = Session["sessionName"].ToString();

//移除
Session.Remove("sessionName");

2011年12月9日 星期五

[C#] 使用Split分割用多字串分隔的字串

//string 版
string ss = "sasa, test01, test02, admin, jimmy, jack, benson, ";
string[] splitResult = ss.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0;i < splitResult.Length; i++)

//char 版
string ss = "sasa, test01, test02, admin, jimmy, jack, benson, ";
string[] splitResult = ss.Split(new char[] { ',' });

2011年12月6日 星期二

[ASP.NET] DateTime Formating

此文章為有關DateTime <-> String的來回轉換                                                                                                                                    
搭配TimeSpan 即可計算時間差                                                                                                                           

1private string DateDiff(DateTime DateTime1, DateTime DateTime2)
2 {
3string dateDiff = null;
4 TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
5 TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
6 TimeSpan ts = ts1.Subtract(ts2).Duration();
7 dateDiff = ts.Days.ToString()+"天"+ ts.Hours.ToString()+"小時"+ ts.Minutes.ToString()+"分鐘"  + ts.Seconds.ToString()+"秒";
8 return dateDiff;
9 }
說明:
1.DateTime值類型代表了一個從公元0001年1月1日0點0分0秒到公元9999年12月31日23點59分59秒之間的具體體日期時刻。  
因此,你可以用DateTime值類型來描述任何在想像範圍之內的時間。一個DateTime值代表了一個具體的時刻                    
2.TimeSpan值包含了許多屬性與方法,用於訪問或處理一個TimeSpan值                                                                    
下面的列表涵蓋了其中的一部分:                                                 
                                                                       
Add:與另一個TimeSpan值相加。
                                                                                                                                    
Days:返回用天數計算的TimeSpan值。
                                                                                                                                    
Duration:獲取TimeSpan的絕對值。
                                                                                                                                    
Hours:返回用小時計算的TimeSpan值
                                                                                                                                    
Milliseconds:返回用毫秒計算的TimeSpan值。
                                                                                                                                    
Minutes:返回用分鐘計算的TimeSpan值。
                                                                                                                                    
Negate:返回當前實例的相反數。
                                                                                                                                    
Seconds:返回用秒計算的TimeSpan值。                                                                                                                      
Subtract:從中減去另一個TimeSpan值。                                                                                                                      
Ticks:返回TimeSpan值的tick數。                                                                                                                                                
TotalDays:返回TimeSpan值表示的天數。
                                                                                                                        
TotalHours:返回TimeSpan值表示的小時數。
                                                                                                                      
TotalMilliseconds:返回TimeSpan值表示的毫秒數。                                                                                                 
TotalMinutes:返回TimeSpan值表示的分鐘數。
                                                                                                               
TotalSeconds:返回TimeSpan值表示的秒數。
                                                                                                            
關於格式化處理 可再參考以下