站內文章

顯示具有 C#-基本 標籤的文章。 顯示所有文章
顯示具有 C#-基本 標籤的文章。 顯示所有文章

2014年11月27日 星期四

System.Text.Encoding.Default 產生亂碼


最近在處理簽章遇到了這個問題,產生的簽章格式是bytearray,想轉成string
一開始用了 string str = System.Text.Encoding.Default.GetString ( byteArray );
結果發現產生的string是亂碼,後來用下面這個方式解決
ByteArrayToHexString


    private string ByteArrayToHexString(byte[] data)
    {
        StringBuilder sb = new StringBuilder(data.Length * 3);
        foreach (byte b in data)
            sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
        return sb.ToString().ToUpper();
    }

2014年11月26日 星期三

String直接換成Bytes


string 長怎樣,轉過去bytes就怎樣
限制string長度必須為偶數

    protected byte[] StringToBytes(string HexString)
    {
        int byteLength = HexString.Length / 2;
        byte[] bytes = new byte[byteLength];
        string hex;
        int j = 0;
        for (int i = 0; i < bytes.Length; i++)
        {
            hex = new String(new Char[] { HexString[j], HexString[j + 1] });
            bytes[i] = HexToByte(hex);
            j = j + 2;
        }
        return bytes;
    }

    private byte HexToByte(string hex)
    {
        if (hex.Length > 2 || hex.Length <= 0)
            throw new ArgumentException("hex must be 1 or 2 characters in length");
        byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
        return newByte;
    }

2014年11月19日 星期三

SQL Count 計算資料庫內特定資料的筆數


這邊提供的方法是利用ExecuteScalar指令取出執行完SqlCommand的值

// ExecuteScalar:
// 執行查詢,並傳回查詢所傳回的結果集第一個資料列的第一個資料行。 會忽略其他的資料行或資料列。
// 關於ExecuteScalar 更多的說明 http://goo.gl/xtV64S
    using (SqlCommand cmd = new SqlCommand("SELECT COUNT(Import_Date) FROM ComparisonData WHERE Import_Date='" + time1 + "'", SqlConn)) // 看ComparisonData內有幾組相同的Import_Date
    {
        string time2 = Convert.ToDateTime(saveNow).ToString("yyyyMMdd");
        Lot_Number = "P" + time2 + (Convert.ToInt16(cmd.ExecuteScalar()) + 1).ToString("d4"); //批次號碼 - P+8碼西元年月日+4碼流水編號
    }

2014年11月14日 星期五

比較時間差異

這邊提供三個方式
1. 比較時間前後 使用 DateTime.Compare
// 參考來源 http://goo.gl/Ay5hAE
using System;

public class Example
{
   public static void Main()
   {
      DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
      DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
      int result = DateTime.Compare(date1, date2);
      string relationship;

      if (result < 0)
         relationship = "is earlier than";
      else if (result == 0)
         relationship = "is the same time as";         
      else
         relationship = "is later than";

      Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
   }
}
// The example displays the following output: 
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM



2. 比較時間差異 使用 SQL語法
// http://goo.gl/nTQX3D 每日一SQL-善用DATEADD和DATEDIFF
// http://goo.gl/PrB0JC 如何用簡單的 SQL 技巧取得特定日期是否為週末假日

SELECT DATEDIFF(DAY, '2010-10-03','2010-10-04'  )
// 出來的結果就是 1,代表相隔一天。



2. 比較時間差異 使用 TimeSpan
    DateTime ts1 = Convert.ToDateTime(sqlDDT.Rows[0][1].ToString()); // 取得datatable欄位資料並轉時間格式
    DateTime ts2 = DateTime.Now; // 抓取現在時間
    Double ts = new TimeSpan(ts2.Ticks - ts1.Ticks).TotalSeconds;
    if (ts >= 60)// 判斷時間差異 時間差大於60秒 則執行
    {
       // do
    }
// 關於 TimeSpan 的屬性使用可以參考
// http://goo.gl/NqvtYy
// Hours 與 TotalHours 是有差別的(前者是只有比較Hours後者則是算整個的時間差-會包含日的換算)

2014年10月27日 星期一

連接資料庫並新增資料表及填入資料



                // 設定資料庫路徑
                string path = @"C:\Documents and Settings\lict\My Documents\WindowsCE My Documents\FixRepair.sdf";
                string constrpda = "DataSource=" + path;
                // 連接資料庫
                using (SqlCeConnection conn = new SqlCeConnection(constrpda))
                {
                    conn.Open();
                    // 建立資料表 ComparisonDataPDA 欄位 Total(存放原先資料庫裡應有的數量) ; Type (設備種類) ; Lot_Number (批次號碼)
                    using (SqlCeCommand Cmd = new SqlCeCommand("CREATE TABLE ComparisonDataPDA(Total nvarchar(20),Type nvarchar(20),Lot_Number nvarchar(50))", conn))
                    {
                        Cmd.ExecuteNonQuery();
                        Cmd.Dispose();
                        // 將設備數量、設備種類、批次號碼 寫進資料庫
                        using (SqlCeCommand adcmd = new SqlCeCommand("Insert into ComparisonDataPDA(Total,Type,Lot_Number) values('20','0','P20141012001')", conn))
                        {
                            adcmd.ExecuteNonQuery();
                            adcmd.Dispose();
                        }
                    }
                }

2014年10月16日 星期四

datatable 與 gridview 抓值差異

// gridview1和 datatable 抓值有些許的差異
// 差在gridview在判斷column時需要用.cell抓

GridView1.Rows[0].Cells[1].ToString() // giidview 抓值
datatable1.Rows[0][1].ToString() // datatable 抓值

2014年10月15日 星期三

判斷Gridview中的值是否為空

判斷row的時候可以用 .count 要判斷Gridview中某值是否為空可以用這個方式
//判斷Girdview Cell 值為空
GridView1.SelectedRow.Cells[2].Text.ToString() == " "

去除空白字元 Replace、Trim

//去除字串裡面的空白(或任意)字元用 replace 去除 
GridView1.Rows[i].Cells[5].Text.ToString().Replace(" ","")
GridView1.Rows[i].Cells[5].Text.ToString().Replace("hollo","hello") // hollo -> hello

//去除字串前後空白 Trim
GridView1.Rows[i].Cells[5].Text.ToString().Trim()

在datatable 中 新增新的Column

DataColumn column1 = new DataColumn("Row");  // 在datatable dt1 中 新增欄位存放項目編號
column1.DefaultValue = Session["fixsearch2_item_num"].ToString(); // 給值
dt1.Columns.Add(column1);

Session的使用 建立 取值 移除

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

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

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

C#連接資料庫進行 查詢、新增、修改、刪除

SqlConnection SqlConn;

// 資料表名稱 ImportSwitch
// 資料欄qqq qqqq

SqlConn.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\VS20141001\\App_Data\\TPC_Transformers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlConn = new SqlConnection(ConnStr);
SqlConn.Open();

//查詢並填入DataTable
DataTable dt = New DataTable();
SqlDataAdapter da;
da = new SqlDataAdapter("Select * From ImportSwitch", SqlConn);
da.Fill(dt);

//進行資料新增 資料欄 qqq 新增1  qqqq新增2
SqlCommand Cmd;
Cmd = New SqlCommand("Insert into ImportSwitch(qqq,qqqq) values('1','2')", SqlConn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();

//進行資料修改 qqq修改為1
Cmd = New SqlCommand("Update ImportSwitch Set qqq = '1'", SqlConn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();


//進行資料刪除
Cmd = New SqlCommand("Delete From ImportSwitch where qqq = '1'", SqlConn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();


SqlConn.close();