Sunday, December 25, 2011

Happy Holidays

My apologies for the shortage of blog posts recently, but between the new job and some unannounced side projects I've been extremely busy. So here is some best of 2011 filler material...

  • Gizmo of the Year: Asus Transformer Prime
  • Console Game of the Year: Super Mario 3D Land
  • PC Game of the Year: Orcs Must Die
  • Movie of the Year: Troll Hunter
  • Programmer of the Year: Markus "Notch" Persson
  • Gift of the Year: FLYING SHARKS!

Happy Holidays,

Sunday, November 20, 2011

Game Review: Super Mario 3D Land

How to create Super Mario 3D Land:

  1. Invent a time machine.
  2. Travel back to 1988 and kidnap the Super Mario Bros 3 design team.
  3. Put the Super Mario Galaxy development team under SMB3 designers.
  4. Have James Cameron be a senior producer of the 3D department.
  5. Profit!


While its not the open world adventure Super Mario 64 2 sequel I have been waiting for since 1995, it still kicks a**. Creative worlds, vivid colors, classic music, fluid controls, Luigi, Dry Bowser, tanookie tails everywhere, this game has it all! Aside from living up to it's lineage as a masterful platformer, and beyond being jam packed packed with well polished content, Super Mario 3D Land really shines by doing two things right in particular:

First, the 3D is actually useful.

Forgive the pun, but the 3D element of Super Mario Land actually adds a new dimension to the game play. Some of jumping puzzles can be quite challenging, and having depth perception is very helpful to gauging your jumps. Just to put this into perspective, yes that was another pun, I have only ever turned the 3D on while playing this game. However, to be honest, I still don't usually leave the 3D on the whole time that I am playing; but I do try using the 3D before I fall back on the golden tanookie leaf.

Second, it has a perfect challenge curve.

Professional game reviewers all seem to agree that good games should be easy to play, challenging to beat, and very difficult to complete. Super Mario 3D Land seems to agree with that philosophy, as it follows it to the letter. I blew through all eight worlds the first week I got it, and now I am crawling through the super frig'n hard special worlds. To be clear, the special worlds are not just harder; they also add fun new mechanics (Shadow Mario) and game play modes (timed runs) that really contribute to the replay value of the entire game.

Score - 9/10

It has taken far too long for the 3DS to finally get some games that made the investment in the hardware worth it, but that at least that time has finally come. Even though I don't much care for 3D technologies, I must still confess that this game got it right. Super Mario 3D Land is just a platformer, but it is a truly masterful platformer that acts as the perfect cornerstone for this young game console.

Game on!

Sunday, November 6, 2011

jQuery UI Modal Dialog disables scrolling in Chrome

Is Chrome becoming the new IE?

As much as I love jQuery, I still cannot escape the fact that jQuery UI leaves a lot to be desired. Yesterday I ran across an issue where the jQuery UI modal dialog acted inconsistently in different browsers. Normally opening a modal leaves the background page functionality unaltered, but in Webkit browsers (I ran into this while using Chrome) it disables the page scroll bars.

The Fix

Yes, this bug has already been reported. Yes, it is priority major. No, it won't be fixed anytime soon. For a feature as widely used as the Modal Dialog, I find that kinda sad.

However, thanks to Jesse Beach, there is a tiny little patch to fix this! Here is a slightly updated version of the fix:

(function($) {
  if ($.ui && $.ui.dialog && $.browser.webkit) {
    $ = $.map(['focus', 'keydown', 'keypress'], function(event) { 
      return event + '.dialog-overlay';
    }).join(' ');

Additional Resources

Hope that helps!

Thursday, November 3, 2011

Configuring MVC Routes in Web.config

ASP.NET MVC is even more configurable than you think!

Routes are registered in the Application Start of an MVC application, but there is no reason that they have to be hard coded in the Global.asax. By simply reading routes out of the Web.config you provide a way to control routing without having to redeploy code, allowing you to enable or disable website functionality on the fly.

I can't take credit for this idea, my implementation is an enhancement of Fredrik Normén's MvcRouteHandler that adds a few things that were missing:

  • Optional Parameters
  • Typed Constraints
  • Data Tokens
  • An MVC3 Library

Download for the project and a sample application.

Example Global.asax

public static void RegisterRoutes(RouteCollection routes)
    var routeConfigManager = new RouteManager();

Example Web.config

    <section name="routeTable" type="MvcRouteConfig.RouteSection" />
      <add name="Default" url="{controller}/{action}/{id}">
        <defaults controller="Home" action="Index" id="Optional" />
          <add name="custom"
              type="MvcApplication.CustomConstraint, MvcApplication">
            <params value="Hello world!" />

Thanks Fredrik!


Update 2/16/2013 - I have added this source to GitHub and created a NuGet Package.

Shout it

Monday, October 17, 2011

Using the InternetExplorerDriver for WebDriver

Are you getting this error when trying to use the InternetExplorerDriver for WebDriver (Selenium 2.0)?


"Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones. (NoSuchDriver)"

Don't worry, it's easier to fix than it sounds: Simply go into your Internet Options of Internet Explorer, select the Security tab, and all four zones to have the same Protected Mode value (either all on or all off). That's it!

Sample Code

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace WebDriverTests
    public abstract class WebDriverTestBase
        public IWebDriver WebDriver { get; set; }
        public void TestFixtureSetUp()
            WebDriver = new InternetExplorerDriver();
        public void TestFixtureTearDown()
            if (WebDriver != null)
        public void SetUp()
            WebDriver.Url = "about:blank";
    public class GoogleTests : WebDriverTestBase
        public void SearchForTom()
            WebDriver.Url = "";
            IWebElement searchBox = WebDriver
            searchBox.SendKeys("Tom DuPont");
            IWebElement firstResult = WebDriver
                .FindElement(By.CssSelector("#search cite"));
            Assert.AreEqual("", firstResult.Text);
Shout it


Saturday, October 8, 2011

What did Battlestar Galactica and Farscape have in common?

Thinking back on it, a lot.

The following analysis is written to show how easy it is to describe both shows simultaneously; the numbered notations distinguish the specific details for each show. While I realized that this little write up is probably a few years too late, it was still a blast to write.

While the first two seasons start off sounding somewhat formulaic, it is still amazing just how similar the shows are, and the specific similarities in seasons three and four are just uncanny.

Season 1 - Starts off great.

The show immediately sets itself apart from other shows on television with a strong and diverse cast of characters (1), a very unique sound track (2), high production value special effects (3), and a fresh take on realistic science fiction for television. The first season is mostly episodic, but consistently maintains a running story with strong character development. Viewers that tuned in every week loved the semi-serial format, but each episode was still a fun ride that you could easily jump in an enjoy.

Season one ends by masterfully bringing together all of the background story threads. A main supporting character finally has experiences a key event that we have been waiting for all season; they will never be the same (4). The characters find something that they have been looking for (5), and are immediately ambushed by the enemy. The cliffhanger has our heroes divided; leaving some in harm's way while the others have no choice by abandon their comrades for the time being (6). When the ending credits rolled, we were screaming for more.

Battlestar Galactica
  1. A slew of side characters.
  2. Unique Celtic music and drums.
  3. Unique camera shaking/zooming.
  4. Boomer is revealed to everyone as being a Cylon.
  5. Directions to Earth.
  6. People are stranded on both Caprica and Cobalt.
  1. Unique cast of diverse not humans.
  2. Unique chanting thing.
  3. Muppets in space.
  4. Moya gives birth to Tayln.
  5. John finds out the wormhole tech is in his head.
  6. John and D'Argo are floating in space, Tayln is stolen by Crais.

Season 2 - The high point.

It takes a few episodes, but our characters reunite and the shows basic formula returns. In this season we see production values increase, the main character relationships finally take on the evolved forms that we will know and love for the rest of the show (1, 2), and we get by far the strongest and most universally acclaimed season in the series.

Plot wise, this is the season that finally embarks on the large story arc that can only be resolved with the end of series (3). While season one could have been ended at any time with a simple event, we have now established enough interwoven sub plots and character back stories to commit to seasons of gradual resolution.

The season two finale is some of the best television ever written. Several major events that we have been waiting for all season finally happen (4, 5), at the end of their conclusion our characters are left in radically different positions then they were before (6, 7). Just when it looks like everything might work out, our antagonists show up and leave our heroes in danger (8). I realize how formulaic this sounds, but damn did it work.

Battlestar Galactica
  1. Adama and Roslin start falling for each other.
  2. Lee and his father come to an understanding with each other.
  3. They actually have a direction to earth.
  4. They find a habitable planet.
  5. The next election is held.
  6. Baltar is president.
  7. Most of the crew now lives on New Caprica.
  8. The Cylons show up and occupy New Capria.
  1. John and Aeryn start falling for each other.
  2. John and D'Argo finally become best friends.
  3. John needs to unlock the wormhole knowledge in his head.
  4. The Scorpius clone takes over John's mind.
  5. D'Argo's son is held ransom.
  6. John is insane.
  7. Aeryn is dying.
  8. Scorpius breaks into the lab during John's surgery.

Season 3 - The downward slope.

Season three starts off with a great intro, it resolves the cliffhanger for the previous season well, but it does not send us straight back to our basic formula. While it could have been a good thing to veer off course for a little while, the show drags out this new dynamic for too long. Our characters remain angry, bitter, and sad for basically the entire first of the season (1). By the time things get back to "normal" we are specifically tired of the characters themselves, we are ready to have fun again.

It is also worth noting that this season becomes far more serial than the previous seasons. We now experience entire episodes that really don't stand up on their own. Given how many little plot threads have been woven into the the series by this point, this is not that surprising. True fans know what is going on and they know that a conclusion is coming, but new comers will be discouraged if they try to pick up and start watching any standalone episode in season three.

Our spirits are raised with a great mid-season event, the same high caliber writing and events that we got with the premier itself (2). Unfortunately after we return from mid-season break we go right back to some boring meandering. At this point we know that some major plot resolution is right on the horizon, but rather than take some extra time to set that up we are instead given more filler while we wait for the finale.

Now just before the finale we do get some great stuff, more plot threads are tied up, and more characters finally conclude some of their subplots with great development (3). Really the last few episodes before the finale are well put together, and were worth the multiple season wait.

Then we get to the finale: a complete and under piece of contrived crap. No one saw it coming because it defied common sense (4), it violated establish rules of the universe (5), and it literally undid some of the best character development that the show had (6). The finale was not only garbage in and of itself, but it was also an insult to the show itself, and a giant middle finger to the fans.

Battlestar Galactica
  1. The crew is divided from New Capria.
  2. Adam threatens to nuke half the cast.
  3. Baltar goes on trial, Lee acquits him, Laura's cancer returns.
  4. Starbuck is magically resurrected?
  5. Tie was supposed to be a veteran from the first war!
  6. Tyrol is a cylon, not a man of the people.
  1. Zhaan is facing a slow death.
  2. John's clone dies a great death.
  3. The crew attacks Scorpius, Tayln and Crais self-sacrifice.
  4. The crew splits up, why?
  5. Worm holes now magically appear in the middle of nowhere.
  6. The crew splits up, why?

Season 4 - ...and the s***fest begun!

The season starts by not answering any of the questions raised in the previous cliffhanger (1, 2). The character changes introduced at the last minute of the previous season have undone nearly all of our character relationships (3). Our main protagonist has been demoted from being the leader to just some guy (4). Useless new side characters are introduced for no reason, and they will do nothing for the rest of the series (5). The primary plot thread of the series took a right turn (4), and much of what we thought we knew about the universe that we were playing in has been altered (6, 7). Change can be good, but this wasn't just change, it was a mid series reboot where we lost our save file.

Worst of all, this season will see drama like we have never seen it before. The drama becomes infectious, it takes center stage, it overshadows everything else that is going on, and it is just unrelatable and fake. The show goes from being a realistic science fiction with some great and dramatic character development, to just being a science-less Grey's Anatomy. I cannot over state this enough: I f***ing hated it.

The season crawls along at a snail's pace of drabby depressing episodes until we finally reach the bottom of the barrel, the mid-season finale. We finally accomplish what the primary goal of the entire series: we finally reach earth. And it sucks. And then we leave. And we never come back. And that's it. (No notations required.)

By now, as unfortunately loyal viewers, we know that the series is ending after this season. So we swallow our pride and finish out season four just so that we can say we saw the whole thing through.

The season four finale ends things pretty well for the material that it had to work with (8), but it's still lack luster (9). It's like the last 20 seconds of a roller coaster ride when you are pulling back in to the loading area: you remember the good times, you are glad you did it, it was probably worth the wait, but best loops were long ago and now you just have an upset stomach.

Battlestar Galactica
  1. Why was there a power outage?
  2. Where did the wake up music trigger thing come from?
  3. Let's just summarize this by saying that everyone hates everyone else.
  4. Lee resigns and becomes a politician because he got in an argument with daddy...really?
  5. What purpose did Baltar's cult serve?
  6. The Cylons, self admittedly, never had anything even resembling "a plan."
  7. The Cylons didn't make the skin jobs.
  8. Cylons fighting Cylons. On the inside of an asteroid belt. Next to a black hole. Ya, that was really cool.
  9. Starbuck was a ghost? Lame.
  1. Where did that worm hole come from?
  2. Why did the crew split up?
  3. I really am a broken record but, why did the crew split up?
  4. John (our adaptable hero) is now the crazy guy, and D'Argo (the angry guy) is the captain...really?
  5. Where did Noranti come from? Also, why do I care?
  6. Worm holes are now predefined by an existing network.
  7. We are traveling in "tormented space."
  8. The Peace Keeper Wars was really good; it threw out all the season four junk and just resolved the important stuff.
  9. Both sides just agree to stop fighting? Lame.

Epilogue - Lessons Learned

I think that we can learn some important lessons from these two shows, and hopefully not repeat their mistakes in the future. Because there are literally no sci-fi shows on television right now, I am unable to direct these comments directly at anyone or anything, and thus I'll keep them brief.

  • Map out your primary season plot points out in advance, and stick to them.
  • End your show when it is supposed to end; don't try to tack on more story later.
  • Increasing the amount of drama is not a substitute for plot development.
  • Don't do Stargate casting crossovers.

One finale note: I think that BStar and Farscape succeeded where Babylon 5 failed, and failed exactly where J. Michael Straczynski succeeded. The production value, casting, dialog, consistency, and episode to episode quality are all fantastic for both BStar and Farscape. However their inability to define, maintain, and eventually resolve a plot was disappointing. Perhaps someday Ronald D. Moore will partner with Straczynski to develop a show, and then I'll have to pay money and fly out to protest to whichever studio cancels it in mid-season.


Tuesday, September 27, 2011

Unity.MVC3 and Disposing Singletons

Recently I was having a conversation with a friend where I was able to articulate my thoughts on dependency injection more eloquently than I ever had before. In fact, I may have phrased this better than any nerd in the history of programming. That's a bold statement, so you be the judge:

"I didn't just swallow the inversion of control kool-aid, I went on the I.V. drip."


I recently starting working on a new project where they wanted to use Microsoft's Unity for their DI framework. It's not the exact flavor of IOC container would have chosen, but I am all for best practices regardless of specific implementation.

Important side note about MVC3: There is a new way to wire up for dependency injection. MVC now natively exposes a System.Web.MVC.DependencyResolver that you can set to use your container. This means that you no longer need to create a custom MVC controller factory to inject your dependencies.

While researching how best to implement Unity in my MVC 3 project, I came across Unity.Mvc3 by DevTrends. (Here is a little overview.) It's a great project for all the right reasons:

  1. It's up to date.
  2. It's lightweight.
  3. It solves pre-existing issues.

Note that last point. There are a lot of wrappers out there, and a lot of simple copy paste code snippets, but I really appreciate when someone goes out of their way to do more than just write their own version of something. To be specific, unlike many of the alternatives Unity.Mvc3 works with IDisposable dependencies, and that just happens to be a requirement of the project that I am working on.

Also, DevTrends get's additional bonus points for deploying their solution as a NuGet package!

Disposing Singletons with Application_End

I did find two small problems with Unity.Mvc3:

First and foremost, singleton dependencies (anything registered with ContainerControlledLifetimeManager) were not being disposed. This was easy enough to fix however, I just wired up a dispose call to my Bootstrapper in the MvcApplication's Application_End method.

Second, the NuGet package's initialize method was spelled wrong. I actually view this is actually a good thing, because it means that I am not the only person who makes spelling errors in code that they opensource! HA HA HA!

Bootstrapper Example

public static class Bootstrapper
    private static IUnityContainer _container;
    public static void Initialize()
        _container = BuildUnityContainer();
        var resolver = new UnityDependencyResolver(_container);
    public static void Dispose()
        if (_container != null)
    private static IUnityContainer BuildUnityContainer()
        var container = new UnityContainer();
        // TODO Register Types Here
        return container;
public class MvcApplication : System.Web.HttpApplication
    protected void Application_Start()
    protected void Application_End()


Saturday, September 17, 2011

Object Oriented JavaScript Tutorial

Over the past month I spent a lot of time helping teach a good friend of mine how to write advanced JavaScript. Although he had worked with JavaScript many times before, he did not know a lot of the simple things that make JavaScript the crazy dynamic rich development experience that it is. Together we built up this series of examples to help teach everything from language basics to object orientation.

Why do we need yet another JavaScript tutorial?

JavaScript is an interesting language. It is loosely typed, the object orientation has been hacked in over time, and there are at least 10 ways to do anything. The most important thing you can do when writing JavaScript is to choose a set of conventions and stick with them. Unfortunately with so many different ways to do things out there, it's hard to find tutorials that are consistent in their conventions.

Just like developing in any other programming language, understanding the fundamentals is key to building up an advanced application. This tutorial starts out extremely simple, and incrementally gets more advanced. It shows alternative implementations for different tasks, and tries to explain why I prefer the ones that I do. Meanwhile it always follows a consistent set of conventions.

Let's get to the tutorial!

This tutorial comes in 16 lessons. They are designed to be debugged with Firebug for Firefox. If you don't want to actually run the scripts then you can always just read them by downloading the small htm files below and opening them in notepad (or whichever text editor you prefer).

  1. JavaScript Types
  2. Object Properties
  3. Object Declarations
  4. Objects vs Arrays
  5. Object Pointers and Cloning
  6. Equals Operators
  7. Closures
  8. Advanced Closures
  9. Defining Classes with Closures
  10. Defining Classes with Prototype
  11. Function Scope
  12. Creating Delegates
  13. Class Inheritance
  14. Advanced Class Inheritance
  15. More Advanced Class Inheritance
  16. Extending jQuery

Additional Resources

If all that wasn't enough or it just got you thirsty for more, here are some additional resources to help start you down the path of becoming a ninja with JavaScript. My recommendation is that whenever you are writing JavaScript you should have w3schools open in a second browser window at all times.


9/21 Update - Thanks to Zach Mayer (of for providing a great critique of my tutorial. He pointed out several typos and small bugs in lessons 4, 6, 7, 9, 10, 12, 14, 15.

Monday, August 22, 2011

Why best practices?

I recently engaged in a fun discussion: Why should we (developers) follow best practices?

My first knee jerk reaction was to say "because they are best practices!" Of course someone immediately pointed out to me what a terrible argument that was. To their point, I could call anything a best practice, but that does not necessarily make it a good thing.

Best Practices: All the cool kids (wearing fedoras) are doing it.

So yes, I agree that any particular best practice should be able to stand on it's own merit. Of course this immediately brings up the next problem...

How do we train people to follow these best practices without having to prove out each and every one?

This is where we have to put our egos aside and be willing to defer to other people's opinions. When a Microsoft MVP or your team lead comes to you and says that you should do something a particular way, you probably want to consider what they have to say. This is because they have credentials, and that they have (hopefully) earned those titles and merit badges from years of experience, which would certainly imply that their opinion has value.

Am I saying that you should just defer to your senior developers / elders? No, absolutely not! Honesty goes both ways, so if something is wrong then you call them out on it! However, you should not feel the need to scrutinize every practice someone else puts forward just because you have not used it before. Again, if something is a good idea it often becomes self evident once implemented.

If you are trying to promote a best practice, start by providing a simple example or two.

Why should we have a data access layer where all of our database code goes? There are several reasons. When a change gets made to the database (and changes WILL get made to the database), there is only one place where you have to go to update your data access logic. Putting all of your logic in one place ensures that people will not rewrite the same queries over and over again. The list goes on.

If you are the trainee, please do not fall back on using arguments from ignorance.

If you are a web developer and you are asking why should I use interfaces in your MVC models, then you probably have not worked on a large project where multiple controllers (each with different models) are all rendering the same user controls. Admittedly it may take a little bit more code to implement an interface, but the reuse that it provides more than makes up for that, and when we look at this in action the advantages should become self evident.

On a related note, why do so many developers not believe in training?

Even after making it big, professional sports players still train everyday. All of the best athletes in the world still have coaches.  The world's leading scientists still read new papers published by students. So what makes software engineers any different?

I encourage all developers to go out and read blogs, check out sample projects, research design patterns, attend their local user groups, and do anything to get exposed to new ideas! Remember that such things will often provide an immediate return in your every day work life. Testable code makes hunting bugs easier, it makes your integration phase shorter, it makes releases go smoother, and that makes your stress level go down!

Programming is fun, and adhering to best practices only helps make it more fun for everyone!


Monday, August 15, 2011

Gathering Requirements for Open Source Projects

This past weekend was Dallas TechFest 2011. It was a great conference filled with great speakers and great attendees. Despite speaking at 9am both mornings (which I consider to be far too early in the morning for...well, anything), I had amazing turn outs for both presentations. In short, I had a blast, I got to hang out with great people, and I even learned at thing or two. But I digress.

For the abridged version, just stick to the big italic text. ;)

The Setup

Having so many community leaders in one place at one time, on Friday night a Dot Net User Group leader meetup was held, and this meeting took the form of a fishbowl. Many questions were raised, most got answers, but of course others only wound up raising more questions. Something particularly fun that happened when Devlin Liles raised the question, and I'm paraphrasing: "Why are so many SIG (special interest group) websites so crappy?"

After we all kicked this around for a while, and all the arguments seemed to boil down to the fact that everyone uses different systems to organize their groups, and there does not exists a univerially accepted and easy process to integrate them. As the conversation wound down, I hopped up in the one of the chairs and offered to help spearhead a project to write some type of new website that could help solve these problems.

Then something really really cool happened: a show of hands was called, and almost everyone in the room expressed an interest in contributing to such an open source website!

We very quickly decided to hold an open requirements gathering session the next day at Dallas TechFest (coincidentally to be held in the CodeSmith Hack Room). This is just another example of why I love being a member of the .NET community. It shows just how fun, interactive, and giving the this particular geek can be.

The Problem

Our story continues Saturday morning in the CodeSmith Hack room. Almost three dozen devs showed up to participate, meaning that our numbers had already grown since the previous night! We started out by making two lists on the rooms white board, "this it absolutely must do" and "things it absolutely must not do". The lists were drawn up, votes were cast, and then the drill down debate began.

It took us an additional 45 minutes to realize that the mistake had already been made: We had all listed off similar requirements, but we all had different visions of what this website would actually do.

It took us a while, but we finally figured out that we were all using the same adjectives and verbs to describe different nouns. Finally we called a vote to discuss if we were talking about 1) a top down approach where the website collects and aggrigates data from other SIG sites, or 2) a bottom up approach where this is just an open source SIG website that anyone can host themselves.

So, why did it take us so long to identify the problem? Also, how could this miscommunication have been avoided?

The Solution

Countless statistics and case studies have pointed to the requirements phase as the key to determining whether not a project will succeed or fail. I view this as a modest reminder that no project is immune to this, especially not open source ones. I fear that developers, especially the rock stars who like to engage in open source projects, often forget this.

In my opinion, our particular situation could have been avoid if we had started by defining some basic use cases.

We started out by focusing on functional requirements, but depending on which permutation of these that we selected we would come out with very different products. If we had started out by defining some use cases, that might have helped us determine how our users would interact with this website and thus would have helped us better understand our functional requirements.


I am not saying that we should have broken out our UML Diagram tools. I am saying that by simply defining basic use cases we can help create a context in which to define functional requirements.

Here are some examples to help clarify this.

Objective: Create a website to help people find user groups.
Requirement 1: Must include user group information.
Requirement 2: Make events appear on a searchable calendar.
Requirement 3: Search for events by metroplex or geographical area.
Ambiguity: Is this a portal to other websites, or is it a hosting service for other websites?

Now, let's add two use cases (one for the end user, and one for the administrator) to clarify things.

Objective: Create a website to help people find user groups.
Requirement 1: Must include user group information.
Requirement 2: Make events appear on a searchable calendar.
Requirement 3: Search for events by metroplex or geographical area.
Use Case 1: Users may arrive at the website and see a list of upcoming events in their area.
Use Case 2: Administrators should be able to register their existing website with this portal.
Ambiguity: Not so much.

Anyway, I hope that helps! 


Friday, July 29, 2011

Zen and the Art of Dependency Injection in MVC

Let me start off on a modest note: I am not an expert on dependency injection.
I am, however, certain of the value that it provides.


After having engaged in the same conversation time and time again, I have become convinced that there is indeed "one simple way to get any developer to write better code." That is because every developer, Junior or Senior, C# or Java, can always engage in more Test Driven Development with Dependency Injection. These are best practices that we can all agree on and that will always result in better and more maintainable code.

If you are already doing TDD with Dependency Injection, keep it up and help spread the word! If you are not, it's time to start. On the plus side, thanks to tools like NuGet, it has never been easier to get started with all of these new fun techniques. :)

Dependency Injection

Dependency Injection is a universally accepted best practice for a number or reasons, not the least of which is how easy it makes unit testing. You should be able to test one section of code without having to rely on the other 99% of your application. By injecting dependencies you are able to control what code is being tested with pin point precision.

A little ant can't move a lake, nor should it want to. However with a little help from a good surface tension framework, it can easily move a drop of water.


The MVC architecture provides you with a consistent entry point into your code: controller actions. All requests come in and get processed the same way, always passing through a consistent set of action filters and model binders. Right out of the box the MVC model binders are already injecting models straight into your controllers, so why not take it one more step forward and inject your services too?

My controller actions almost always need two things: 1) a model and 2) a service to process that model. So let the MVC model binder manage the RequestContext and inject your model, and let a DI framework manage the logic by injecting your service.


To get started (after having installed NuGet) you need look no farther than Tools -> Library Package Manager -> Manage NuGet Packages. If you search for Ninject, a MVC3 specific package will come up that can install itself straight into your MVC3 project and get you going in mere seconds.

Ninject is just one choice of Dependency Injection framework, and it has great documentation. If you would prefer something else then just pick your flavor of choice and keep on moving.


Create your controllers, models and services like normal, and update your controller to take in a service dependency through it's constructor.

public class CalculatorController : Controller
     public ICalculatorService CalculatorService {get; private set;}
     public CalculatorController(ICalculatorService calculatorService)
         CalculatorService = calculatorService;

Then all that you have left to do is create a model that binds the service type to it's interface...

public class MvcExampleModule : NinjectModule
     public override void Load()

...and load that in the static RegisterServices method.

public static class NinjectMVC3
     private static void RegisterServices(IKernel kernel)
          var module = new MvcExampleModule();

That's it. That is all that you have to do to start using Dependency Injection.
Want proof? Download the sample application.


Sunday, July 17, 2011

How JSONP Works

So recently I was having a conversation with someone about my JSONP update for the ExtJS library. We were talking about how I added error handling to their default implementation, and exactly what trick I had used to do that. However, we should probably start at the beginning...

What is JSONP, and how does it work?

JSONP is a standard (a hack really) that allows you to make AJAX requests across different domains. While this is an obvious security risk, there are also times where do right necessary.

Your browser appends a script block to your webpage that points to the foreign domain. Because of this, the JSONP request must be a simple get request that returns raw JavaScript.

So, what's the catch?

The return format for the JSONP request must be in the form of a call to a single global function. Once loaded, the script will execute and immediately call the global handler, which should know how to get the request data back to its caller. Also, depending on your browser, the script block may fire an onload (or in the hacky IE world, an onclick) event to help get the data back to its proper location.

The even trickier part is error handling, as there are no universal events to report script load failures.

Error Handling with JSONP

Ok, we are finally back on topic! As far as I know there are only three basic solutions to this problem...

Bad) No error handling at all.
Obviously this is a crappy solution, but it is what the default ExtJS implementation does. Somehow I suspect this lack of error handling support is 'justified' by saying that you shouldn't be using JSONP in the first place.

Better) Check for success after your max time out.
This is what my ExtJS implementation does. Before the request is made I set a timeout to call back 1 second after the max timeout of the request. The global handler calls a function that updates the JSONP request queue, canceling the timeout. If the time out is not canceled, it is assumed that the request failed and an error handler is called. This is much better than having now error handling, but it is still rather mediocre, as it could cause your end user to wait 30 seconds to find out about an error that happened 29 seconds ago.

Best) Wire up to state change events for the script block.
This is what the jQuery JSONP plugin does. Obviously this is the best solution, as it is using events exactly as they are supposed to be. The problem of course is that it has to support all the different browsers and all their different events.

In Summary

JSONP is useful, and is pretty easy to use. Implementing your own client side JSONP solution is kind of tricky, especially when taking error handling into account.

I have been trying to update my JSONP implementation to support additional error handling events, but so far it has proven to be rather difficult. Hopefully we'll see a 3.0 in the not too distant future, but right now I need to go watch the 2011 Womens World Cup Final! :D


PS: Hopefully I will get the opporutnity to talk about this at SenchaCon 2011 in Austin if you haven't yet, go sign up!

Final Fantasy VI, Remake or Reboot?

This little rant is extremely off topic for this blog, and was inspired by a random conversation I had recently. Please note that reading about game design is small hobby of mine, and that these days I spend more time reading about video games than I do playing them.

Square Enix's Impending Demise

With Square Enix's stock in the toilet, and no major releases on the horizon, we are left with one delightful prospect to think about: Who is going to buy up their intellectual property, and what are they going to do with it? Yes, I am definitely getting ahead of myself. Square Enix is not gone yet, and the current trends seem to indicate that they will probably remake FFVI for the 3DS in the not too distant future. But hey, a guy can dream!

Personally I am delighted to see the JRPG juggernaut failing, specifically because I can't wait to see what gems will surface when they are forced to liquidate their basement. Square Enix has released, with very few exceptions, no new content since there big merge in 2003. What content they have released has been almost exclusively low rated rehashes of their old IP. They have been ridiculed for their lack of innovation, and reliance on merely porting and re-releasing old titles for revenue.

We have seen this same problem of stagnation appear in other mediums such as film and television, and the American film industry seems to have come up with a particularly effective solution...

Reboot The Franchise

It worked for Batman, James Bond, Star Trek, Battlestar Galactica, and many more. So why not put this technique to work in the video game industry?

As any artistic medium ages it also matures, and future generations continuously get held to higher standards. This is true for all aspects of every genre. I don't care if you talking about television (such as Battlestar Galactica), or film (Batman), every aspect of the new product is an improvement over the old: The plot no longer relies on deus ex machina. The scripts are held to a higher literary standard. Characters are deeper, multidimensional people who exhibit growth. The graphics, well I doubt that category this requires an example. 

Generally a reboot is called for once the old material has either gotten stale, or become trapped under its own overly contrived plot. Take for example, the X-Men movie franchise. As of movie three, it's box office and critical ratings had dropped, half of the main cast was dead, and thus it was no surprise that movie four tanked as well. Movie four, and any subsequent sequels, would inevitably be forced to carry around the baggage of the previous installments. The solution, reboot a prequel! Enter First Class, up go the ratings, out go the viewer's previously lowered expectations, and in comes that much needed revenue.

I am just filled with optimism about what a good reboot could offer the Final Fantasy franchise, specifically when working with such great content as FFVI, but I'll get there in a moment.

The Problem with Ports

I love Chrono Trigger. I bought it, played it, and beat it back on the SNES. Then I didn't buy it again, play it again, and beat it again back on the PSX. I did buy it again, play it again, and beat it again back on the DS. Now I am expected to buy it again, play it again, and beat it again on the Wii Virtual Console.

How many times am I expected to pay for the same exact content? I can sort of justify paying for the same content on a different medium, such as taking CT on the go with my DS, but I simply cannot justify paying for it on the same medium. Usually with DVDs or Blue Rays we are getting a higher quality format of the content, and even then I don't like paying for the same movie again. So why would I want to pay for the same low resolution sprites on my same TV in front of my same couch every 5 years?

While porting games can help bring games to the attention of new markets, and perhaps even help raise exposure for missed opportunities and cult classics, generally I view porting games simply as a means to grab some extra cash from successes gone by.

Example: Star Wars. Star Wars Digitally Remastered. Star Wars Special Edition. And soon, Star Wars 3D. Enough said.

The Problem with Remakes

So what is wrong with just remaking a classic, like they did with Final Fantasy IV for the Nintendo DS? Good question. I'll start by saying that FFIV DS was a good game, and finish by saying that it was simply nothing new. That's it, that's my entire critique of FFIV. Did you like the original? Then you will like the remake.

Here are some problems with remakes.

1) They don't solve the problems of the original game.
I love FFVI, it is hands down my favorite RPG of all time. However it does have flaws, and I am not just talking about the original mediocre English translation. Simple example: the entire second half of the game has a mediocre script because the game engine could not rely on you having certain characters in your party, and naturally there was a lot of miss opportunity there.

2) Remakes do not introduce anything new to the gaming experience.
We already know the plot twists. We already know all of the characters fates. We already know which abilities we will get, what they do, and which ones we will use. Even I will occasionally reread the same book, but it does not make me excited and willing to pay money when it comes out with a new forward and covert art. The same can be said for the Blue Ray format of a movie.

3) It causes what I refer to as Han Shot First Syndrome.
The primary goal of a remake is to up the graphics, this goes for both movies and games. However even when that is all that you try to tweak, you will still inevitably piss off your some percent of your fan base. Perhaps they will prefer the old designs, or more than likely some details will be lost or changed in a way that they don't like. The point is that you are not giving them something new to care about, you are giving them something different to bitch about. (On a side note: Han did shoot first, and it was those small details that made his character development so much better.)

The Potential of Reboots

A reboot is free to take the best of the original and ditch the pieces that just didn't work. It gives all of us something new while still preserving the nostalgia of the original. It is just as good for developers as it is for consumers. It is the very definition of win-win!

Look at a reboot as the ultimate application of user feedback. Not only can we review the initial user reactions, but also we have the opportunity to see how those impressions help up over time. With a reboot we are free to take into account years user input, and compare that data against both the past and the future iterations of the genre in question. A reboot basically turns the original experience into a really long beta, and provides us with a richer and more complete final product.

Also, with a reboot there can be no complaint that you are not getting your money's worth. Developers are making something new, and consumers are paying for something new.

Rebooting Final Fantasy VI

FFVI has so much great material to work with. A very large, equally diverse, well developed cast of characters. An epic plot spanning multiple generations and multiple worlds. An excellent plot with both humorous highs and literally world shattering lows. Shadowy figures, political intrigue, lies, betrayal, steam punk technology, summoning magic. I mean really, this game has everything!

So what could we make better?

1) The graphics.
Let's just get that one out of the way first. The game was beautiful back in 1994 and it has aged well, but so has Elizabeth Hurley and she is almost 50. Yes, it's time for this game to get a fresh coat of paint, but I want to see more. I want to see different costumes for our heroes in the world of ruin, such as Edgar's bandit leader outfit. I want to see Kefka actually fight the Espers in Thamasa, instead of him pointing his little hand at the sky. I want to see Terra morph into a radiating entity, not a light purplish thing.

2) The script, and the second half of the core story.
I alluded to this earlier, but the second half of FFVI has some technical flaws. While I love that the second half is completely open ended, and even completely optional, the limited game mechanics of that era left us with a somewhat incomplete final chapter. I want those world of ruin plot sequences to be as full and rich as the world of balance. Also the whole script could use an overhaul, and I don't just mean another re-translation. Go watch an episode of TV Drama from 1994, then watch one from 2011, that's the kind of difference I am talking about.

3) Additional sub-plots and side stories.
The Espers in particular should be flushed out more. FFVI does a wonderful job of turning their summons not only into key elements of the plot, but also into real characters. What it doesn't do so good a job of is flushing those characters out and taking the time to give them dialog. They all have names and powers, but why stop there? Why not give the Espers their own back stories and plot threads?

4) Character balance.
It's no secret that everyone loves the Figaro twins. Not only do they have great personalities and a cool story line, but they also have great combat abilities. I honestly don't know anyone who likes playing as Setzer, Relm, Strago, or Mog. We should take the time to fix that. Let's give Relm the art style controls of Okami. Let's give Mog some motion controls. Let's make every character as fun to play as Sabin's Streetfighter style Blitz controls.

5) Production value.
If you are going to reboot this classic, then there needs to be a significant investment put into it. The sound track was great for a synthesizer, but it needs to get remixed and played but a full scale orchestra. The script was classic but it was translated by a small time American sweat shop, we need to call in full time writers on both the Japanese and American sides. FFVI was one of the first turn based RPGs to have multiplayer, let's take it online and make the Coliseum a head to head challenge.

To me, Edgar will always be a "son of submariner", but Kefka doesn't have to say it again next time.

Avoiding Pitfalls

Any FFVI remake or reboot should be very careful not to fall in to the pitfalls of the modern Final Fantasy franchise. Assuming that Square Enix does end up remaking FFVI for the 3DS, I really hope they take these points into consideration.

1) Games are supposed to be fun.
Players want to go on an adventure and enjoy themselves, not train for a marathon. FFVI had great pacing. The game moved from event to event, and very rarely required you to grind for levels or money. The combat was both fast and fun. The camera never wasted my time spinning around at the start of every fight, and every action was almost a special ability instead of a boring old attack. The point here is that FFVI did all these things well, and it would be a shame for such features to get lost.

2) Go easy on the drama.
Good story telling defines itself by the contrast between its highs and lows. For every moment of sorrow there should be a moment of joy, characters need to laugh just as much as they cry. It is these different situations that help flush out characters, giving them depth. Final Fantasy plots always involve saving the entire world, they are epics, but it's still fantasy and should try not to take itself too seriously. Also, emo kids coming of age is a really worn out plot device. It is realistic for characters to doubt themselves, but it's really frustrating when it is a central plot point. 

3) Avoid the absurdism art style.
Vests and skirts are not battle armor. Airships should probably look like they can fly. Every summon does not need to split open the planet's crust. It is great for a game to be stylized, and a fantasy setting deserves to enjoy a lot of freedom in that department, but let's not abuse that privilege.

What do YOU think?

Should someone, preferably not Square Enix, reboot Final Fantasy VI?
Are there any other improvements that you would like to see?
What modern console would you want this for?
How soon could this happen?
Are you with me?


Tuesday, July 12, 2011

Guide to Visiting Dallas

Some of my family is coming in to Dallas just to see the city, so they asked me for some help with planning their visit. After putting together some links for them, a thought occured to me: a lot of people are coming to Dallas for TechFest next month, and this might be able to help them out. 

I hope some folks out there find that useful!


Saturday, July 2, 2011

Another CodeSmith DNUG Tour Update!

On the road again, I just can't wait to get on the road again! The life I love is making code with my friends, and I can't wait to get on the road again!


  • New York
    • July 6th - Fairfield DNUG - Code Generation
    • July 7th - Long Island DNUG - Code Generation
  • Texas
    • July 12th - College Station DNUG - PLINQO
    • July 26th - Dallas ASP.NET UG - Attack of the Cloud
    • August 12th - Dallas TechFest - Attack of the Cloud, Embedded QA
    • October 23rd - Austin, SenchaCon - (Pending Approval)
  • Louisiana
    • August 6th - Baton Rouge, SQL Saturday - PLINQO
    • August 8th - Shreveport DNUG - Attack of the Cloud
    • August 9th - New Orleans DNUG - Code Generation
    • August 10th - Baton Rouge DNUG - Code Generation
    • August 11th - Lafayette DNUG - Code Generation
  • Utah
    • September 8th - Salt Lake City, Utah DNUG - TBA
    • September 10th - Salt Lake City, Utah Code Camp - TBA
    • September 10th - Salt Lake City, SQL Saturday Utah - (Pending Approval)

Want me to come speak in your area? Just drop me a line!

See you on the road,

Friday, June 24, 2011

Dallas TechFest 2011 Registration is OPEN

Are you a developer? Do you live in the DFW area? Then come join me at...

Dallas TechFest 2011
When: Friday, August 12, 2011 - Saturday, August 13, 2011
Where: University of Texas at Dallas (Richardson, TX)

Use discount code TwoDays to get $50 (that's half) off the price of a ticket!

See you there,

Friday, June 3, 2011

Life is good in Florida

It seems that no matter what state I go to I find myself being pleasantly surprised.

Arkansas was fun, Iowa was cool, and now Florida is very chill. Perhaps I am thinking about this all wrong; maybe it's less about geographic or geopolitical lines and more about people. All these speaking tours I am going on have one thing in common: no matter where I go I am always surrounded by my fellow .NET developers.

...and all of you people rock!

I am a nerdy guy, and birds of a feather flock together, but this is more than that. Every user group has been filled with fun and interesting people, and we all arrived at the same destination by taking different paths. We come together at these meetings because we all "get it", we love what we do, and I can not think of a better crowd of people that I want to spend my time with.

In short: Thank you.

Thank you Microsoft for developing such great technology. Thank you INETA for helping these DNUGs stay organized. Thank you everyone that has come out to my presentations so far. Thank you everyone who has gone out after the meetings to keep talking shop. On that note:

A tavern that serves beer in pink elephant glasses...can anyone top that? I don't know, but I intend to find out with my remaining presentations!

  • June 7th (Tuesday) - Deerfield Beach, Florida - Code Generation
  • June 8th (Wednesday) - Fort Walton Beach, Florida - Code Generation
  • June 9th (Thursday) - Mobile, Alabama - Code Generation

See you out there,

Tom DuPont
Vagabond Programmer

Friday, May 13, 2011

LINQ to SQL vs Entity Framework vs NHibernate

I am working on a new presentation that is essentially a compare and contrast analysis of the three major ORMs out there (LINQ to SQL, Entity Framework, and NHibernate). My problem is not the content, it's choosing a name for the presentation! Here are just a few ideas that I've been considering:

  • Ultimate Fighter
    • Ultimate Fighter: ORM Edition!
    • ORM Showdown: The good, the bad, and the query.
    • ORM Fight Night
    • Object Relational Matchup
  • Misc Movies
    • ORM Club: If it's your first night, your app has to fight.
    • Super-ORM-Man 4: The Quest for Business Logic
    • Dr. Strange DAL: Or how I learned to stop worrying and generated an ORM!
  • Video Games
    • World of ORM Craft
    • pORMtal: This is a triumph!
    • pORMtal 2: Wa are going to have fun, with computer science!
  • Star Wars
    • ORM Wars, Episode 4: A New DAL
    • ORM Wars, Episode 5: The Profiler Strikes Back
    • ORM Wars, Episode 6: Return of the DAL
  • Indiana Jones
    • ORM and the Raiders of the lost DAL
    • ORM and the DAL of Doom
    • ORM and the Last Cascade
  • Star Trek
    • ORM Trek 1: The Data Access Layer
    • ORM Trek 2: The Wrath of DAL
    • ORM Trek 3: The Search for Business Logic
    • ORM Trek 4: The Request's Roundtrip Voyage Home
    • ORM Trek 5: The Data Access Frontier 
    • ORM Trek 6: The Undiscovered Productivity
    • ORM Trek 7: Code Generations
    • ORM Trek 8: First Contract
    • ORM Trek 9: SQL Injection
    • ORM Trek 10: ADO.Nemesis
  • The Hobbit
    • Lord of the ORM: Fellowship of the Data Layers
    • Lord of the ORMs: The Batch Queries
    • Lord of the ORMs: Return of the DAL
    • There and Back Again: An Entity's Tale, by ORM

Wednesday, May 4, 2011

PLINQO for NHibernate, Beta 1 Released!

PLINQO makes NHibernate "so easy, even a caveman can do it."

PLINQO can generated your HBM files, entity classes, and all NHibernate configuration in seconds. It then allows you to safely regenerate that code at anytime, thus synchronizing your mappings with the database while still intelligently preserving custom changes. PLINQO for NHibernate is a enhance and simplify wrapping of NHibernate that brings the best practices, optimizations, and convenience of the PLINQO frameworks to NHibernate.

Check it out, ya'll! Check it check it out!

Friday, April 29, 2011

CodeSmith 2011 User Group Tour Update!

The Arkansas leg of the tour went really well. Hey, rest of the US: Arkansas has an amazing .NET community! I don't know what's better, their top notch developers or their gorgeous scenic byways? Either way, I am officially a huge fan of Arkansas. My thanks to everyone who came who out, and a special thanks to all the user group leaders.

Update: We have added a Louisiana leg to the tour!

Calling all Louisiana .NET developers, I will be visiting your city the second week of August! If you live in Shreveport, New Orleans, Baton Rouge, or Lafayette, be sure to come out to your local DNUG and learn about (among other things) code generation!


  • New Mexico
    • May 5th (Thursday) - New Mexico - Attack of the Cloud
  • Iowa
    • May 9th (Monday) - Cedar Rapids - Code Generation
  • Texas
    • May 11th (Wednesday) - DFW Connected Systems UG - PLINQO: Advanced LINQ to SQL
  • Florida
    • May 26th (Thursday) - Memphis - Code Generation
    • June 1st (Wednesday) - Brevard County  - PLINQO: Advanced LINQ to SQL
    • June 2nd (Thursday) - Tallahassee - Attack of the Cloud
    • June 7th (Tuesday) - Deerfield Beach - Code Generation
    • June 8th (Wednesday) - Fort Walton Beach - Code Generation
  • Alabama
    • June 9th (Thursday) - Mobile - Code Generation
  • New York
    • July 6th (Wednesday) - Fairfield - Code Generation
    • July 7th (Thursday) - Long Island - Code Generation
  • Louisiana
    • August 8th (Monday) - Shreveport - Attack of the Cloud
    • August 9th (Tuesday) - New Orleans - Code Generation
    • August 10th (Wednesday) - Baton Rouge - Code Generation
    • August 11th (Thursday) - Lafayette - Code Generation


  • Attack, of the Cloud!
    • Cloud computing is great, but what do we put in the cloud? The web is advancing at an incredible pace and it’s time to start building true Web Applications, not just web sites! Web Apps shake off the constraints of operating system specific frameworks and free developers to work in an open standards based environment. This session will cover a variety of topics ranging from ASP.NET MVC development, unit testing, REST APIs, JSON, JQuery, ExtJS, tips and tricks, lessons learned, and more. It will conclude with building a sample blog reader Web App, and then deploying that to Windows Azure.
  • Generate Your Code!
    • Code generation is a powerful practice that allows you produce higher-quality, more consistent code in less time. This helps remove the mundane and repetitive parts of programming, allowing developers to focus their efforts on more important tasks, and saving companies time and money. Code generation enables you to: efficiently reduce repetitive coding, generate code in less time with fewer bugs, and produce consistent code that adheres to your standards.
  • Using Embedded QA to Build Rock-Solid Software
    • Without an automated means to collect errors from deployed applications, how can you know that your software is performing as expected? Embedded QA can be used to augment your own internal QA efforts, greatly increasing both the effectiveness of your testing and overall stability of your applications. As Jeff Atwood phrased it, "If you're waiting around for users to tell you about problems with your website or application, you're only seeing a tiny fraction of all the problems that are actually occurring. The proverbial tip of the iceberg."
  • PLINQO: Advanced LINQ to SQL
    • In the time that LINQ to SQL has been available, we have been identifying ways to make LINQ to SQL better. We have compiled all of those cool tips and tricks including new features into a set of CodeSmith templates. PLINQO opens the LINQ TO SQL black box giving you the ability to control your source code while adding many new features and enhancements. It's still LINQ to SQL, but better!

Hope to see you soon!
~ Tom

Tuesday, April 12, 2011

Two Important Questions about PLINQO EF

The .NET community is the best development community ever.
How do I know that? Because they ask the best questions!

Here are two really important questions that we have been asked concerning PLINQO for Entity Framework that I wanted to call some extra attention to:

What is the advantage of using PLINQO EF instead of standard Entity Framework?

In 1.0 the primary goal was to improve the regeneration story of Entity Framework, thus making it easy to update and sync data and code changes. The entities are pretty much equivalent, but the PLINQO query extensions greatly improve and simplify the composition of queries.

With future versions there will be more features brought in from the PLINQO for L2S feature set.  This will include built in caching, auditing, enhanced serialization, possibly WCF and DataServices support, and hopefully batch/future queries!

What are the benefits, if any, of moving to PLINQO EF over PLINQO L2S?

Such benefits are not there yet, but will be. The primary reason to migrate right now would be to inherit the benefits that standard EF has over L2S, most notably is its multiple database support (so more than just SQL Server).

There will be a simple migration path between the two versions of PLINQO, but the bottom line is that PLINQO EF is not ready for that yet. It is still in beta, and is simply not yet as feature complete as PLINQO L2S. It's going to take one or two releases until we get there, but we will get there! :)

Tuesday, March 29, 2011

Presentation Downloads

Presentation downloads are (finally) up!

The PLINQO presentation will be up some time next week.


Friday, March 18, 2011

OAuth 2.0 for MVC, Two Legged Implementation

OAuth 1.0 was one complicated beast. The OAuth 2.0 spec greatly simplified things, but that also had the wonderful side effect of rending all of our old OAuth 1.0 code obsolete. They say that "the only thing a pioneer gets is an arrow in the back," I disagree, I say "the thing that only a pioneer gets to have is an adventure."

For example, I got to help write this wonderful, cutting edge, open source, OAuth 2.0 implementation for MVC!

OAuth 2.0 Overview

OAuth is all about tokens. You start by getting a Request Token from the server, and then using that to secure your login information. When you have successfully logged in you will be given a role/permission specific Access Token, you will then submit this token with all of your future requests. You will also get a Refresh Token with your Access Token. Once your Access Token has expired, you can then submit your Refresh Token to get a new pair of Access and Request Tokens.

Two Legged vs Three Legged

A two legged implementation is rather straight forward, you log into the server you are trying to access. A three legged implementation allows you to gain access to a resource by authentication with a third party server.  For the time being this project only supports two legged authentication.


You must implement four classes to use this library:

  1. OAuthIdentityBase
  2. OAuthPrincipalBase
  3. OAuthProviderBase
  4. OAuthServiceBase

The first three are very small classes, requiring only a few short lines of code. The Service is the work horse where most of your code will go, but even then it only requires the implementation of four methods.

public abstract class OAuthServiceBase : ProviderBase, IOAuthService
    public static IOAuthService Instance { get; set; }
    public abstract OAuthResponse RequestToken();
    public abstract OAuthResponse AccessToken(string requestToken,
        string grantType, string userName, string password, bool persistent);
    public abstract OAuthResponse RefreshToken(string refreshToken);
    public abstract bool UnauthorizeToken(string token);

Then of course you will need to update your Web.config:

    <section name="oauth" type="OAuth2.Mvc.Configuration.OAuthSection, OAuth2.Mvc, Version=, Culture=neutral"/>
  <oauth defaultProvider="DemoProvider" defaultService="DemoService">
      <add name="DemoProvider" type="OAuth2.Demo.OAuth.DemoProvider, OAuth2.Demo" />
      <add name="DemoService" type="OAuth2.Demo.OAuth.DemoService, OAuth2.Demo" />
      <add name="OAuthAuthentication" type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=, Culture=neutral"/>

Securing Your Pages

That's the easy part, just add the MVC Authorize Attribute to any actions or controllers that you want to secure.

public class HomeController : Controller
    public ActionResult Index()
        return View();
    public ActionResult Secure()
        return View();

The Demo API in Action

  • /oauth/requesttoken
    • Request Params
      • None
    • Result
      • RequestToken = a028f1895cc548af9de744f63d283f6e
      • Expires = 300
      • Success = true
  • /oauth/accesstoken
    • Request Params
      • oauth_token = a028f1895cc548af9de744f63d283f6e
      • username = tom
      • password = c4e5995d4cb8b26970336b956054ac1be9cc50b3
    • Result
      • AccessToken = 3b23ee5f128a45c88e657ecc74c41bbc
      • Expires = 300
      • RefreshToken = 85126a53bca940f1ae7c9d797f63a274
      • Success = true
  • /oauth/refreshtoken
    • Request Params
      • refreshToken = 85126a53bca940f1ae7c9d797f63a274
    • Result
      • AccessToken = 8cfc317af6ed45b2b065a8fa5da3ba81
      • Expires = 300
      • RefreshToken = d0b4a8898d974e939ca83b55cfeabcac
      • Success = true
  • /oauth/unauthorize
    • Request Params
      • oauth_token = 8cfc317af6ed45b2b065a8fa5da3ba81
    • Result
      • Success = true

Additional Resources

Happy authenticating!
~ Tom

Friday, March 11, 2011

CodeSmith 2011 User Group Tour

The CodeSmith Tools are hitting the road (and even the skies) to talk about .NET technology all around the US!
Want us to speak at your local user group? Just drop me a line!

We will post again each month with updates and additional details, so stay tuned!


  • Oklahoma
    • April 4th (Monday) - Oklahoma City DNUG - PLINQO: Advanced LINQ to SQL
  • Arkansas
    • March 25th (Friday) - North West Arkansas TechFest 2011 - Attack of the Cloud
    • April 11th (Monday) - Fort Smith DNUG - PLINQO: Advanced LINQ to SQL
    • April 12th (Tuesday) - North West Arkansas DNUG - TBA
    • April 13th (Wednesday) - North West Arkansas SQL Server UG - PLINQO: Advanced LINQ to SQL
    • April 14th (Thursday) - Little Rock DNUG - Using Embedded QA to Build Rock-Solid Software
  • New Mexico
    • May 5th (Thursday) - New Mexico DNUG - Attack of the Cloud
  • Iowa
    • May 9th (Monday) - Cedar Rapids DNUG - Code Generation
    • August 4th (Thursday) - Des Moines DNUG - Using Embedded QA to Build Rock-Solid Software
  • Texas
    • May 11th (Wednesday) - DFW Connected Systems UG - PLINQO: Advanced LINQ to SQL
  • Florida
    • May 26th (Thursday) - Memphis DNUG - Code Generation
    • June 1st (Wednesday) - Space Coast DNUG - PLINQO: Advanced LINQ to SQL
    • June 2nd (Thursday) - Tallahassee DNUG - Attack of the Cloud
    • June 7th (Tuesday) - Deerfield Beach DNUG - Code Generation
  • New York
    • July 7th (Thursday) - Long Island DNUG - Code Generation
    • TBD - Fairfield DNUG - Code Generation


  • Attack of the Cloud
    • Cloud computing is great, but what do we put in the cloud? The web is advancing at an incredible pace and it’s time to start building true Web Applications, not just web sites! Web Apps shake off the constraints of operating system specific frameworks and free developers to work in an open standards based environment. This session will cover a variety of topics ranging from ASP.NET MVC development, unit testing, REST APIs, JSON, JQuery, ExtJS, tips and tricks, lessons learned, and more. It will conclude with building a sample blog reader Web App, and then deploying that to Windows Azure.
  • Code Generation
    • Code generation is a powerful practice that allows you produce higher-quality, more consistent code in less time. This helps remove the mundane and repetitive parts of programming, allowing developers to focus their efforts on more important tasks, and saving companies time and money. Code generation enables you to: efficiently reduce repetitive coding, generate code in less time with fewer bugs, and produce consistent code that adheres to your standards.
  • Using Embedded QA to Build Rock-Solid Software
    • Without an automated means to collect errors from deployed applications, how can you know that your software is performing as expected? Embedded QA can be used to augment your own internal QA efforts, greatly increasing both the effectiveness of your testing and overall stability of your applications. As Jeff Atwood phrased it, "If you're waiting around for users to tell you about problems with your website or application, you're only seeing a tiny fraction of all the problems that are actually occurring. The proverbial tip of the iceberg."
  • PLINQO: Advanced LINQ to SQL
    • In the time that LINQ to SQL has been available, we have been identifying ways to make LINQ to SQL better. We have compiled all of those cool tips and tricks including new features into a set of CodeSmith templates. PLINQO opens the LINQ TO SQL black box giving you the ability to control your source code while adding many new features and enhancements. It's still LINQ to SQL, but better!

Hope to see you soon!
~ Tom 

Tuesday, March 8, 2011

PLINQO for NHibernate?

As my Uncle Ben once said, "with great insomnia comes great responsibility." Or maybe that was Spiderman, I don't remember. All I know is that I couldn't go to sleep last night, and when I came to this morning there was a proof of concept PLINQO for NHibernate architecture on my screen.

I am not saying we are working on PLINQO for NHibernate...yet.

NHibernate is a well established ORM that is backed by a great community, and frankly, they have their own way of doing things. NHibernate is built on some great principals: patterns, testability, and openness. Also, things like Fluent NHibernate and Sharp Architecture are examples of some superb extensions to the base NHibernate framework, and they are perfectly tailored to fit NHibernate needs.

Originally we had thought that creating PLINQO templates for NHibernate would be going against the grain of the NHibernate community. The architecture of PLINQO, specifically it's query extension pattern, is a bit of an anti-pattern. Also PLINQO is based on LINQ to SQL, and not all of it's features are needed in the more mature NHibernate framework.

So if we were to make PLINQO for NHibernate, what value would it provide?

First and foremost, simplicity.
A major goal of PLINQO is to get the end user up and running as fast as possible. A major complaint of NHibernate is that it can be very complex to setup. It seems that simplifying the start up process would be a major advantage to new users.

This could provide a migration path to NHibernate.
Using LINQ to SQL or PLINQO and want to switch to NHibernate? Maybe you need more DB Providers, maybe you like open source components, or maybe you have converted to the church of Rhino; in any case, this would be a great way to make that transition quick and easy.

PLINQO for NHibernate means more PLINQO.
...and I LOVE PLINQO! I certainly don't think more PLINQO could hurt anyone, heck, I'm pretty sure that it will help someone! Also, on a personal note, I would get to code more PLINQO! If you can't tell from all the exclamation points, I find that prospect to be freak'n exciting!

What would PLINQO for NHibernate look like?

Remember back when you were in grade school and your teacher told you that there were no stupid questions? That was a stupid question.

Ideally the PLINQO NHibernate templates would generate you a matching data layer. You would swap out your templates, update your namespaces, and you're back in business.

public void ByQueries()
    // This DataContext is powered by a NHibernate ISession
    using (var db = new PetshopDataContext())
        var x = db.Product
            .ByName(ContainmentOperator.NotEquals, "A")

        var y = db.Product
            .ByName(ContainmentOperator.StartsWith, "B")
        var z = y.ToList();

        Assert.AreEqual(1, z.Count);
        Assert.AreEqual(x.Id, z[0].Id);

So by the way, that code snippet is real, and that test succeeds.

Real Time Web Analytics