26 May 2011

C# - Format a file size

Here's how you can format a file size, specified in bytes, into a nice string for display:
public const string DECIMAL_FORMAT = "0.##";
public static string ToFormattedSize(int size) {
  float KB = 1024f;
  float MB = 1024f * KB;
  float GB = 1024f * MB;

  if (!size.HasValue)
    return "-";
  else if ((float)size.Value > GB)
    return ((float)size.Value / GB).ToString(DECIMAL_FORMAT) + " GB";
  else if ((float)size.Value > MB)
    return ((float)size.Value / MB).ToString(DECIMAL_FORMAT) + " MB";
  else if ((float)size.Value > KB)
    return ((float)size.Value / KB).ToString(DECIMAL_FORMAT) + " KB";
  else
    return ((float)size).Value.ToString(DECIMAL_FORMAT) + " B";
}

17 May 2011

C# - Encryption/decryption

I wrote these extensions to easily encrypt strings and later decrypt them again.

Keys

First the encryption will need these.
For each project I use them in, I change the keys a little.
private static readonly byte[] KEY = { 15, 85, 64, 52, 131, 86, 216, 44 };
private static readonly byte[] IV = { 5, 44, 19, 95, 129, 164, 9, 108 };

Encrypt

public static string Encrypt(this string source) {
  try {
    if (string.IsNullOrEmpty(source))
      return source;
    else {
      using (var des = new DESCryptoServiceProvider())
      using (var ms = new MemoryStream())
      using (var cs = new CryptoStream(ms, des.CreateEncryptor(KEY, IV), CryptoStreamMode.Write))
      using (var sw = new StreamWriter(cs))
      {
          sw.Write(source);
          sw.Flush();
          cs.FlushFinalBlock();
          sw.Flush();
          return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
      }
    }
  }
  catch {
    return string.Empty;
  }
}

Decrypt

public static string Decrypt(this string source) {
  try {
    if (string.IsNullOrEmpty(source))
      return source;
    else {
      using (var des = new DESCryptoServiceProvider())
      using (var ms = new MemoryStream(Convert.FromBase64String(source)))
      using (var cs = new CryptoStream(ms, des.CreateDecryptor(KEY, IV), CryptoStreamMode.Read))
      using (var sr = new StreamReader(cs))
      {
          return sr.ReadToEnd();
      }
    }
  }
  catch {
    return string.Empty;
  }
}

09 May 2011

C# - Parse JSON

Parsing JSON to strongly types objects is real easy in C#.
You just need to have the objects as they are represented in JSON, like these:

public class GridFilter {
  public string GroupOp { get; set; }
  public IEnumerable Rules { get; set; }
}

public class GridFilterRule {
  public string Field { get; set; }
  public string Op { get; set; }
  public string Data { get; set; }
}

Then all you need to do is this:

GridFilter filter = new JavaScriptSerializer().Deserialize(filters);

And your object structure will be created and filled from a JSON string.

Opera - High contrast on certain tabs

This is how in the Opera web browser you can have high contrast on some tabs and normal contrast on others. This is usefull - for me at least - to have white text on black on very light websites while still viewing other sites as normal.

To do this, you need the Appearance > Buttons > Browser view > User Mode button on the toolbar. Then:
  • Click the arrow next to this button and choose Manage Modes...,
  • Give both modes the same settings, but uncheck My style sheet for one of them,
  • In the mode that has the My style sheet setting, you can set the High Contrast option, in the other one you can't; so on a page in this mode set this option.
Now you can easily toggle between normal and high contrast by switching between author and user mode. This mode can be set per tab, so this way you can have normal and high contrast tabs in the same browser window.

05 May 2011

C# - Bitwise flags (bitmask)

Bitwise flags allow you to combine multiple flags into a single integer.
This really applies to many programming languages.
In C# you can do it like this:

The flags

The following defines the flags.
Notice how the value doubles - are powers of two - for each flag (binary system).
The flags attribute  indicates that bitwise operators will be performed on this enum.
[Flags]
public enum Role{
  AuxCreator = 1,
  AuxEditor  = 2,
  AuxDeletor = 4
}

Combine them

Getting the integer that combines some flags is easy using the bitwise or operator:
int roles = Role.AuxCreator | Role.AuxDeletor; //roles = 5

Check for flag set

Then, you can check whether a certain flag is set in the integer using the bitwise and operator as follows:
bool isAuxDeletor = (roles & Role.AuxDeletor) == Role.AuxDeletor; //isAuxDeletor = true

Unset a flag

To unset a flag from the bitmask, you can use the bitwise and operator again, with the inverse of the flag:
int roles = Role.AuxCreator & (~Role.AuxDeletor); //roles = 1