Pages

Monday, 4 January 2010

Cheap IoC in native C++

In a 2008 episode of dnrTV James Kovac describes how to create a very simple IoC container. All the container does is mapping the name of an interface to an instance of this interface.

Easy to do in .NET with a generic Dictionary, but what about native C++? It turns out it's not that much more difficult: all you need is a STL map and C++'s typeid. 

What is an IoC container?
A class that given an interface ISomething returns the concrete object implementing ISomething.


Why do you need an IoC container ?

It's one way to do dependency injection.

Let's say you want to unit-test some business layer that relies on a data layer. The business layer sees the data layer through an interface (let's call it IDataLayer). The actual instance of IDataLayer is created by either:

  • the entry point of the code that uses the business layer (an executable for instance). This is production code and it has to create the object connecting to the real database.
 
int _tmain(int argc, _TCHAR* argv[])
{
    // Create the concrete DataLayer object
    DataLayer dataLayer;

    // Register it with the resolver
    Resolver::Register<IDataLayer>(dataLayer);

    BusinessStuff businessStuff;
    businessStuff.DoStuff();

    return 0;
}
  • the unit-test code. The IDataLayer object in that case is a fake object that doesn't connect to the real database and therefore makes unit-tests easily reproducible and fast.

void BusinessStuffTest::DoStuff_Nominal_DoesNotRaiseException()
{
    // Arrange

    // Create the concrete DataLayer object
    FakeDataLayer dataLayer;

    // Register it with the resolver
    Resolver::Register<IDataLayer>(dataLayer);

    BusinessStuff businessStuff;

    // Act
    businessStuff.DoStuff();

    // Assert
    dataLayer.AssertStuffWasDone();

}

    Implementation of the Resolver class
    The Resolver class has two methods Register and Resolve. Here is the code for the Resolver class (very straightforward):


      #pragma once

      #include
      #include

      using namespace std;

      ///
      /// Allows you to Register and Resolve global objects
      ///
      class Resolver
      {
          static map<string, void* > typeInstanceMap;

      public:

          template<class T> static void Register(const T& object)
          {
              typeInstanceMap[typeid(T).name()] = (void*)&object;
          }

          template<class T> static T& Resolve()
          {
              return *((T*)typeInstanceMap[typeid(T).name()]);
          }
      };

      This is a just a starting point. In production Resolver could do with methods such as Unregister(), IsRegistered(), UnregisterAll()...


      An IoC container is one way to do dependency injection. Other ways include:
      • pass the injected object using the constructor
      • pass the injected object using a setter method
      Both methods above can become tedious very quickly in a big project.
      I tried all 3 methods and I find the IoC approach scales rather well. I've used it for 10 months in a production project and it works nicely with unit tests.

      Resources:

      Jean-Paul Boodhoo on the gateway pattern
      Roll your own IoC container (dnrTV)
      The Art of Unit-Testing where Roy Osherove tells everything about dependency injection and fake objects.

      Monday, 9 November 2009

      Windows 7 and the Press

      I was replacing Windows 7 beta with Windows 7 Release Candidate on my laptop a few months ago... And I was joking with colleagues about the future success of this new version. Having used Vista for two years
      Windows 7 didn't strike me as an earth-shattering evolution. Yet we predicted that people would rush on Windows 7 like bees on cupcakes for two main reasons:
      • the press was very positive about Windows 7 after it slaughtered Vista
      • the Release Candidate was as good as the final thing and free to use until March 2010. In other words people could use a fully working OS for free for 10 months.
      I don't think Vista deserved the bad press it received. I used it for two years: RC1 and RC2 on an old PC then the RTM 32-bit and eventually 64-bit on my main machine.
      Driver issues? A bit at the beginning but nothing that couldn't be overcome.
      Speed issues? Desktop: nothing that I could notice on a 4GB dual-processor Dell with raid-striped 15000rpm SAS drives. Laptop: browsing the web was fine, Visual studio was slow. After I moved to Windows 7 browsing the web was still fine and Visual Studio still slow.

      When I removed Vista 32-bit from my Vaio and installed Windows 7 RC, it indeed felt a bit snappier. But again, ANY version of Windows feels snappier after a fresh install.

      Whether you run XP, Vista or Windows 7 the OS you're running on a machine does not matter as much as the following factors:
      - how fresh the install is: re-install your OS often, with a bit of organisation it can be quick.
      - the amount of RAM: install more than you think you'll need.
      - the hard drive speed: one 15000rpm drive is good, two are better.


      I might oversimplify a bit, still I think there are mostly two reasons why you want to upgrade to a new OS:
      • the untold one: it looks better than the previous version.
      • the one you tell people to look clever: the OS is faster, contains bug fixes and new useful features.
      Thanks to unbalanced press opinions Windows 7 at last gives people an excuse to cave in to the first reason while being covered by the second.

      Monday, 2 November 2009

      Books I currently flip through #7

      Technology
      Methods
      • Apprenticeship Patterns, 1st Edition
        image
      Finance
      • The (Mis)behaviour of Markets (Benoit Mandelbrot)
        image
       
      Others
      • Blink (Malcolm Gladwell)
        image
      • The Black Swan (Nassim Nicholas Thaleb)
        image

      Sunday, 1 November 2009

      Trying out TeamCity and CruiseControl

      A few teams use Cruise Control at work. It seems to be a fairly standard choice when it comes to continuous integration. Roy Osherove recommends TeamCity over CruiseControl because he doesn't like getting his hands dirty with XML configuration (can't blame him).

      I tried both to get a feel of what you can do with them. I ran TeamCity of my main machine and CruiseControl on a VM to avoid clashes.

      I managed to get a build running in TeamCity without too much difficulty. I installed the tray notifier.

      CruiseControl is a bit more tricky. After I edited the config files I kept getting exceptions when trying to startup ccnet.exe. Had to go through several install iterations before getting something running.

      Installing TeamCity:
      • Install Tortoise SVN
      • Install VisualSVN Server
      • Run the TeamCity installer
      • Start the build agent manually (rather than through a Windows service).
      • Install the TeamCity Windows tray notifier


      Installing Cruise Control inside a virtual machine.
      • Windows Virtual PC RC, wich is a new version of Virtual PC for Windows 7.
      • Install Virtual Server 2008
      • Install SVN command line  
      • Edit the ccnet.config file
      • Get the Web Dashboard working:
        • Install IIS: under Windows Server 2008, it's not a Windows feature any more, it's a server role. You have to go to Server Manager > Roles > Add Roles and follow the wizard to add IIS.
        • Run the CruiseControl.Net installer
        • Create a new application in IIS for the ccnet webdashboard. In Server Manager, go Roles > Web Server (IIS) > Internet Information Services, open Sites > Default Web Site. Right-click Default Web Site and choose Add Application. Set Application Pool to Classic .NET AppPool.







      Saturday, 31 October 2009

      How to re-build your PC in less than 2 hours

      Pre-requisites:
      • Your data on D:, the OS on C:
      • Your backup ready (nothing to do because you have an automatic full D-drive incremental back-up scheduled to run every day )
      • Your CD case with all legally acquired original CDs for software and drivers
      • Access to the spreadsheet where you carefully store all serials for the above.
      Go:
      1. Boot from DVD
      2. Format C:.
      3. Click Next, OK, next, Ok, I agree, OK, Next, London GMT
      4. Install your favorite software. For me it is:
        1. Kaspersky
        2. Office
        3. Chrome, Firefox
        4. Skype, Live Messenger
        5. Visual Studio
      5. Check the time: if it took you more than 2 hours, start all over again.

      Sunday, 27 September 2009

      Reading the SQL Server Execution Plan

      We're having a pretty good weather in London: still sunny and about 18C. I took the bicycle to Hampstead Heath with the VAIO in the rucksack and started looking into SQL performance tuning, as you do.

      Went through SQL Server 2008 Query Performance Tuning Distilled in Safari.

      Here are a few reading notes...

      What are the different types of joins?
      • nested loop join: the most intuitive one. This is the sort of join you would write if you were to code it in C++: iterate over the smallest table first and for each row, look for a match in the other table. Efficient only if the first input is small, and the second is large and indexed.
      • hash join: used if the largest input is not indexed. This is done in two steps:
      step 1: builds a hash table with the smallest of both inputs. This hash table uses a hash function to associate a value in the joined column with an index to a bucket. Go through the whole input row by row and add each row to its appropriate bucket using the hash function.
      step 2: go through the second input row by row. For each value in the joined column, work out the index to the bucket in the hash table using the hash function. If a row is present, then there is a match and the row is kept in the result set.
      • merge join: used if an index exists on the join columns of both tables. The join columns are sorted in both tables using the indexes. Then comparing columns is relatively fast because it takes advantage of the ordering.
      What is a RID Lookup?
      • If a table does not have a clustered index, data pages are on the heap.
      • If a table has a clustered index, they are inside the clustered index.
      Non clustered indexes contain pointers to table rows: this pointer is either
      • a RID (Row ID) if the table is on the heap
      • or a clustered index key if the table has a clustered index.

      A RID lookup takes place on a heap table (table without clustered index). In order to locate data using a non clustered index SQL Server uses the RID to locate the data row in the heap. A RID lookup is costly because it involves an extra page read (on top of the page read needed for the non clustered index). You wouldn't get this extra page read with a clustered index.

      How to see the execution plan directly from the SQL profiler?
      This is very handy! No need to try and re-run a slow query in SSMS. Simply track the event ShowPlan XML in SQL Profiler under the Performance group. When you run the trace you can see the actual execution plan of any statement. The plan is displayed in a graphical way as in SSMS.
      Warning, not to be used in production! It slows down the performance of the database quite a lot.

      More about indexes:
      Index Analysis
      Index Design Recommendations 

      Other resources:
      Checklist for analysing slow-running queries




      Thursday, 18 June 2009

      XPath

      XPath came handy lately as I needed to look-up an in-memory XML document.
      I know it's probably smoother with Linq to Xml but my project had to compile under VS2005 so I used the .NET 2.0 library which does not contain Linq but contains XPath.

      Starting from the following xml file:

      <?xml version="1.0" encoding="utf-8"?>
      <pigs>
        <piggy infected="false" name="bob"/>
        <piggy infected="false" name="alfred"/>
        <piggy infected="true" name ="rodrigo">
          <disease name="swine flu"/>
          <disease name="boredom"/>
          <disease name="pig blues"/>
          <address>confidential</address>
          <phonenumber>01234546576</phonenumber>
        </piggy>
      </pigs>


      To load the XML in memory:

      XmlDocument doc = new XmlDocument();

      try

      {

      doc.Load("piggy.xml");

      }

      catch (XmlException e)

      {

      Console.WriteLine("Could not load the file. Detail: " + e.Message);

      }



      To query elements based on their name:

      XmlNodeList allPigs = doc.SelectNodes("/pigs/piggy"); // Returns all nodes called 'piggy' located inside the root-level node called 'pigs'.

      foreach (XmlNode node in allPigs)

      Console.WriteLine(node.Name + " " + node.Attributes["name"].Value);



      To query elements based on their attribute name:

      // Returns only infected pigs

      XmlNodeList infectedPigs = doc.SelectNodes("/pigs/piggy[@infected='true']");

      foreach (XmlNode node in infectedPigs)

      Console.WriteLine(node.Name + " " + node.Attributes["name"].Value);


      To return a single node (same query as above but only one node is expected):


      // Returns the single infected pig

      XmlNode infectedPig = doc.SelectSingleNode("/pigs/piggy[@infected='true']");

      if (infectedPig != null)

      Console.WriteLine(infectedPig.Name + " " + infectedPig.Attributes["name"].Value);


      To do a query relative to the current node:
      All queries above were made relative to the top of the document. But it you call SelectNodes against an XmlNode, you can do a query relative to that node. Just ommit the '/':

      // Query relative to the current node. Returns all diseases for the infected pig

      XmlNodeList diseases = infectedPig.SelectNodes("disease");

      foreach (XmlNode node in diseases)

      Console.WriteLine(node.Name + " " + node.Attributes["name"].Value);



      Resources:
      MSDN: XPath Syntax
      LINQ to XML queries
      XML Support in SQL Server 2005

      Monday, 1 June 2009

      Webforms vs MVC (London .NET User Group)

      100 people listened to Sebastien Lambla and Phil Wistanley at the Microsoft customer centre in Victoria. They talked for 2 hours without a break. Two hours is a long time but the formula they adopted was entertaining and fun. Seb was supporting MVC, Phil Webforms. They kept rotating at the mike, going through humorous slides, throwing jokes at each other and interacting with the audience. Seb:
      • Webforms has a tendency to hide HTML and actually generates a lot of goo.
      • MVC relies on you knowing HTML but once you learn it, things get pretty easy.
      • Webform's page lifecycle is complex
      • Webforms is for morons.
      Phil:
      • MVC is too complicated,
      • Webforms has a lot of ready-made controls, lots of 3rd party vendors
      • Uses a familiar event model
      • MVC is for hippies.
      To sum it up, Webforms is for building apps quickly (better suited for the financial world), MVC is good if you need a high level of quality and testability.