Posts Tagged ‘C#’


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 ≥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!


Ajax User Controls in ASP.Net MVC Preview 3

In .Net on July 29, 2008 by Matt Grande Tagged: , , , ,

I was taking a look into how to ajax up my website using the new ASP.Net MVC stuff, and I came across some difficulties. After using Ruby on Rails for the better part of the last year, I expected to be able to call render_to_string or something similar on a UserControl, and replace a div with that string.

I’m writing a basic product page, and the product can come in many colours. I opted to ajaxify the colour pagination.

The first thing I did was get JQuery into my project. JQuery is a javascript library that makes a lot of the more common AJAX and DHTML tasks easier.

function ChangeColorwayPage(pageNumber) {
  // Hide the element with the id of colorway1
  // Generate the URL of the ajax call
  url = '/ColorWay/ChangeColorWayPage/<%= ViewData.Model.Style_Number %>/' + pageNumber;
  // Make a GET request to the URL.  The third parameter is the function that gets called after the ASP.Net code is run.
  $.get(url, null, function(data, status) {
    // Replace the HTML within the div 'colorway1'
    // Show the div again!

This was easy enough. The tricky part came when rendering a UserControl into a string. I opted to make a simple AjaxController that inherits from the base Controller object.

namespace YourApp.Controllers
    public class AjaxController : Controller
        public string RenderToString(string UserControl, object model, Dictionary<string, object> ViewParameters)
            // Replace the current context with a new context that writes to a string writer
            var existingContext = System.Web.HttpContext.Current;
            var writer = new StringWriter();
            var response = new HttpResponse(writer);
            var context = new HttpContext(existingContext.Request, response) {
                User = existingContext.User
            System.Web.HttpContext.Current = context;

            // Add the ViewParameters to the ViewData hash
            foreach (string key in ViewParameters.Keys)
                ViewData[key] = ViewParameters[key];

            // Execute the action
            var viewResult = View(UserControl, model);

            // Execute the result

            // Restore the old context
            System.Web.HttpContext.Current = existingContext;

            return writer.ToString();

And now, in my ColorWay controller, all I have to do is this:

namespace YourApp.Controllers
    // Notice that it inherits from AjaxController
    public class ColorWayController : AjaxController
        public string ChangeColorWayPage(string sellingStyleNumber, int pageNumber)
            var productSpecs = new ProductSpec(sellingStyleNumber, false);
            var parameters = new Dictionary<string, object>();
            parameters["page"] = pageNumber;

            // Simply call RenderToString and you're good to go!
            return RenderToString("ProductSpecColorWay", productSpecs, parameters);

And with that, you should be good to go.

Happy coding!