2012年2月29日 星期三

javascript Hex to Decimal and Decimal to Hex

function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}

javascript string to Hex

ActionScript Code:
function encodeToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}
function decodeFromHex(str){
 var r="";
 var e=str.length;
 var s=0;
 while(e>1){

 r=r+String.fromCharCode("0x"+str.substring(s,s+2));
 s=s+2;
 e=e-2;
 }

return r;
}

str = "hello";
trace("Original: "+str);
str = encodeToHex(str);
trace("Encode: "+str);
str = decodeFromHex(str);
trace("Decode: "+str);
output Code:
Original: hello
Encode: 06806506c06c06f
Decode: hello

php 取得網址與目錄

在PHP裡如果想要取得目前的網址資訊,不論是網域、目錄路徑或是參數,可以透過交叉使用下面的方法來達成目的。
$_SERVER['HTTP_HOST'] // 取得網域
$_SERVER['REQUEST_URI'] // 取得網域內的完整路徑及參數
$_SERVER['PHP_SELF'] // 取得網域內的完整路徑,但不含參數
$_SERVER['QUERY_STRING'] // 只取得參數

c# Hex and Dec

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
/* Output:
   Hexadecimal value of H is 48
    Hexadecimal value of e is 65
    Hexadecimal value of l is 6C
    Hexadecimal value of l is 6C
    Hexadecimal value of o is 6F
    Hexadecimal value of   is 20
    Hexadecimal value of W is 57
    Hexadecimal value of o is 6F
    Hexadecimal value of r is 72
    Hexadecimal value of l is 6C
    Hexadecimal value of d is 64
    Hexadecimal value of ! is 21
*/


string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');foreach (String hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer.
    int value = Convert.ToInt32(hex, 16);    // Get the character corresponding to the integral value.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}
/* Output:
    hexadecimal value = 48, int value = 72, char value = H or H
    hexadecimal value = 65, int value = 101, char value = e or e
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 20, int value = 32, char value =   or
    hexadecimal value = 57, int value = 87, char value = W or W
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 72, int value = 114, char value = r or r
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 64, int value = 100, char value = d or d
    hexadecimal value = 21, int value = 33, char value = ! or !
*/



http://msdn.microsoft.com/zh-tw/library/bb311038.aspx

2012年2月28日 星期二

c# DataSet与DataTable的区别

DataSet:数据集。一般包含多个DataTable,用的时候,dataset["表名"]得到DataTable  
  DataTable:数据表。  
  一:  
  SqlDataAdapter   da=new   SqlDataAdapter(cmd);  
  DataTable   dt=new   DataTable();  
  da.Fill(dt);  
  -----------------  
  直接把数据结果放到datatable中,  
  二:  
  SqlDataAdapter   da=new   SqlDataAdapter(cmd);  
  DataSet   dt=new   DataSet();  
  da.Fill(dt);  
  ----------------  
  数据结果放到dataset中,若要用那个datatable,可以这样:dataset[0]  
  更常见的用法:  
  SqlDataAdapter   da=new   SqlDataAdapter(cmd);  
  DataSet   dt=new   DataSet();  
  da.Fill(dt,"table1");  
  用的时候:这样取datatable:  
  dataset["table1"]  

C# Get / Post 取得網頁資料流

實作網頁資料擷取函式。

        ///
        /// 取得需求位址的response串流(GET)
        ///
        /// 傳回需求位址的串流
        public Stream GetHttpStream(string url,string refererUrl)
        {
            // 使用 WebRequestFactory 建立要求。
            this.wreqScrape = (HttpWebRequest)(WebRequest.Create(url));
            this.wreqScrape.CookieContainer = this.cookieContainer;             //this.wreqScrape.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)";
            this.wreqScrape.UserAgent = this.userAgentsSet[this.rn.Next(0,7)];
            this.wreqScrape.Method = "GET";
            this.wreqScrape.Timeout = 50000;
            if(refererUrl != "")
               this.wreqScrape.Referer = refererUrl;
            try
            {
                // 傳回回應資料流。
                this.wresScrape = (HttpWebResponse)(this.wreqScrape.GetResponse());
                return this.wresScrape.GetResponseStream();
            }
            catch (Exception ex)
            {
                throw new Exception("在提取您所要求的" + url + "網頁時發生錯誤。" +
              "請檢查您所鍵入的 URL 以及 Internet 連線,並再次嘗試。WebException:" + ex.Message);
                //throw new Exception(ex.Message);
                //失敗就丟出空stream
                //return null;
            }
        }
        ///
        /// 取得需求位址的response串流(POST)
        ///
        /// 傳回需求位址的串流
        public Stream PostHttpStream(string url,string refererUrl,string postData)
        {
            // 使用 WebRequestFactory 建立要求。
            this.wreqScrape = (HttpWebRequest)(WebRequest.Create(url));
            this.wreqScrape.CookieContainer = this.cookieContainer;             //this.wreqScrape.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)";
            this.wreqScrape.UserAgent = this.userAgentsSet[this.rn.Next(0, 7)];
            this.wreqScrape.Method = "POST";
            this.wreqScrape.Timeout = 50000;
            this.wreqScrape.ContentType = "application/x-www-form-urlencoded";
            if (refererUrl != "")
                this.wreqScrape.Referer = refererUrl;
            //這樣設會讓post data 產生 error
            //this.wreqScrape.ContentLength = postData.Length;
            try
            {
                //使用utf-8編碼
                UTF8Encoding encoding = new UTF8Encoding();
                //將post data 轉成 bytes
                byte[] bytes = encoding.GetBytes(postData);
                //在擷取資料流之前,必須先設定 ContentLength 屬性的值
                // Set the content length of the string being posted
                this.wreqScrape.ContentLength = bytes.Length;
                //HttpWebRequest.GetRequestStream - 方法傳回用來傳送資料給 HttpWebRequest 的資料流。
                //傳回 Stream 物件之後,您可以使用 Stream.Write 方法以 HttpWebRequest 傳送資料。
                //post data to server亦即傳送資料
                using (Stream writeStream = this.wreqScrape.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
                // 傳回回應資料流。
                this.wresScrape = (HttpWebResponse)(this.wreqScrape.GetResponse());
                //this.wresScrape.Cookies = this.cookieContainer.GetCookies(this.wreqScrape.RequestUri);
                //foreach (Cookie cookie in this.wresScrape.Cookies)
                //{
  
                //}
                return this.wresScrape.GetResponseStream();
            }
            catch (WebException ex)
            {
                throw new Exception("在提取您所要求的" + url + "網頁時發生錯誤。" +
                "請檢查您所鍵入的 URL 以及 Internet 連線,並再次嘗試。WebException:" + ex.Message);
                //throw new Exception(ex.Message);
                //失敗就丟出空stream
                //return null;
            }           
        }

        ///
        /// 可將回傳的stream轉換為字串(逐行重組)
        ///
        /// esponse重組字串
        public string StreamConvertToRecombineString(Stream stmSource,Encoding encodeType)
        {
            if (stmSource != null)
            {
                try
                {
                    using (StreamReader sr = new StreamReader(stmSource,encodeType))
                    {
                     
                        try
                        {
                            string temp = "";
                            //while ((temp = sr.ReadLine().ToLower().Trim()) != "") 
                            //當不是網頁結尾的話就讀取
                            while ((temp = sr.ReadLine()).Trim().IndexOf("") == -1)
                            {
                                if (temp != "")
                                {
                                    if (temp.IndexOf("\t") >= 0)
                                    {
                                        temp = temp.Replace("\t", "").Trim();
                                        this.sbReturnHTML.Append(temp);
                                    }
                                    else
                                    {
                                        temp = temp.Trim();
                                        this.sbReturnHTML.Append(temp);
                                    }
                                }
                            }                             this.sbReturnHTML.Append("");
                            //置換全形數字,如12345,轉換為12345,可不加
                            StringTool.BigNumberConvertToSmaillNumber(ref sbReturnHTML);
                            return  sbReturnHTML.ToString() ;
                        }
                        catch
                        {
                            return sbReturnHTML.ToString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception();
                }
                finally
                {
                    this.sbReturnHTML.Remove(0, this.sbReturnHTML.Length);
                    this.wresScrape.Close();
                }
            }
            else
            {
                return "";
            }
        }

c# HTTP Post

using System.Net;
...
string HttpPost (string uri, string parameters)
{ 
   // parameters: name1=value1&name2=value2 
   WebRequest webRequest = WebRequest.Create (uri);
   //string ProxyString = 
   //   System.Configuration.ConfigurationManager.AppSettings
   //   [GetConfigKey("proxy")];
   //webRequest.Proxy = new WebProxy (ProxyString, true);
   //Commenting out above required change to App.Config
   webRequest.ContentType = "application/x-www-form-urlencoded";
   webRequest.Method = "POST";
   byte[] bytes = Encoding.ASCII.GetBytes (parameters);
   Stream os = null;
   try
   { // send the Post
      webRequest.ContentLength = bytes.Length;   //Count bytes to send
      os = webRequest.GetRequestStream();
      os.Write (bytes, 0, bytes.Length);         //Send it
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Request error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   finally
   {
      if (os != null)
      {
         os.Close();
      }
   }
 
   try
   { // get the response
      WebResponse webResponse = webRequest.GetResponse();
      if (webResponse == null) 
         { return null; }
      StreamReader sr = new StreamReader (webResponse.GetResponseStream());
      return sr.ReadToEnd ().Trim ();
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Response error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   return null;
} // end HttpPost 

c# datatable to json

public string GetAllCategory()  
{       
    string result = "";   
    DataTable dt= catDAO.GetAllCategory();  
    result=JsonConvert.SerializeObject(dt, new DataTableConverter());   
    return result;   

c#在Data Table是中出現的特定類型

新增:
            DataTable dataTble = new DataTable();

加入欄位:
            DataTable dataTble = new DataTable();

刪除欄位:
            DataTble .Rows[dataTableNum].Delete();

經由Data Row加入:
            DataRow workRow = dataTble .NewRow();
            workRow["RowName"] ="Sample" ;
            workRow["RowData"] = 1;
            dtDate.Rows.Add(workRow);


直接由SQL加入:
            sqlCon = new SqlConnection(strCon);
            sqlCom = new SqlCommand();
            sqlCom.Connection = sqlCon;
            sqlCom.CommandText = "select_v";
            sqlCom.CommandType = CommandType.StoredProcedure;
            sqlCon.Open();
            sdr = sqlCom.ExecuteReader();
            dt = new DataTable();
            dataTble .Load(sdr);


整列複製:
            DataTable dt2 = new DataTable();
            dt2 = dataTble .Copy();//複製
            dt2.Rows.Clear();
            dt2.ImportRow(dataTble .Rows[0]);//加入第一行

簡單排序:
            DataView dvTemp = dataTble .DefaultView;
            dvTemp.Sort = "RowData, RowName ";
            dvTemp.Sort = "RowData  DESC, RowName  DESC ";//倒排序
            dataTble = dvTemp.ToTable();

設定單一主鍵:
dt.PrimaryKey = new DataColumn[] { dt.Columns["RowName"] };

設定多主鍵:
dt.PrimaryKey = new DataColumn[] { dt.Columns["RowName"], dt.Columns["RowData"] };


搜尋單一條件:
DataRow dr = dt.Rows.Find("條件");


搜尋多條件:
object[] search = new object[] { "條件1", "條件2" };
DataRow dr = dt.Rows.Find(search);

修改搜尋條件內的某個欄位的資料:
dt.Rows.Find("條件").SetField("RowName","要更新的資料"); 

Data Grid View內容轉為Data Table:

        public DataTable DataGridView_To_DataTable(DataGridView dataGridView)
        {
            DataTable dt = new DataTable();
            DataColumn dc;
            for (int i = 0; i < dataGridView.Columns.Count; i++)
            {
                dc = new DataColumn();
                dc.ColumnName = dataGridView.Columns[i].Name.ToString();
                dt.Columns.Add(dc);
            }

            for (int j = 0; j < dataGridView.Rows.Count - 1; j++)
            {
                DataRow dr = dt.NewRow();
                for (int k = 0; k < dataGridView.Columns.Count; k++)
                {
                    dr[k] = dataGridView.Rows[j].Cells[k].Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

2012年2月23日 星期四

Transform between Hex and Dec in Javascript

var hexChars = "0123456789ABCDEF";

function Dec2Hex (dec) {
    
var a = dec % 16;
    
var b = (dec - a)/16;
    
var hex = "" + hexChars.charAt(b) + hexChars.charAt(a);
    
return hex;
}


function Hex2Dec(hex) {
    
return parseInt(hex,16);
}

2012年2月17日 星期五

C# panel 控件 背景 位置 设置

Microsoft Visual C# 2008 Express Edition
WinForm
其他控件的背景图片也可以这样设置
背景图片重复:BackgroundImageLayout属性设置为Tile(默认)
背景图片左边显示:BackgroundImageLayout属性设置为None
背景图片右边显示:BackgroundImageLayout属性设置为None,同时RightToLeft属性设置为Yes
背景图片居中显示:BackgroundImageLayout属性设置为Center
背景图片拉申:BackgroundImageLayout属性设置为Stretch
背景图片按比例放大到合适大小:BackgroundImageLayout属性设置为Zoom