When you’ve been working heavily with c# for a few days, coalesce jumps into your head for a lot of c# issues. Heres a little helper to provide coalesce in .net
/// <summary>
/// Returns the first non null value, same as SQL's COALESCE()
/// </summary>
/// <param name="p">Args array</param>
/// <returns>First non null value</returns>
public static String Coalesce(params object[] p)
{
foreach (Object o in p)
{
if (o != DBNull.Value && o != null)
{
return o.ToString();
}
}
return "";
}
I had a requirement for a series of select boxes that required the related one to only allow selections above the first. I created a little utility function that enables and disables the options based on a function you supply. Usage is pretty simple. Pass in the first and second select as jQuery objects, then pass in your function that evaluates whether an option is enabled or not.
Read more…
Utility to take a number and convert it to the english text. Not mine this one but lost the original url! If it’s yours let me know
public class NumberToWords
{
// Single-digit and small number names
private string[] _smallNumbers = new string[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
<a href="http://www.fruitbatscode.com/net/c/uad-9-numbers-to-words#more-454" class="more-link">Read more...</a>
Ever had controls that need to add to the Query String but not duplicate or erase what’s already there? This is a little utility I dug out and just changed to use a generic dictionary recently. Just use it as you would a normal dictionary. When you instantiate a copy it picks up the current query string. There are two ToString() methods, one just return the query string and the other appends another string to the end and takes care of the ? & issues.
Read more…
When processing sortables etc. Its handy to be able to get the index of individual items. Heres how you find the position of an li within a list:
var position = $item.parent().find('> li').index($item) + 1;
Okay, so Util-a-day was a bit optimistic! Here’s the next one, simple function to convert a file size in a user friendly description. It converts the size to the nearest kb, mb or gb.
public static String ConvertBytes(double bytes){
String FORMAT = "{0:N2}";
if (bytes > 1073741824)
return String.Format(FORMAT, (bytes / 1024 / 1024 / 1024)) + " GB";
else if (bytes > 1048576)
return String.Format(FORMAT, (bytes / 1024 / 1024)) + " MB";
else if (bytes >= 1024)
return String.Format(FORMAT, (bytes / 1024)) + " KB";
else
return bytes + " Bytes";
}