Unit Testing with jQuery using FireUnit & QUnit

Today’s screencast is the 5th in a series of developer Firefox Extensions. You can view my previous 3 short Screenr screencasts here…

    In addition to this post being part in a series of Firefox Extension screencasts, it is actually also the 3rd part of an old series looking through various JavaScript Unit Testing frameworks…
    The following short screencast will give a quick review of the FireUnit Firefox Firebug Add-on and also the QUnit Unit Testing framework for jQuery. In case you don’t want to watch the 4 minute screencast I thought I would go ahead and flush out the rest of this blog post with code, screenshots, and commentary.
      As a review, to exercise our Unit Testing frameworks we have been using a simple Pig Latin function as our testing subject.

    This code is not optimal and it will be refactored in a future post. So, please focus on the Unit Testing and not the actual Pig Latin function :)

    So, here is the Pig Latin converter function we will be using for our tests…

    function EnglishToPigLatin() {
    this.CONSONANTS = 'bcdfghjklmnpqrstvwxyz';
    this.VOWELS = 'aeiou';
    this.Translate = function(english, splitType) {
    var translated = '';

    var words = english.split(/\s+/);
    for (var i = 0; i < words.length; ++i) {
    translated += this.TranslateWord(words[i]);
    if (i+1 < words.length) translated += ' ';
    }

    return translated;
    }
    this.TranslateWord = function(english) {
    /*const*/ var SYLLABLE = 'ay';

    var pigLatin = '';

    if (english != null && english.length > 0 &&
    (this.VOWELS.indexOf(english[0].toLowerCase()) > -1 || this.CONSONANTS.indexOf(english[0].toLowerCase()) > -1 )) {
    if (this.VOWELS.indexOf(english[0].toLowerCase()) > -1) {
    pigLatin = english + SYLLABLE;
    } else {
    var preConsonants = '';
    for (var i = 0; i < english.length; ++i) {
    if (this.CONSONANTS.indexOf(english[i].toLowerCase()) > -1) {
    preConsonants += english[i];
    if (preConsonants.toLowerCase() == 'q' && i+1 < english.length && english[i+1].toLowerCase() == 'u') {
    preConsonants += 'u';
    i += 2;
    break;
    }
    } else {
    break;
    }
    }
    pigLatin = english.substring(i) + preConsonants + SYLLABLE;
    }
    }

    return pigLatin;
    }
    }

    First we are going to write a simple set of 20 FireUnit tests that can be ran inside Firefox’s Firebug using the FireUnit Add-on.







    If we run the webpage inside of Firefox, we don’t see anything from the browser window, but if we open Firebug and click the “Tests” tab, then we can see the output of the 20 tests.

    FireUnit

    One of the other nice features of FireUnit is that its compare assertion will actually show the difference of the two values instead of just saying they are the same or not. Here is an example of the output from a failing compare…

    FireUnitCompare

    The output is pretty impressive, but what if you already have a lot of existing QUnit Unit Tests or what if you would also like to have some sort of User Interface to your test page. Well, the nice thing about FireUnit is that you can integrate it into QUnit! By adding several lines of code we can have the output of our QUnit tests render to the FireUnit Add-on as well!

    The following is a set of QUnit Unit Tests with 4 lines of code near the end that registers the output with FireUnit as well.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">



    English To Pig Latin QUnit Tests







    English To Pig Latin QUnit Tests









      QUnitWithFireUnit

      Now, not only do we have a User Interface on the webpage, but we also have the tests running in Firebug.

      For more information about FireUnit you can check out a post by Jonn Resig and it’s Wiki on GitHub. And if you are interested in QUnit, there is a nice overview on the jQuery webiste.

      Read More »

      Using StructureMap with ASP.NET MVC & MVC Contrib

      I’ve found myself using the MVC Contrib project more and more lately. There are tons of golden framework nuggets just waiting to be used.

      I recently integrated StructureMap into the my current ASP.NET MVC framework using MVC Contrib. The reason I decided to write this post is because most of the resources I found on the internet appeared to be a little out of date and used deprecated StructureMap APIs. So, here it goes…

      Note: The following examples are using StructureMap v2.5.3 & ASP.NET MVC v2 Preview 1 & MVC Contrib MVC2 Branch code bits. You may find minor differences in API &| syntax if you are using a different version.

      First lets investigate why StructureMap is necessary in the first place. You can find some good blog posts by Jeremy D. Miller about the basics of the Dependency Injection Pattern and using an IOC tool.

      In order to facilitate mocking and decouple our application we pass an interface of our service into our controller instead of a concrete class. The default controller factory that ASP.NET MVC uses requires a default constructor to be present, but we are going to define our own Controller Factory later in this post using one of the MVC Contrib classes.

      Note: There is actually a really good screencast with @robconery and @jeremydmiller about using StructureMap in ASP.NET MVC. There were several “Aha!” moments for me as I watched it. The StructureMap API has changed slightly since the screencast, but I will show the updated syntax in the following of this post.

      The following is a typical ContactController class that will house the Index, Details, Create, Edit, and Delete actions. You will notice that instead of having a default constructor, I have an overloaded contructor and am passing in an interface to my service. I will wire up StructureMap to handle passing in the appropriate object later in this post.

      public partial class ContactController : Controller
      {
      private IContactService service;

      public ContactController(IContactService service)
      {
      this.service = service;
      }
      }

      The wiring part, happens typically in the Application_Start event from the Global.asax.cs file. In addition to Registering your MVC routes (which should have already been wired up when you created your MVC application) you need to both configure StuctureMap to know what concrete classes map to what interfaces as well as tell MVC to use StructureMap to create its controllers.

      public class Global : HttpApplication
      {
      protected void Application_Start(object sender, EventArgs e)
      {
      RegisterRoutes(RouteTable.Routes);

      Bootstrapper.ConfigureStructureMap();
      ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
      }
      }

      I am going to attempt and explain the above code snippet line by line, so lets start with the Bootstrapper.ConfigureStructureMap() and then we will discuss the StructureMapControllerFactory().

      After everything is said and done, the important part of StructureMap is that it knows what interfaces should map to what concrete types so that it can inject the appropriate instances at runtime. This is where the Bootstrapper.ConfigureStructureMap() comes into play.

      public static class Bootstrapper 
      {
      public static void ConfigureStructureMap()
      {
      ObjectFactory.Initialize(x => x.AddRegistry(new MyApplicationRegistry()));
      }
      }

      public class MyApplicationRegistry : Registry
      {
      public MyApplicationRegistry()
      {
      Scan(assemblyScanner =>
      {
      assemblyScanner.TheCallingAssembly();
      assemblyScanner.WithDefaultConventions();
      });
      }
      }

      The above code is initializing StructureMap with the MyApplicationRegistry that contains the rules for the interface & concrete type mappings. You may be wondering, “But I don’t see where IContactService is mapped to ContactService” and that is a very good question. The answer is that StuctureMap takes the Convention Over Configuration approach and tries to take some educational guesses based on a set of default naming conventions.

      Lets say that your configuration isn’t following standard naming conventions. Can you still use StructureMap? Well, of course you can :) You have full control over the mappings and can set them up however you wish. The following is an example of me manually doing the mapping instead of using the default naming conventions. The Bootstrapper remains the same, so I only will show the code that is different below…

      public class MyApplicationRegistry : Registry
      {
      public MyApplicationRegistry()
      {
      ForRequestedType().TheDefaultIsConcreteType();
      ForRequestedType().TheDefaultIsConcreteType();
      }
      }</pre>

      Now lets focus on the StructureMapControllerFactory that we saw after we Configured StructureMap from the Global.asax. The StructureMapControllerFactory class that I am instantiating actually comes with the MVC Contrib project.  The contents of this class isn’t really all that complicated, but its one less thing you have to write by hand. The following is an example of a oversimplified implementation of the StructureMapControllerFactory that you could write yourself…

      public class StructureMapControllerFactory : DefaultControllerFactory
      {
      protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
      {
      return ObjectFactory.GetInstance(controllerType) as IController;
      }
      }

      Since we separated our dependencies and used StructureMap for injection our application is now loosely coupled and our ability to Unit Test more areas has increased.

      Stay tuned for a new series where I will upgrade a standard ASP.NET MVC project to ASP.NET MVC 2 and then integrate StructureMap, Moq, MbUnit, and suite of Unit Tests.

      Read More »

      ASP.NET AJAX Add-ons (FireAtlas & FireCookie) for Firefox's Firebug

      Today’s screencast is the 4th in a series of developer Firefox Extensions. You can view my previous 3 short Screenr screencasts here…

      For those of you that do ASP.NET or ASP.NET AJAX development, then the following Firebug Add-ons might be of interest to you.

      FireAtlas is a tool that enables you to view the PageRequestManager events, trace WebService calls, inspect Partial Updates, and view any installed application components. You can actually try out some samples pages to exercise most of the functionality of this Add-on, but I will be viewing the twitter scheduler application TwtMstr (developed by @wbm) to demonstrate some of the features in my screencast.

      FireCookie is another useful tool that allows you to view any cookies that are relevant for the current web page. This can be handy for an ASP.NET developer to inspect the .ASPXROLES, .ASPXAUTH, or ASP.NET_SessionId values that are common for most ASP.NET applications.

       

      Yet again, I hope this was beneficial to you. If you enjoyed the presentation I would appreciate either a comment to this blog &| a tweet about it to share with others.

      "#ASPNET #AJAX Add-ons (FireAtlas & FireCookie) for #Firefox's #Firebug" by @elijahmanor #tech #nettuts #screencast http://j.mp/111ZQO

      Also, if you have any suggestions that you have to help become a better presenter I would appreciate that as well. If you have a minute, please add a comment with your thoughts.

      Read More »

      Reasons Why .NET Developers Love Their MacBook Pros

      Initial Questionnaire

      I recently posted an informal survey asking .NET Developers why they love their MacBook Pros and I want to thanks the 51 individuals who responded to my survey.

      Objective Results

      The first four questions (other than name, twitter, etc…) were general questions about their MacBook Pro hardware. Those types of questions are easy and quick to graph.

      Note: If you see some discrepancies of the numbers please note that shortly after I first submitted the questionnaire I added the hardware questions. So, the first several people who answered the survey didn’t have those questions.

      Reasons You Love your MacBook Pro for .NET Development

      As to summarize the above charts, it seems that most of the people who responded to the survey were .NET developers using a MacBook Pro with a 2.66MHz Processor, 4 GB RAM, and a 15 inch monitor.

      Subjective Results

      Well, objectively that is all I can really graph. The rest of the questions allowed free form text, which is difficult to chart :) however, I did attempt to summarize each question into common answers so that I can graph them. So, here are my findings…

      WhyDidSwitchFromPcToMac

      So it seems that the majority of those that switched did so because they had the opportunity to run both OSX and Windows, they felt the hardware was better (faster & quality), and they thought it was more stylish :)

      WouldYouConsiderMovingBackToPc

      Of those that have switched from a PC to a Mac the vast majority (64%) said that they would not switch back to the PC and only a handful were adamant about moving back to the PC.

      AreThereFeaturesThatTheMacHasThatThePcDoesnt

      Mac users feel that their OS is more usable and simple compared to Windows, they feel the software for OSX is better, is more stable, and it was mentioned over and over that the multitouch trackpad on the Mac is a plus!

      DoYouFindYouAreSacrificingPerformanceByUsingTheMac

      An overwhelming majority of Mac users feel that they are no sacrificing any performance by using the Mac. Of those that did feel they were lacking some performance, they attibuted it to using a VM (VMWare or Parallels) and recommending using Bootcamp instead.

      AnythingElseIShouldKnowBeforeIChange

      As a last ditch effort to glean any useful information, I asked if there was anything else I needed to know before I made the change to a Mac. A large portion of the responses encouraged me to purchase VM software (VMWare or Parrallels), reprogram my keyboard for the PC, and to buy as much of RAM as possible.

      Conclusion

      Overall, I am very pleased with the responses of the questionnaire. I am even more inclined to make the switch myself. Only time will tell if this will actually take place, but I do appreciate you humoring me in this research and I’m sure you will know when and/or if I do take the Mac plunge for .NET development :)

      Read More »

      Page Speed & YSlow Firebug Extensions to Increase Web Page Performance

      Today’s screencast is the 3rd in a series of developer Firefox Extensions. You can view my previous 2 short Screenr screencasts here…

      You will most likely be asked to speed up the performance of some web page whether it be your corporate, personal, or some other web page. There are so many things that can cause a web page to be perceived as slow that it is helpful to have a tool to give you a guideline of where to start. 

      Fortunately, there are two great tools for the Firebug Add-on for Firefox that do performance checking of any given web page. The tools we will be looking at in the following screencast are Google’s Page Speed and Yahoo’s YSlow Add-ons.

       

      Yet again, I hope this was beneficial to you. If you enjoyed the presentation I would appreciate either a comment to this blog &| a tweet about it to share with others.

      "Page Speed & YSlow Firebug Extensions 2 Increase Web Page Performance" by @elijahmanor #tech #nettuts #webdev #screencast http://j.mp/7IFWJ

      Also, if you have any suggestions that you have to help become a better presenter I would appreciate that as well. If you have a minute, please add a comment with your thoughts.

      Read More »