Archive for the ‘.Net’ Category


All the roads in Canada

In .Net on May 6, 2013 by Matt Grande Tagged: , , ,

If you’re just here for the image, click here (10638×9101, 1.17MB). If you want more information, please read on!

I recently saw a map of Oregon containing only the roads, and nothing more.  I thought it was really interesting how you could see where the population centres and natural features (lakes, mountains, etc) were.  I decided to try something with Canada.

The first challenge was finding a dataset containing all the roads in Canada. Luckily, it was on StatsCanada’s website, but it took longer than expected to find.

I opted for the GML format, since it’s the one I’m most familiar with.  The full file is a fairly large 1.9GB.  Here’s a sample of one road, Wilcox Street in Hamilton, Ontario:

<fme:lrnf000r12g_e gml:id="id00987e75-8fb2-4224-8e82-f2b97dd86307">
<gml:LineString srsName="_FME_0" srsDimension="2">
<gml:posList>7197110.1 878145.377099998 7197136.3143 878156.274300002</gml:posList>

The most important piece of information in there, for my purposes, is the <gml:posList> tag.  In this case, the data is stored as pairs of Eastings & Northings.  This means that for the above road, it travels from 7197,110 metres East and 878,145 metres North of the origin to 7,197,136 metres East and 878,156 metres North of the origin.

I decided to write a script to extract only the data I needed.  Essentially:

if (line.StartsWith("<gml:posList>"))

This brought the file size from 1.9GB to 448MB, and the number of lines from 49,352,141 to 1,983,127.

With this smaller file, I could parse each data point to find the boundries.  This helped me determine the file size to use.  I used a ratio of 500 metres per pixel which, I felt, gave a good balance between detail and file size (although it is quite large, still).

Now that I had all the boundaries and all the points, I was able to plot them on an image using .Net’s graphics library.  A few dozen lines of code, and a few seconds of processing, and I had my map.

Code will be relased on my BitBucket shortly. Stay tuned!


HamOntFire – Visualizing @HFS_Incidents

In .Net,Hamilton on January 14, 2013 by Matt Grande Tagged: , , , , ,

Awhile back, I came across the @HFS_Incidents twitter account. It broadcasts all of the calls that Hamilton Fire Services responds to.

Being an Open Data guy, I was pretty happy to see this, but I thought Twitter wasn’t the best format. If I see an event, I might have no idea where it refers to. “0 Block GERTRUDE ST” isn’t helpful unless you already know where Gertrude Street is.  I also thought that this might be a good opportunity to get my hands dirty with Google Maps, Web Sockets, the Twitter API, and image generation.

The format of the tweets was pretty easy to parse, so I decided to throw together a few services and map the data out. And with that, HamOntFire was born.

At a high level, here’s what’s happening:

  • SuperWebSocket is constantly polling the Twitter API for new tweets
  • When new tweets are found…
    • I parse the data into an object (mostly to get the address into a Google-appropriate format)
    • I geocode the location using Google’s Geocoding API
    • I store the data in RavenDB
    • The event is pushed to the browser
  • The browser displays the tweets using Google Maps.

This was all fairly easy, with one exception: Both RavenDB and SuperWebSocket are dependent on Json.Net (Newtonsoft’s fantastic Json parser which has become the de facto standard), but each required very different versions (=4.0.8 and &ge;4.5.4, respectively). After some research, I discovered that this was easy to take care of in .Net, thanks to binding redirects:

<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="" newVersion="" />

This says “For any versions of Newtonsoft.Json between v0.0.0.0 and, just use version”

Once that was taken care of, everything else was a piece of cake.

You can check out the site for yourself here, and check out the code on GitHub here.

Post Script: I’m also trying to come up with other statistics to display on the Stats page. If you can think of any, please let me know!


Thoughts on REST: Who gives a shit?

In .Net on August 9, 2010 by Matt Grande Tagged: , ,

I feel like I’ve come to a new understanding of REST.

I’ve long been an evangelical supporter of REST. I’ve felt that Controllers should have, at most, the Seven Actions (List, Show, Edit, Update, New, Create, Delete).

But no longer…

I’m currently working on a project that had a normal, everyday requirement. Purchase Orders can be edited, and they can also be closed. From the Pure-REST point-of-view, I have two options: A convoluted Update action that does two things or a creating a specific PurchaseOrderClose controller that does one highly-specific thing.

Instead, I opted to do something terrible and dangerous…

I added a Close method to my PurchaseOrder controller. I added a custom route (/PurchaseOrders/{id}/Close). The world didn’t explode, and the API is still easy to understand.

It’s a simple lesson, but one that’s often hard-learned: To every rule, there is always an exception. Always err on the side of cleaner code.

/// <summary>
/// This is it.  This is the one that will infect your soul, curve your spine,
/// and keep the country from winning the war. 
/// </summary>
public ActionResult Close(int id)
	var po = _poRepository.Close(id);
	return View(po);


Some Simple NUnit Code Snippets

In .Net on November 11, 2009 by Matt Grande Tagged: , , , ,

I decided to learn how to write code snippets and wrote a couple quick ones to help out my NUnit testing. You can grab them here.

What’s in these snippets?

Just a couple quick & easy Assert completers. Hopefully these will help you learn how to write your own (better) snippets.

  • ae – Assert.AreEqual(expected, actual);
  • ait – Assert.IsTrue(true);
  • aif – Assert.IsFalse(false);

How to install snippets

Copy and paste the XML from the link above and save it in a file with the extension .snippet. I’d recommend saving it in the default code snippets folder (C:\Users\lskywalker\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets). Then, in Visual Studio, go to Tools -> Code Snippets Manager…, and click Add. Navigate to the file you saved, and you’re done!

Neat! Where can I learn more?

Everything I learned, I learned from the MSDN articles about code snippets.

Good luck, and happy coding.


Pluralization Helper for C#

In .Net,Rails on October 28, 2009 by Matt Grande Tagged: , , ,

UPDATE – This code is now available on GitHub.  Click here for the repo.

I recently wanted a pluralization inflector in a C# project, one similar to the one in Ruby on Rails. Unable to find a satisfactory one, I whipped up my own. Here’s what I’ve got.

namespace MyNamespace
    public class Formatting
        private static readonly IList<string> Unpluralizables = new List<string>
        { "equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "deer" };
        private static readonly IDictionary<string, string> Pluralizations = new Dictionary<string, string>
            // Start with the rarest cases, and move to the most common
            { "person", "people" },
            { "ox", "oxen" },
            { "child", "children" },
            { "foot", "feet" },
            { "tooth", "teeth" },
            { "goose", "geese" },
            // And now the more standard rules.
            { "(.*)fe?", "$1ves" },         // ie, wolf, wife
            { "(.*)man$", "$1men" },
            { "(.+[aeiou]y)$", "$1s" },
            { "(.+[^aeiou])y$", "$1ies" },
            { "(.+z)$", "$1zes" },
            { "([m|l])ouse$", "$1ice" },
            { "(.+)(e|i)x$", @"$1ices"},    // ie, Matrix, Index
            { "(octop|vir)us$", "$1i"},
            { "(.+(s|x|sh|ch))$", @"$1es"},
            { "(.+)", @"$1s" }

        public static string Pluralize(int count, string singular)
            if (count == 1)
                return singular;

            if (Unpluralizables.Contains(singular))
                return singular;

            var plural = "";

            foreach (var pluralization in Pluralizations)
                if (Regex.IsMatch(singular, pluralization.Key))
                    plural = Regex.Replace(singular, pluralization.Key, pluralization.Value);

            return plural;

And of course, some NUnit tests.

namespace AutomatedTests
    public class FormattingTests
        public void StandardPluralizationTests()
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("sausage", "sausages");  // Most words - Just add an 's'
            dictionary.Add("status", "statuses");   // Words that end in 's' - Add 'es'
            dictionary.Add("ax", "axes");           // Words that end in 'x' - Add 'es'
            dictionary.Add("octopus", "octopi");    // Some Words that end in 'us' - Replace 'us' with 'i'
            dictionary.Add("virus", "viri");        // Some Words that end in 'us' - Replace 'us' with 'i'
            dictionary.Add("crush", "crushes");     // Words that end in 'sh' - Add 'es'
            dictionary.Add("crutch", "crutches");   // Words that end in 'ch' - Add 'es'
            dictionary.Add("matrix", "matrices");   // Words that end in 'ix' - Replace with 'ices'
            dictionary.Add("index", "indices");     // Words that end in 'ex' - Replace with 'ices'
            dictionary.Add("mouse", "mice");        // Some Words that end in 'ouse' - Replace with 'ice'
            dictionary.Add("quiz", "quizzes");      // Words that end in 'z' - Add 'zes'
            dictionary.Add("mailman", "mailmen");   // Words that end in 'man' - Replace with 'men'
            dictionary.Add("man", "men");           // Words that end in 'man' - Replace with 'men'
            dictionary.Add("wolf", "wolves");       // Words that end in 'f' - Replace with 'ves'
            dictionary.Add("wife", "wives");        // Words that end in 'fe' - Replace with 'ves'
            dictionary.Add("day", "days");          // Words that end in '[vowel]y' - Replace with 'ys'
            dictionary.Add("sky", "skies");         // Words that end in '[consonant]y' - Replace with 'ies'

            foreach (var singular in dictionary.Keys)
                var plural = dictionary[singular];

                Assert.AreEqual(plural, Formatting.Pluralize(2, singular));
                Assert.AreEqual(singular, Formatting.Pluralize(1, singular));

        public void IrregularPluralizationTests()
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("person", "people");
            dictionary.Add("child", "children");
            dictionary.Add("ox", "oxen");

            foreach (var singular in dictionary.Keys)
                var plural = dictionary[singular];

                Assert.AreEqual(plural, Formatting.Pluralize(2, singular));
                Assert.AreEqual(singular, Formatting.Pluralize(1, singular));

        public void NonPluralizingPluralizationTests()
            var nonPluralizingWords = new List<string> { "equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "deer" };

            foreach (var word in nonPluralizingWords)
                Assert.AreEqual(word, Formatting.Pluralize(2, word));
                Assert.AreEqual(word, Formatting.Pluralize(1, word));

And finally, usage.

var output = Formatting.Pluralization(2, "item");
// Produces "items"
output = Formatting.Pluralization(5, "sheep");
// Produces "sheep"
output = Formatting.Pluralization(100, "sausage");
// Produces "sausages"
output = Formatting.Pluralization(1, "sausage");
// Produces "sausage"

Now, I’m sure that I’m missing some cases in there. For example, I haven’t found a good way to pluralize “proof.” If any of you wonderful people find another missing case, or if you want to add one, let me know in the comments.


Hashtables and .Net Web Services

In .Net on October 21, 2008 by Matt Grande Tagged: , , , ,

If you’ve spent any time with .Net Webservices, you’ve probably seen this error:

System.NotSupportedException: The type System.Collections.Hashtable is not supported because it implements IDictionary.

Recently my co-worker Chelsea and I devised a way to get around this.  Hashtables are essentially collections of DictionaryEntrys with some extras to make certain functions.  So, all you have to do is convert from a Hashtable to a List<DictionaryEntry>.  Here’s how:

private static List<DictionaryEntry> ConvertHashToDictionaryEntryList(Hashtable source)
    var resultList = new List<DictionaryEntry>();

    foreach (DictionaryEntry item in source)

    return resultList;

Hope this helps!  Happy coding.


Solving Multiple Inheritance in C# 3.0

In .Net on September 17, 2008 by Matt Grande Tagged: , , ,

I recently came across a problem while trying to DRY my old code.  I had been two classes, one that inherits from DropDownList called DynamicDropDownList, and one that inherits from CheckBoxList called DynamicCheckBoxList.

Since both DropDownList and CheckBoxList inherit from ListControl, there was some duplicated code.  However, I was at a loss as to how to remove that since C# doesn’t support multiple inheritance.

I eventually came up with the following solution using Extensions Methods, which are new to C# 3.0.

First, create a new class to hold your duplicated methods.  Note that both the class and the method are declared static.

namespace YourNamespace
    public static class DynamicListControlExtension
        public static void DoYourStuff(this ListControl listControl)
            // Do your stuff here.

Then, in your soon-to-be-DRY classes include the following:

using YourNamespace;

namespace YourOtherNamespace
    public class DynamicDropDownList
        public void RefactoredMethod()
            // This method could also be written like this if you prefer:

And there you have it!  You’ll notice that I’ve included the this qualifier.  It is necessary in this case.

As always, leave a comment if you have any questions.  Happy coding!