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#