2012/11/29

Delete a specific DataRow from the DataTable

DataTable dt = BusinessLogic.GetTable(sqlCmd);
dt.Rows.Remove(dt.Select("ColumnName1 = '12345' and ColumnName2 = '67890'")[0]);
dt.AcceptChanges();

2012/11/07

Blog uses new SyntaxHighlighter

I changed to use the latest SyntaxHighlighter recently and found that it causes many posts unreadable. If you found any post that you want to read is unreadable, please leave a message here. I will fix it ASAP.

2012/10/08

WebClient.DownloadString()

I just want to check a web content has something I want or not, so I use the WebClient.DownloadString() instead of using HttpWebRequest, HttpWebResponse, StreamReader... etc.
using (WebClient wclient = new WebClient())
{
    wclient.Encoding = Encoding.UTF8;   // change to fit your environment
    string content = wclient.DownloadString(url);
    result = content.Contains(keyword);
}

2012/08/13

Add parameters in oledb and odbc CommandText

OleDb:
using (OleDbCommand cmd = new OleDbCommand())
{
  cmd.CommandText = "Select * from VIP where ID = ? And RegDate >= ?";
  cmd.Parameters.AddWithValue("id", id);
  cmd.Parameters.AddWithValue("regDate", regDate);
  using (OleDbDataReader reader = cmd.ExecuteReader())
  {
    // ..........
  }
}
Odbc:
using (OdbcCommand cmd = new OdbcCommand())
{
  cmd.CommandText = "Select * from VIP where ID = ? And RegDate >= ?";
  cmd.Parameters.Add("id", OdbcType.Int).Value = id;
  cmd.Parameters.Add("regDate", OdbcType.DateTime).Value = regDate;
  using (OdbcDataReader reader = cmd.ExecuteReader())
  {
    // ..........
  }
}

1. The name of parameter doesn't matter, but the order of parameter does.
2. I didn't include full codes here so don't forget to fill in other components like OleDbConnection or OdbcConnection.

2012/08/06

Trapping F9 in Winform

private void Form2_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.F9)
  {
    // your work here...
  }
}

1. Use the KeyDown event to trap it.
2. Set the Form's KeyPreview property to True.

2012/04/12

Force to show Exception in English

using System.Threading;
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

Reference: 如何強迫 .Net 應用程式輸出英文的例外訊息

2012/02/16

[C#] Android C2DM

internal static bool sendAndroidNotification(string message, string registrationID)
{
    const String ClientLoginURL = @"https://www.google.com/accounts/ClientLogin";
    const String C2DMServerURL = @"http://android.apis.google.com/c2dm/send";
    string collapseKey = DateTime.Now.ToShortDateString();

    String AuthTokenParams =
        @"accountType=GOOGLE&Email=" + Properties.Settings.Default.AndroidSenderEmail   // your sender email
        + "&Passwd=" + Properties.Settings.Default.AndroidSenderPassword    // your sender password
        + "&service=ac2dm";
    string authToken = getAndroidAuthToken(ClientLoginURL, AuthTokenParams);

    Dictionary<stringstring> data = new Dictionary<stringstring>();
    data.Add("data.msg"HttpUtility.UrlEncode(message));  // use UrlEncode() so that I can push messages other than English (like Chinese)

    return sendAndroidPushMessage(C2DMServerURL, registrationID, collapseKey, authToken, data);
}

2012/02/08

MSSQL get current datetime

SELECT CURRENT_TIMESTAMP
or
SELECT {fn NOW()}
or
SELECT GETDATE()

byte[] convert to hexadecimal string (and vice versa)

byte[] to hex string:
static string ByteArrayToString1(byte[] source)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte item in source)
    {
        sb.AppendFormat("{0:x2}", item);
    }
    return sb.ToString();
}

static string ByteArrayToString2(byte[] source)
{
    return BitConverter.ToString(source).Replace("-""");
}

static string ByteArrayToString3(byte[] source)
{
    // namespace: System.Runtime.Remoting.Metadata.W3cXsd2001
    return new SoapHexBinary(source).ToString();
}

static string ByteArrayToString4(byte[] source)
{
    // works for .Net 4 only
    return String.Concat(Array.ConvertAll(source, x => x.ToString("X2")));
}

Loop through enum

enum Week
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}
foreach (Week item in Enum.GetValues(typeof(Week)))
{
    //...
}

Reference: Can You Loop Through All Enum Values? c#

2012/01/17

IPv4 Address convert to Integer (and reverse) (updated)

static Int64 IPv4StringToInt64(string ipv4String)
{
    Int64 ipInteger = 0;
    try
    {
        ipInteger = (long)(uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipv4String).GetAddressBytes(), 0));
    }
    catch (Exception)
    { }

    return ipInteger;
}
static string IPv4Int64ToString(Int64 ipv4Int64)
{
    if (ipv4Int64 < 0)
        return "0.0.0.0";
    else if (ipv4Int64 < 4294967295)
        return IPAddress.Parse(ipv4Int64.ToString()).ToString();
    else
       return "255.255.255.255";
}
Usage:
Console.WriteLine("255.255.255.0 => " + IPv4StringToInt64("255.255.255.0"));
Console.WriteLine("4294967040 => " + IPv4Int64ToString(4294967040));

Reference: stackoverflow - How to convert an IPv4 address into a integer in C#?