Introduction to Dependency Injection

Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test.

I like to use samples to explain Dependency Injection. We’ll use a SqlMetaDataProvider class which needs to provide the meta data coming from a SQL Server database. It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model. Obviously, i want to be able to test this class without actually going to the database because that would make the tests slow. So how can we test if the relational data is being converted to the object model without going to the database?

Well, let’s look at what the class does. First of all, it retrieves sql server meta data. Then it converts it to an object model. But retrieving the meta data doesn’t really belong here… it should be functionality that’s offered by another class. So we create a SqlDataRetriever class. All it will do is return meta data in the relational structure. Nothing more. So now, our SqlMetaDataProvider class can simply use the SqlDataRetriever class to retrieve the meta data. So basically, SqlDataRetriever is now a dependency of the SqlMetaDataProvider class because SqlMetaDataProvider is depending on SqlDataRetriever to return the relational meta data.

At this point, our class could look like this:

    public class SqlMetaDataProvider : IMetaDataProvider
    {
        private readonly string _connectionString;
        private readonly SqlDataRetriever _sqlDataRetriever;
 
        public SqlMetaDataProvider(string connectionString)
        {
            _connectionString = connectionString;
            _sqlDataRetriever = new SqlDataRetriever();
        }
 
        public MetaDataStore GetMetaDataStore()
        {
            SqlMetaData sqlMetaData = _sqlDataRetriever.GetMetaData(_connectionString);
 
            return ConvertToMetaDataStore(sqlMetaData);
        }
 
        private MetaDataStore ConvertToMetaDataStore(SqlMetaData sqlMetaData)
        {
            MetaDataStore store = new MetaDataStore();
 
            AddTablesToStore(sqlMetaData.TableInfo, store);
            AddColumnsToTablesInStore(sqlMetaData.ColumnInfo, store);
            CreateRelationshipsBetweenTables(sqlMetaData.RelationshipInfo, store);
 
            return store;
        }
    }

Note: I left out the code for the AddTablesToStore, AddColumnsToTablesInStore and CreateRelationshipsBetweenTables methods because they aren’t relevant to this specific topic.

Now we need to make sure we can replace the instance of SqlDataRetriever during testing with one we can supply ourselves. That test instance could then simply return a DataSet that was created in-memory, thus keeping our tests running fast. Notice how SqlMetaDataProvider has a reference of the type SqlDataRetriever. The type is essentially fixed, which creates a strong dependency on the SqlDataRetriever class. If we were to replace the type of the reference with an interface, it would at least make it easier to use another type for our required dependency, one that simply implements the interface.

So we create the ISqlDataRetriever interface:

    public interface ISqlDataRetriever
    {
        SqlMetaData GetMetaData(string connectionString);
    }

And then we modify the definition of SqlDataRetriever to implement the interface:

    public class SqlDataRetriever : ISqlDataRetriever

Now we need to modify our SqlMetaDataProvider class so it holds a reference to the interface type, instead of the class type:

        private readonly ISqlDataRetriever _sqlDataRetriever;

We still need to find a way to inject our dependency into our SqlMetaDataProvider so we’ll modify the constructor:

        public SqlMetaDataProvider(string connectionString, ISqlDataRetriever sqlDataRetriever)
        {
            _connectionString = connectionString;
            _sqlDataRetriever = sqlDataRetriever;
        }

The only downside to this is that it now takes more work to create an instance of SqlMetaDataProvider… work that clients shouldn’t need to do if they just want to use the default ISqlDataRetriever implementation. If you’re using an Inversion Of Control (IoC) container, you can simply request an instance of SqlMetaDataProvider and the IoC container would also create the necessary dependency for you. Using an IoC container however is outside of the scope for this post, so we won’t do that. In fact, if you know that your production code will always use the SqlDataRetriever implementation, you could also provide a simpler constructor which takes care of that for you:

        public SqlMetaDataProvider(string connectionString)
            : this(connectionString, new SqlDataRetriever()) {}

So you could use the simpler constructor in your production code, and the other one in your test code. Speaking of test code, we still need to write that test which tests the conversion without hitting the database. First, we need to create an implementation of ISqlDataRetriever which allows us to pass a DataSet to it which the ISqlDataRetriever instance should return to its consumer (our SqlMetaDataProvider):

    public class SqlDataProviderStub : ISqlDataRetriever
    {
        private SqlMetaData _sqlMetaData;
 
        public SqlMetaData SqlMetaData
        {
            set { _sqlMetaData = value; }
        }
 
        SqlMetaData ISqlDataRetriever.GetMetaData(string connectionString)
        {
            return _sqlMetaData;
        }
    }

And finally, the test:

        [Test]
        public void GetMetaDataStore_ProvideDataSetWithTwoTablesAndRelationship_MetaDataStoreIsCorrect()
        {
            SqlMetaData sqlMetaData = PrepareMetaDataSetInMemoryWithTestData();
 
            SqlDataProviderStub sqlDataProvider = new SqlDataProviderStub();
            sqlDataProvider.SqlMetaData = sqlMetaData;
 
            // pass null as the connectionString, and pass our SqlDataProviderStub
            IMetaDataProvider metaDataProvider = new SqlMetaDataProvider(null, sqlDataProvider);
 
            MetaDataStore store = metaDataProvider.GetMetaDataStore();
 
            AssertStoreContainsOurTestData(store);
        }
Original article by Davy Brion

Running NUnit from Visual Studio

If you are like me, I like to keep my Visual Studio environment as clean as possible, so if I can get away from adding any addins in to Visual Studio I will always go for that option.

So when it comes to testing I prefer to run with NUnit and run it as n external program.  

To do this just right click on the unit test project -> choosing the properties option -> setecting the Debug tab -> choose “start external program” and enter the NUnit assembly path, in my case this is “C:\Program Files\NUnit 2.5\bin\net-2.0\nunit.exe”, next is to select the command line arguments and point this to your unit test dll,

e.g.  “C:\Program Files\NUnit 2.5\samples\csharp\money\bin\Debug\cs-money.dll” /run

The “run” parameter will automatically run the loaded project

Alternatively you can use a Visual Studio add-in such as TestDriven.Net, this also provides NCoverExplorer to provide you with code coverage.

Mocking

 

In object-oriented programming, mock objectsare simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

It is possible to perform integration testing on the Membership Provider, take a look at this blog entry to find out more Integration testing the MembershipProvider

Within the Project we are using Rhino MocksOren Eini is doing a great job with this framework, and I think it’s the only one that seems to be keeping up with the latest features in .NET, other than TypeMock. Plus, it’s totally free to use. It’s also the only one other than TypeMock which does not require you to input strings for method names you’d like to mock, which is cool. It’s compelling to use it but the project is currently maintained by just one person. If Oren decides to drop it, or for any reason stop working on it, the book might turn out outdated quite quickly. Plus, it’s not very widely used, though it seems to be gaining in popularity.

References

Introduction to Mocking with Rhino Mocks

Mocking

Code Samples

 

Configuration for NLog

When I am writing an application it is so important to make sure you record and log information correctly, there are a number of free loggers you can use

I have come to use NLog, by Jaroslaw Kowalski, it’s so easy to use and get up and running, which is what you really need if you are using a logger of any type.

But what is the best practice when using a log in a live environment?

Or more importantly what and how do you configure you configuration file to make sure you are logging all your information?

The way I see it is, capture your logging to the Event Log and a Database for information and tracing.

When it comes to Errors and Fatal logging then, write it to as many places as you can, an Error file, the Event Log, a Database Log, and perhaps a special Exception Database Log, because if something has failed, you’ll want to shout about it, and you want to record it in as many places as possible.

Here is an example of an NLog configuration

NLog.config (2.63 kb)

To setup the database use the following creation creation script

NLogDatabase.sql (1.16 kb)

Make sure within the SQL Database you have a user “nloguser”, with a password of “nlogpassword”, these are both defined in the NLog configuration file, and can be changed if need be.

That is it, all you have to do now is wait for your live application to log some information.

I am sure there are a few other configuration options available and I welcome anyones comments on how to improve this configuration file.

London

 

Arrive on Friday night, preferably at city airport and head east to Brick lane for a curry. After dinner have drinks at the Vibe bar or 93 feet east. If you are feeling super energetic see what is going on at Sosho, Cargo or Electricity showrooms before getting a good night of sleep.

Saturday morning, get up early and have breakfast at Patisserie Valerie in Knightsbridge. Have a wander around Harrods for an hour or two making sure that you check out the food hall. Jump on the tube and head over to Camden. You may enjoy the market – I don’t – but if the chaos isn’t for you get off at Chalk Farm station rather than Camden to avoid it all. Grab lunch at Thanh Binh one of the best cheap Vietnamese restaurants in London, I recommend the Pho.

After lunch, walk to the top of Primrose hill for one of the best views of the whole city. On the way back to the tube, stop for a pint or two outside The engineer or The queens.

I’d suggest a rest at this point so you can make the most of your evening. For dinner book Latium and have cocktails before/after at the Sanderson.

You are on your own for the evening. I don’t really do clubbing any more, but the one piece of advice I give is don’t just wander to Leicester square and choose a venue, there are some absolute hovels. If you are just after a few more drinks after dinner I like the bar at the Charlotte street hotel.

Sunday morning, make sure you enjoy a full English breakfast to start your day. Your hotel probably serves one and to be honest there isn’t any particular culinary skill involved in making one so it is hardly worth hunting down an ‘authentic greasy spoon’ cafe.

Get a tube to Westminster and walk over the bridge enjoying the uber tourist views of Big ben and the houses of parliament. Get a boat from Waterloo pier next to the London eye to Bankside pier, browse Tate modern for a while then cross the river using the millennium foot bridge, head up to St. Pauls Cathedral and check out thewhispering gallery.

Make sure you use the Thames Clippers commuter boats. The tourist boats are over priced and very slow.

Back on the boat to Greenwich, from Blackfriars pier. Walk through the grounds of the naval college and into the park, up to the observatory for another view over London. If you have time check out the three markets in Greenwich.

Finish your trip with a late Sunday roast and a beer at the Plume of feathers (you’ll need to book a sitting at 2 or 4pm). Get on the DLR and head back to city airport!

That is just one of many ways of spending a weekend in London. I missed out Fish and Chips, some great markets and many of my favourite pubs simply because of time constraints. I also tried to leave plenty of spare time between my recommendations so you can wander off the beaten track and discover your own London – in my experience, just wandering is one of the true joys of travel.

My final tip, here is what  to avoid. Leicester Square, Theatre Land, The London eye, Buckingham palace. Some Londoners may passionately disagree, but I think you’d be wasting valuable time.

So, if you are reading this and thinking of visiting, enjoy my city. Arguably the greatest on earth.

 

Windows Service

I need to generate a Windows Service application, I’ve done this before, but could I remember how to do it. ¬†In my searching I found this code sample very useful¬†Creating a Basic Windows Service in C# on The Code Project

WindowsService_Src

 

Another useful article I found was from Microsoft Windows Services: New Base Classes in .NET Make Writing a Windows Service Easy

 

Caching from a non Web applications

Okay you are developing a WinForm application and you are looking at performance, one area is Caching of information, but wait a minute I’ve been using caching in my web applications for sometime, but how do you do it from a WinForm application as you don’t have a host to store your cache.

Would you know it you can use the web cache too, just you have to take a few extra steps to retain your cache, either in memory or in temporary files.

You can use the HttpRequest to store the System.Web.Cache objects in your application, and this works well.

I also came across any Blog, providing another method to Caching, however I have a little concern over this method of caching in files as you are likely to get file locking.

Using System.Web.Caching From The Console Or Windows Forms

I’ve written my own simple VB.NET application to show it working and just holding the Cache in memory for the life of the application.

WinFormCache.zip (17.73 kb)

Of course you could run a Windows Service which holds all the Cache information, this way it will be available to all your WinForm applications should you require it.

StructureMap Example

After using StructureMap for a while I thought it would be nice to generate a simple example of how it all works, so I’ve built in Visual Studio 2008, both C# and a VB.NET version.

StructreMap Example.zip (4.47 kb)

StructureMapExampleVB.zip (9.41 kb)

For more information on StructureMap please go to their main website

If you need to know more about IoC’s then it’s worth making a look at the following links:

Inversion of Control

List of .NET Dependency Injection Containers (IOC)

IoC Benchmarks

MVC Storefront: Dependency Injection

NinJect

Small free and replacement for Notepad

Do you still use Notepad that ships with Windows?

I did, until I found NotePad2, it’s fast, it’s easy to use, and more to the point it works.

I’ve been using it for the past 2 months, and I have not got any clue to the features, but what I like about it is it just works and is a very good replacement for the standard Windows Notepad. 

Here are the features, cribbed from the NotePad2 Website:

Customizable syntax highlighting: 

  • HTML, XML, CSS, JavaScript, VBScript, ASP, PHP, CSS, Perl/CGI
  • C/C++, C#, Java, VB, Pascal, Assembler, SQL, Python, NSIS
  • INI, REG, INF, BAT, DIFF
  • Drag & drop text editing inside and outside Notepad2
  • Basic regular expression search and replace
  • Useful word, line and block editing shortcuts
  • Rectangular selection (Alt+Mouse)
  • Brace matching, auto indent, long line marker, zoom functions
  • Support for Unicode, UTF-8, Unix and Mac text files
  • Open shell links
  • Mostly adjustable
  • Auto indentation
  • Bracket matching
  • Encoding conversion between ASCII, UTF-8 and UTF-16 formats
  • Multiple undo/redo; rectangular block selection
  • Newline conversion, between DOS (CR/LF), Unix (LF) and Mac (CR) formats 

How to Replace notepad with notepad2 in Vista?

  1. First you need to download notepad2 from here
  2. First you need to Rename Notepad2.exe to notepad.exe.
  3. Find c:\windows\notepad.exe and c:\windows\system32\notepad.exe and set the owner to ‘Administrators’, and grant Administrators full control.
  4. Using Windows Explorer, drag and drop the renamed notepad2.exe to c:\windows and c:\windows\system32.
  5. Optional replace the permissions on the new notepad.exe to Read & Execute and Read.
 
Another one to look at is Notepad++, it has a lovely set of plugins such as XML have a look at Tim Almonds post on the XML plugin