November 2010 Blog Posts

A cool List .Sort() extension method via lambda

Here's an awesome List<T>.Sort() extension method: public static List<T> Sort<T,U> ( this List<T> Source, Func<T,U> OrderFunc ) { return Source.OrderBy( OrderFunc ).ToList(); } Use it with a lambda like this:     MyList<SomeClass> mylist = PopulateList();     mylist = mylist.Sort( i => i.Sequence );  ow that's an awesome sort function! Or like this for non-:     MyList<int> mylist = PopulateList();     mylist = mylist.Sort( i => i ); Now that's a cool sort function! Rob

Google Maps JavaScript API v3 Demo

I was honored to speak at the Google Technology User Group last night.  To combine a love of JavaScript, a very powerful tool, and an audience of enthusiastic fans is an incredible joy. The topic was Google Maps, and specifically the Google Maps JavaScript API version 3.  v3 simplifies and streamlines the api in some very significant ways over v 2.  Most notably, you no longer need an API key, you only need to include a script tag.  That is awesome! We started from a wonderfully simple "hello world" map, built up through creating Markers and pop-ups (called InfoWindows), worked through geolocation...

Get all Enum values as a List

Often times it's helpful to get a list of all defined values for an enum.  Enum.GetValues( typeof( MyEnumType ) ) returns an Array.  This is less than helpful.  An untyped Array is harder to query against than something much more IQueriable<T>. So I typically write something like this: Type t = typeof(MyEnumType); Array vals = Enum.GetValues( t ); List<MyEnumType> enumvals = new List<MyEnumType>(); foreach ( T val in vals ) {     enumvals.Add( val ); } After writing this code a dozen times, it occurred to me that an extension method was in order.  Here's the extension method: public static List<T> GetListOfEnum<T>() {     Type t = typeof(T);     if (...

GetCookies Safely

The broken code: HttpCookie cookie = Request.Cookies["cookiename"]; if ( cookie != null && !string.IsNullOrEmpty( cookie.Value ) ) { The problem: this code will create an entry named "cookiename" in the Request's Cookies dictionary.  If you're early enough in the event cycle that it hasn't copied cookies from Request.Cookies to Response.Cookies, it'll send your dummy entry with the response to the browser as a new cookie -- even if you do nothing else with it!  This is bad. Why have code like this?  Probably because this: Response.Cookies["cookiename"] = new Cookie( "cookiename", "somevalue" ); is easier than this: if ( Response.Cookies["cookiename"] != null ) {     Response.Cookies["cookiename"] = new Cookie(...