Category Archives: C#

C# Multiple Property Sort

As you can see in the snippet below, sorting is easy with Linq.  Simply provide your OrderBy criteria and you’re done.  If you want a secondary sort field, add a ThenBy expression to the chain.  Want a third level sort?  Just add ThenBy along with another sort expression.

  1. var projects = new List<Project>
  2.     {
  3.         new Project {Description = "A", ProjectStatusTypeId = 1},
  4.         new Project {Description = "B", ProjectStatusTypeId = 3},
  5.         new Project {Description = "C", ProjectStatusTypeId = 3},
  6.         new Project {Description = "C", ProjectStatusTypeId = 2},
  7.         new Project {Description = "E", ProjectStatusTypeId = 1},
  8.         new Project {Description = "A", ProjectStatusTypeId = 2},
  9.         new Project {Description = "C", ProjectStatusTypeId = 4},
  10.         new Project {Description = "A", ProjectStatusTypeId = 3}
  11.     };
  13. projects = projects
  14.     .OrderBy(x => x.Description)
  15.     .ThenBy(x => x.ProjectStatusTypeId)
  16.     .ToList();
  18. foreach (var project in projects)
  19. {
  20.     Console.Out.WriteLine("{0} {1}", project.Description,
  21.         project.ProjectStatusTypeId);
  22. }

Linq offers a great sort solution most of the time, but what if you want or need to do it the old fashioned way?

  1. projects.Sort ((x, y) =>
  2.         Comparer<String>.Default
  3.             .Compare(x.Description, y.Description) != 0 ?
  4.         Comparer<String>.Default
  5.             .Compare(x.Description, y.Description) :
  6.         Comparer<Int32>.Default
  7.             .Compare(x.ProjectStatusTypeId, y.ProjectStatusTypeId));
  9. foreach (var project in projects)
  10. {
  11.     Console.Out.WriteLine("{0} {1}", project.Description,
  12.         project.ProjectStatusTypeId);
  13. }

It’s not that bad, right?

Just for fun, let add some additional logic to our sort.  Let’s say we wanted our secondary sort to be based on the name associated with the ProjectStatusTypeId. 

  1. projects.Sort((x, y) =>
  2.        Comparer<String>.Default
  3.             .Compare(x.Description, y.Description) != 0 ?
  4.        Comparer<String>.Default
  5.             .Compare(x.Description, y.Description) :
  6.        Comparer<String>.Default
  7.             .Compare(GetProjectStatusTypeName(x.ProjectStatusTypeId),
  8.                 GetProjectStatusTypeName(y.ProjectStatusTypeId)));
  10. foreach (var project in projects)
  11. {
  12.     Console.Out.WriteLine("{0} {1}", project.Description,
  13.         GetProjectStatusTypeName(project.ProjectStatusTypeId));
  14. }

The comparer will now consider the result of the GetProjectStatusTypeName and order the list accordingly.  Of course, you can take this same approach with Linq as well.

ASP.NET Meta Keywords and Description

Some of the ASP.NET 4 improvements around SEO are neat.  The ASP.NET 4 Page.MetaKeywords and Page.MetaDescription properties, for example, are a welcomed change.  There’s nothing earth-shattering going on here – you can now set these meta tags via your Master page’s code behind rather than relying on updates to your markup alone.  It isn’t difficult to manage meta keywords and descriptions without these ASP.NET 4 properties but I still appreciate the attention SEO is getting.  It’s nice to get gentle reminder via new coding features that some of the more subtle aspects of one’s application deserve thought and attention too. 

For the record, this is how I currently manage my meta:

  1. <meta name="keywords"
  2.     content="<%= Html.Encode(ConfigurationManager.AppSettings["Meta.Keywords"]) %>" />
  3. <meta name="description"
  4.     content="<%= Html.Encode(ConfigurationManager.AppSettings["Meta.Description"]) %>" />

All Master pages assume the same keywords and description values as defined by the application settings.  Nothing fancy. Nothing dynamic. But it’s manageable.  It works, but I’m looking forward to the new way in ASP.NET 4.

C# HashSet<T>

I hadn’t done much (read: anything) with the C# generic HashSet until I recently needed to produce a distinct collection.  As it turns out, HashSet<T> was the perfect tool.

As the following snippet demonstrates, this collection type offers a lot:

  1. // Using HashSet<T>:
  2. //
  3. var letters = new HashSet<char>("the quick brown fox");
  5. Console.WriteLine(letters.Contains('t')); // true
  6. Console.WriteLine(letters.Contains('j')); // false
  8. foreach (char c in letters) Console.Write(c); // the quickbrownfx
  9. Console.WriteLine();
  11. letters = new HashSet<char>("the quick brown fox");
  12. letters.IntersectWith("aeiou");
  13. foreach (char c in letters) Console.Write(c); // euio
  14. Console.WriteLine();
  16. letters = new HashSet<char>("the quick brown fox");
  17. letters.ExceptWith("aeiou");
  18. foreach (char c in letters) Console.Write(c); // th qckbrwnfx
  19. Console.WriteLine();
  21. letters = new HashSet<char>("the quick brown fox");
  22. letters.SymmetricExceptWith("the lazy brown fox");
  23. foreach (char c in letters) Console.Write(c); // quicklazy
  24. Console.WriteLine();

The MSDN documentation is a bit light on HashSet<T> documentation but if you search hard enough you can find some interesting information and benchmarks.

But back to that distinct list I needed…

  1. var coderA = new Employee { Id = 1, Name = "Coder A" };
  2. var coderB = new Employee { Id = 2, Name = "Coder B" };
  3. var coderC = new Employee { Id = 3, Name = "Coder C" };
  5. // Coder A is being added to both lists
  6. var cSharpCoders = new List<Employee> { coderA, coderB };
  7. var fSharpCoders = new List<Employee> { coderA, coderC };
  9. var coders = new HashSet<Employee>();
  10. cSharpCoders.ForEach(x => coders.Add(x));
  11. fSharpCoders.ForEach(x => coders.Add(x));
  13. foreach (Employee c in coders) Console.WriteLine(c);
  14. // Returns a unique list set — Coder A Coder B Coder C

The Add Method returns true on success and, you guessed it, false if the item couldn’t be added to the collection.  I’m using the Linq ForEach syntax to add all valid items to the employees HashSet.  It works really great. 

This is just a rough sample, but you may have noticed I’m using Employee, a reference type.  Most samples demonstrate the power of the HashSet with a collection of integers which is kind of cheating.  With value types you don’t have to worry about defining your own equality members.  With reference types, you do.

  1. internal class Employee
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  6.     public override string ToString()
  7.     {
  8.         return Name;
  9.     }
  11.     public bool Equals(Employee other)
  12.     {
  13.         if (ReferenceEquals(null, other)) return false;
  14.         if (ReferenceEquals(this, other)) return true;
  15.         return other.Id == Id;
  16.     }
  18.     public override bool Equals(object obj)
  19.     {
  20.         if (ReferenceEquals(null, obj)) return false;
  21.         if (ReferenceEquals(this, obj)) return true;
  22.         if (obj.GetType() != typeof (Employee)) return false;
  23.         return Equals((Employee) obj);
  24.     }
  26.     public override int GetHashCode()
  27.     {
  28.         return Id;
  29.     }
  31.     public static bool operator ==(Employee left, Employee right)
  32.     {
  33.         return Equals(left, right);
  34.     }
  36.     public static bool operator !=(Employee left, Employee right)
  37.     {
  38.         return !Equals(left, right);
  39.     }
  40. }

Fortunately, with Resharper, it’s a snap. Click on the class name, ALT+INS and then follow with the handy dialogues.


That’s it. Try out the HashSet<T>. It’s good stuff.

C# HybridDictionary Collection

As an icebreaker question, I’ve asked several interviewees to name classes that one might find in the System.Collections namespace.  There a quite a few answers to this questions – especially if you start to explore the System.Collections.Specialized namespace.  Though I completely understand why folks might immediately shout out answers like Hashtable, Stack, Queue or ArrayList, I am still surprised that never once did any candidate every mention System.Collections.Specialized.HybridDictionary.  It’s a shame, too, because it’s pretty cool.

One should consider the size of the collection before choosing a container.  If, for example, you are dealing with a small number of items, you might not want to use a Hashtable since there are some noted inefficiencies.  On the other hand, using ListDictionary for larger lists it is not efficient at all.  Therefore, one might appropriately chose a ListDictionary for small collections and a Hashtable for larger ones.  But what do you do if you aren’t sure how large your collection is going to be? 

That’s where the HybridDictionary comes in.  The HybridDictionary – emphasis on Hybrid – will internally use a ListDictionary while the count is less than or equal to 10 and only when the list becomes larger does it convert to using a Hashtable. The HybridDictionary is best used in situations where some lists are small and others are very large or you just aren’t sure how big a list might eventually grow. 

If you ask me, the HybridDictionary’s ability to migrate from one type to another is a neat trick.  Of course, there are a couple of things you still need to consider:

  1. What’s the overhead associated with the conversion?  Fortunately, if the starting item count is greater than 10, the HybridDictionary will start out with the Hashtable to reduce the overhead generated by the conversion.  However you still have to ask if the cost of further conversions is greater than, say, having a Hashtable manage a small sample of data?  
  2. We have to consider generics.  If you are wondering about the HybridDictionary’s generic equivalent, it’s the Dictionary<>.  The same goes for the Hashtable and ListDictionary; their generic complement is Dictionary<> as well. The point is once you start using generic equivalents, the choice of which collection type to use is pretty much decided for you. 

All the same, the HybridDictionary is really slick even if the only time you get to use it is on an interview.

.NET MailMessage, LinkedResources, AlternateViews and Exceptions

It doesn’t take much to hack together email functionality using the .NET framework.  In most cases you can new-up a MailMessage reference, assign sender and recipient addresses, provide a subject and a message body, configure your SMTP settings and then send.  Done and done.

But let’s say you need to provide both plain text and HTML versions of your message body.  Or maybe you would like to embed an image or two within the message body.  Or, what if, for some reason, you actually want to handle exceptions appropriately.  Well, there’s more to it then.

There are a numerous ways to better organize the following code.  In fact, we just went through an exercise at work where we refactored the heck out of the core email functionality and produce a really clean usable component which can be easily mocked, configured and leverages email templates.  It’s pretty cool.  That being said, I believe the following sample demonstrates the aforementioned core features of .NET emailing. 

I hope it helps. Let me know if I missed anything or it the example could be more clear.

    // Assign a sender, recipient and subject to new mail message
    MailAddress sender =
        new MailAddress("", "Sender");

    MailAddress recipient =
        new MailAddress("", "Recipient");

    MailMessage m = new MailMessage(sender, recipient);
    m.Subject = "Test Message";

    // Define the plain text alternate view and add to message
    string plainTextBody =
        "You must use an email client that supports HTML messages";

    AlternateView plainTextView =
            plainTextBody, null, MediaTypeNames.Text.Plain);


    // Define the html alternate view with embedded image and 
    // add to message. To reference images attached as linked 
    // resources from your HTML message body, use "cid:contentID" 
    // in the <img> tag...
    string htmlBody =
        "<html><body><h1>Picture</h1><br>" +
        "<img src=\"cid:SampleImage\"></body></html>";

    AlternateView htmlView =
            htmlBody, null, MediaTypeNames.Text.Html);

    // ...and then define the actual LinkedResource matching the 
    // ContentID property as found in the image tag. In this case, 
    // the HTML message includes the tag 
    // <img src=\"cid:SampleImage\"> and the following 
    // LinkedResource.ContentId is set to "SampleImage"  
    LinkedResource sampleImage =
        new LinkedResource("sample.jpg", 
    sampleImage.ContentId = "SampleImage";


    // Finally, configure smtp or alternatively use the 
    // mailSettings
    SmtpClient smtp = new SmtpClient
              Host = "",
              UseDefaultCredentials = false,
              Credentials =
                  new NetworkCredential("username", "password")

    //    <mailSettings>
    //        <smtp deliveryMethod="Network">
    //            <network host="" 
    //              port="25" defaultCredentials="true"/>
    //        </smtp>
    //    </mailSettings>

catch (ArgumentException)
    throw new
        ArgumentException("Undefined sender and/or recipient.");
catch (FormatException)
    throw new
        FormatException("Invalid sender and/or recipient.");
catch (InvalidOperationException)
    throw new
        InvalidOperationException("Undefined SMTP server.");
catch (SmtpFailedRecipientException)
    throw new SmtpFailedRecipientException(
        "The mail server says that there is no mailbox for recipient");
catch (SmtpException ex)
    // Invalid hostnames result in a WebException InnerException that 
    // provides a more descriptive error, so get the base exception
    Exception inner = ex.GetBaseException();
    throw new SmtpException("Could not send message: " + inner.Message);

15 Random Things I’ve Learned from Jeffrey Richter

I read through Jeffrey Richter’s CLR via C# not too long ago.  This evening I cracked it open again and jotted down a few notes on what I personally took away from the book. Of course, if I spent the time to write down everything I learned, I might still be busy writing.  I’ve thrown in the towel and though I’m probably not doing the book justice, here are 15 random things I have learned from Jeffrey Richter:CLR Via C# by Richter Richter: Book Cover

Page 3 – Way more than I ever wanted to know about the CLR’s execution model.  That is, everything about Managed Modules, Assemblies, Intermediate Language (IL), Framework Class Library (FCL), Common Type System (CTS) and Common Language Specification (CLS.) 

Page 56 – How to properly version your assemblies – including a breakdown of the assembly version resource information, how/when to increment the major, minor, build and revision numbers, and the distinction between AssemblyFileVersion, AssemblyInfomationVersion and AssemblyVersion numbers.

Page 144 – Best practices on how to write code to compare objects.  Here, Richter drills into object equality, identity and hash codes.

Page 177 – How the compiler handles constants – their values are embedded inside the IL code at compile time. 

Page 185 – Why one must beware of code explosion with initializing fields within classes with multiple constructors.  Key points: Any fields that the constructor doesn’t explicitly overwrite are guaranteed to have a value of 0 or null.  The compiler embeds, at the beginning of all constructor methods, field initialization code.  You should consider not initializing the default field value at the point of field declaration and instead perform the common initialization in a single constructor and have all other constructors explicitly call the common initialization constructor before overriding varying defaults. 

internal sealed class SomeType
    // Do not explicitly initialize the fields here
    private Int32 x;
    private String y;
    private Double z;

    // Sets all fields to their default
    // All constructors explicitly invoke this constructor
    public SomeType()
        x = 5;
        y = "Ben";
        z = 3.14159;

    // Sets all fields to their default, then changes x
    public SomeType(Int32 x) : this()
        this.x = x;        

    // Sets all fields to their default, then changes y
    public SomeType(String y) : this()
        this.y = y;

    // Sets all fields to their default, then changes x, y
    public SomeType(Int32 x, String y) : this()
        this.x = x;
        this.y = y;

Page 254 – The power of string interning and string  pooling.

Page 309 – How to perform unsafe array access and fixed-sized arrays.

Page 322 – How to implement multiple interfaces that have the same method name and signature and…

Page 325 – Why you need to be really careful when using explicit interface method implementations.

Page 365 – A quick introduction into Wintellect’s Power Collections library which extends the .NET Framework’s Class Library with an assortment of collection classes. The Power Collections library, documentation, and licensing information is available on CodePlex.

Page 411 – How the CLR provides special support for Nullable value types.

Page 431 – A little background on System.Exception, System.SystemException and System.ApplicationException and how Microsoft through the basic principles out the window.

Page 457 – Way more information than any single person should know about Garbage Collection (GC).

Page 562 – How to build a system which support add-ins.

Though it wasn’t mentioned in the book, Richter’s Power Threading library (DLL) contains many classes to help with threading and asynchronous programming for the .NET Framework, Silverlight, and the .NET Compact Framework. Jeffrey has described many of the classes contained in the library by way of his MSDN Magazine Concurrent Affairs columns and I found his Channel 9 overview on the AsyncEnumerator class (which uses Yield to simplify multithreading) absolutely fascinating.  The Power Threading Library is available for download here.

That’s fifteen.  I should probably drill into a couple of these with code samples…or you could just get a copy of the book. :)

Random closing thought: When I was flipping through the book today I found a spider smashed between pages 72 and 73.  Ironic?

Expand Urls with C# and LongUrlPlease

I think everyone is familiar with those short urls which are being passed around in applications like Twitter.  It’s pretty neat that there are dozens of services willing to shorten urls for us, but what about lengthening them?  That’s where comes in.  As they say, they promote safer and productive browsing by lengthening short urls so that you don’t have to.  The good folks at longurlplease provide an API documentation and demos on their site. I looked around a bit but I didn’t find a .NET/C# implementer so I put one together last night.

The included sample application merely requests that longurlplease lengthens 1+ short urls using the wrappers class which follows:


public class LongUrlPlease
    private const String LongUrlPleaseUri = "{0}";

    public static Dictionary<String, String> ExpandUrls(params String[] shortUrls)
        var longUrls = new Dictionary<String, String>();

        HttpWebRequest webRequest = GetLongUrlPleaseRequest(shortUrls);
        var response = (HttpWebResponse) webRequest.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
               longUrls = 
new JavaScriptSerializer().Deserialize<Dictionary<String, String>>(sr.ReadToEnd()); } } catch (WebException ex) { } return longUrls; } private static HttpWebRequest GetLongUrlPleaseRequest(IEnumerable<string> shortUrls) { Uri longUrlPleaseUri = GetLongUrlPleaseUri(shortUrls); return (HttpWebRequest) WebRequest.Create(longUrlPleaseUri); } private static Uri GetLongUrlPleaseUri(IEnumerable<String> shortUrls) { var parameters = new StringBuilder(); String delimiter = string.Empty; foreach (var url in shortUrls) { parameters.Append(delimiter).AppendFormat("q={0}", url); delimiter = "&"; } return new Uri(string.Format(LongUrlPleaseUri, parameters), UriKind.Absolute); } }

And here are a couple sample calls:

var singleUrl = LongUrlPlease.ExpandUrls("");

var multipleUrls = LongUrlPlease.ExpandUrls("",


Note the code comments as I needed to use the JavaScriptSerializer rather than the DataContractJsonSerializer due to the fact that longurlplease was essentially returning anonymous types back in the response. 

Download LongUrlPlease


StringBuilder Required Capacity Algorithm

.NET Strings are immutable.  StringBuilder should be used to better performance.  Blah… Blah… Blah…  You’ve heard it all before, but what you might not know is how StringBuilder dynamically allocates its capacity.  The simple answer is StringBuilder will double its capacity when its capacity is reached.  In other words, if you add 1 byte to a StringBuilder with 32 bytes of storage, the allocation will double to 64.  You might be wondering what happens if doubling isn’t enough?  Will storage just keep doubling until the required capacity is met?  Nope.  In this case, StringBuilder will only allocate exactly what is needed.  The algorithm is arguably dumb — double the allocation and, if that’s not enough, add as much as needed.  So, if you add 64 bytes to a StringBuilder with 16 bytes of storage, the allocation will double to 32 and then jump to 80 (16+64) bytes.  In other words, and this is the arguable dumb part, if you add even one more byte, reallocation is required with the next Append(). I personally think the algorithm should continue to double the storage until the required capacity is met or exceeded rather than merely meet the need.

Here’s the code (compliments of Reflector)…

private string GetNewString(string currentString, int requiredLength)
    int maxCapacity = this.m_MaxCapacity;
    if (requiredLength < 0)
        throw new OutOfMemoryException();
    if (requiredLength > maxCapacity)
        throw new ArgumentOutOfRangeException("requiredLength", 
    int capacity = currentString.Capacity * 2;
    if (capacity < requiredLength)
        capacity = requiredLength;
    if (capacity > maxCapacity)
        capacity = maxCapacity;
    if (capacity <= 0)
        throw new ArgumentOutOfRangeException("newCapacity", 
    return string.GetStringForStringBuilder(currentString, capacity);

You can read more here and here.