Posts Tagged ‘.Net’

Articles

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:

</pre>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.6.0.0" newVersion="4.0.8.0" />
 </dependentAssembly>
<pre>

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

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!

Articles

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.

Articles

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);
                    break;
                }
            }

            return plural;
        }
    }
}

And of course, some NUnit tests.

namespace AutomatedTests
{
    [TestFixture]
    public class FormattingTests
    {
        [Test]
        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));
            }
        }

        [Test]
        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));
            }
        }

        [Test]
        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.

Articles

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)
        resultList.Add(item);

    return resultList;
}

Hope this helps!  Happy coding.

Articles

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.DoYourStuff();
            // This method could also be written like this if you prefer:
            DynamicListControlExtension.DoYourStuff(this);
        }
    }
}

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!