More C# Extenders

Cool article today over at http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc about extenders. If you didn’t already know, extenders are static methods that work off the end of objects like special little hangars on. They are like little upgrades you get in a video game — like double jump in Shadow Complex.

Since I loved the article so much I figured I would add some of my collection to the list. I cannot take credit for all of these, as I have collected them over a long time — I might have written half of them.

DateTime

//The w3c string format is used for RSS feeds.
public static string ToW3CString(this DateTime ThisDate)
{
    //Return the datetime in the W3C standard format
    return String.Format("{0:yyyy-MM-ddTHH:mm:ss.fffzzz}", ThisDate);
}

public static DateTime FirstDayOfWeek(this DateTime dt) {
	int diff = dt.DayOfWeek - DayOfWeek.Sunday; 
	if (diff < 0) 
	{ 
			diff += 7; 
	} 
	return dt.AddDays(-1 * diff).Date;
}

public static DateTime LastDayOfWeek(this DateTime dt) {
	return dt.FirstDayOfWeek().AddDays(6);
}

Simple first and last day of week for a specific date. Like, for February 11, 2010 the first day of the week was the 7th.

DataTable

		
public static bool HasColumn(this IDataRecord dr, string columnName)
{	
	for (int i=0; i < dr.FieldCount; i++)
	{
		if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
			return true;        
	}
	return false;
}

Boy, this one has been sitting around for a while. A simple check to see if an untype dataset or table has a specific column.

Strings

//One could probably do more to strip MS Word stuff, etc..
public static string StripHTML(this string str)
{
	if (!string.IsNullOrEmpty(str)) {
		string pattern = "<.*?>";
        string str = Regex.Replace(htmlString, pattern, string.Empty);
        pattern = "&nbsp;";
        str = Regex.Replace(str, pattern, string.Empty);
        return str;
	}
	return string.Empty;
}

public static string CapitalizeWords(this string str)
{
    //Capitalize the words
    if (str == null)
        return str;
    if (str.Length == 0)
        return str;

    StringBuilder Result = new StringBuilder(str);
    Result[0] = char.ToUpper(Result[0]);
    for (int i = 1; i < Result.Length; ++i)
    {
        if (char.IsWhiteSpace(Result[i - 1]))
            Result[i] = char.ToUpper(Result[i]);
        else
            Result[i] = char.ToLower(Result[i]);
    }
    return Result.ToString();
}

//Cleans up text to make a nice little url string
public static string ToURLItem(this string str)
{
    //Make the item a URL item
    if (!string.IsNullOrEmpty(str))
    {
        return str.Replace("™", "")
                     .Replace("&trade;", "")
                     .Replace("©", "")
                     .Replace("&copy;", "")
                     .Replace(".", "")
                     .Replace(":", "")
                     .Replace("?", "")
                     .Replace("!", "")
                     .Replace("'", "")
                     .Replace("\"", "")
                     .Replace("/", "")
                     .Replace("&", "")
                     .Replace("  ", " ")
                     .Replace(" ", "-");
    }
    else
    {
        return string.Empty;
    }
}
Advertisements

One response to this post.

  1. Nice! I know this is an older post, but you can also use this for capitalizing words:


    public static string ToTitleCase(this string str)
    {
    if (str == null)
    return str;
    if (str.Length == 0)
    return str;
    TextInfo tInfo = new CultureInfo("en-US", false).TextInfo;
    return tInfo.ToTitleCase(str.ToLower());
    }

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: