Monday, 7 March 2011

Nhibernate, Unit Of Work, Repository and StructureMap

This could be a long blog...

Well I have spent some time recently trying to understand how to tie all this lot together and I think I have finally cracked it in its simplest form, I am hoping at least. This is my first stab at it and I am already thinking of changing it slightly, but I want to show what I did first.
If there is anything you don't like on here or want to question please come and comment as I would love to get some feedback on what people thought of this. Problematic, see problems with it or even helped to understand it better.

NHibernate
So first of all I modelled a simple domain, just an account user and mapped this to NHibernate to do its thing with the db. Understood then that the NHibernate's SessionFactory should be once per application as its very expensive to create and that ISession is what to use every time you want to make a single or group of changes to the db, or to just retrieve anything.

Code that I Wanted/Needed
So the following are the general things I used and set up simply as possible for now.

Repository
First off I read up loads of articles on creating a repository to wrap up simple NHibernate commands. This could be extended in the future to provide a more advanced implementation. Some would argue not to have the repository at all and use the NHibernate calls directly. I like the idea of keeping the repository implementation as I am hoping it decouples NHibernate from the application (don't know why I will ever need to not use NHibernate yet but its there). I would like to be able to create as many of these as I would like although at the moment I am unsure why I would need more than 1 per thread. This will contain a UnitOfWork.

    5     class Repository : IRepository
    6     {
    7         readonly IUnitOfWork _unitOfWork;
    8 
    9         public Repository(IUnitOfWork unitOfWork)
   10         {
   11             _unitOfWork = unitOfWork;
   12         }
   13 
   14         #region IRepository<AccountUser> Members
   15 
   16         public T GetById<T>(Guid id)
   17         {
   18             return _unitOfWork.CurrentSession.Get<T>(id);
   19         }
   20 
   21         public void Add<T>(T entity)
   22         {
   23             _unitOfWork.CurrentSession.SaveOrUpdate(entity);
   24         }
   25 
   26         public void Remove<T>(T entity)
   27         {
   28             _unitOfWork.CurrentSession.Delete(entity);
   29         }
   30 
   31         #endregion
   32     }


UnitOfWork
This implements IDisposable and is what I used to manage the transaction of the NHibernate session. I would like it to dispose of the session once its been commited or rolledback, it just has a simple commit and rollback and manages to close the session. The session and transaction is created in the constructor here, so the UnitOfWork is ready to be commited or rolledback. The more I am typing here the more I am feeling this class is clunky around the edges of cleaning up. I am not sure if I need to rollback the transaction by default in the dispose if its active already, or whether the Session manages maintains that on a dispose of itself? If anyone knows let me know :-)

    6     public class UnitOfWork : IUnitOfWork
    7     {
    8         private readonly ISessionFactory _sessionFactory;
    9         private ISession _currentSession;
   10         private readonly ITransaction _currentTransaction;
   11 
   12         public UnitOfWork(ISessionFactory sessionFactory)
   13         {
   14             _sessionFactory = sessionFactory;
   15             _currentTransaction = CurrentSession.BeginTransaction();
   16         }
   17 
   18         #region IUnitOfWork Members
   19 
   20         public ISession CurrentSession
   21         {
   22             get { return _currentSession ?? (_currentSession = _sessionFactory.OpenSession()); }
   23         }
   24 
   25         protected ITransaction BeginTransaction()
   26         {
   27             return _currentSession.BeginTransaction();
   28         }
   29 
   30         public void Commit()
   31         {
   32             if (_currentTransaction.IsActive)
   33                 _currentTransaction.Commit();
   34         }
   35         public void Rollback()
   36         {
   37             if (_currentTransaction.IsActive)
   38                 _currentTransaction.Rollback();
   39         }
   40 
   41         #endregion
   42 
   43         #region IDisposable Members
   44 
   45         public void Dispose()
   46         {
   47             if (_currentSession == null) return;
   48 
   49             _currentSession.Dispose();
   50             _currentSession = null;
   51         }
   52 
   53         #endregion
   54     }

As you can probably see there is no creation of the interfaces SessionFactory or UnitOfWork in repository and this is where I have used StructureMap to help out.

StructureMap
I went the Ninject route initially as it had a cool looking site and seemed quite nice to use also. I managed to achieve what I wanted with it and it wasn't difficult at all but I wont show that here. I researched further into which DI/IOC to use and I kind of had a good feel for what people were saying about StructureMap so I changed to use StructureMap instead.
OK so I figured I needed
  • 1 SessionFactory per application running.
  • 1 UnitOfWork per thread running.
  • No limit to the number of Repositories. (not sure why this can't be 1 instance per thread also but I don't think there is harm in having more than 1 as it will use the same UnitOfWork if its in the same thread.)
    9    public static class ContainerBootstrapper
   10     {
   11         public static void BootstrapStructureMap()
   12         {
   13             ObjectFactory.Initialize(x =>
   14             {
   15                 x.ForSingletonOf<ISessionFactory>().UseSpecial(y =>
   16                     y.ConstructedBy(context =>
   17                     {
   18                         var nhConfig = Fluently
   19                          .Configure()
   20                          .Database(MsSqlConfiguration
   21                                     .MsSql2008
   22                                     .ConnectionString(connstr =>
   23                                         connstr.FromConnectionStringWithKey("db")))
   24                          .Mappings(mappings => mappings
   25                                                 .FluentMappings
   26                                                 .AddFromAssemblyOf<AccountUser>())
   27                          .BuildConfiguration();
   28 
   29                         return nhConfig.BuildSessionFactory();
   30                     }));
   31                 x.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<UnitOfWork>();
   32                 x.For<IRepository>().Use<Repository>();
   33             });
   34         }
   35     }
So in here, I am setting up the
  • 1 single SessionFactory ever for the application. The x.ForSingletonOf<ISessionFactory> will sort this out. It uses the Fluent style configuration of the sessionFactory using the database connection and mappings from the domain model set up.
  • Per thread UnitOfWork, we want this as we may have more than 1 save, update and delete on the same transaction, so when its injected into the repository its the same UnitOfWork that is used before the repository has begun to be used, I will show a test later on with this.
  • Repository.
A Couple of Tests
I will try and show a couple of tests that I set up for this, and show how it could be used from the outside. I hope my tests aren't too bad, I know I find it difficult to write a good test, come slate them let me know what you would do, naming them something different? anything? I need to learn more about tests.

Test to write data to the database was successful.
   67         [TestMethod]
   68         public void Can_SaveSomeUserDataViaStructureMap()
   69         {
   70             ContainerBootstrapper.BootstrapStructureMap();
   71 
   72             using (var uoW = ObjectFactory.GetInstance<IUnitOfWork>())
   73             {
   74                 var repo = ObjectFactory.GetInstance<IRepository>();
   75                 var newUser = new AccountUser
   76                                   {
   77                                       Name = "Test",
   78                                       Email = "Email Test",
   79                                       Password = "Password Test"
   80                                   };
   81                 var newUser2 = new AccountUser
   82                                    {
   83                                        Name = "Test2",
   84                                        Email = "Email Test",
   85                                        Password = "Password Test"
   86                                    };
   87                 repo.Add(newUser);
   88                 repo.Add(newUser2);
   89 
   90                 uoW.Commit();
   91 
   92                 //Clear the session so its forced to go to the database and not pull from the cache
   93                 uoW.CurrentSession.Clear();
   94 
   95                 var returnedAccountUser = repo.GetById<AccountUser>(newUser.Id);
   96                 Assert.AreEqual("Test", returnedAccountUser.Name, "Failed to get user from database.");
   97             }
   98         }

so this test was to tell me that I could write more than 1 thing to the database at the same time on the same UnitOfWork. I did use the nhibernate profiler to spy on a little of what was going on here, which may I add is superb, easy to use, understand and set up. Going back to the test though, the UnitOfWork and StructureMap did their job nicely and only created one of them. One UnitOfWork was created as part of the 'using' and the one that was injected into the Repository creation (on line 74 of the test) was the same one. Superb! The data was added, the UnitOfWork commited and job done. I cleared the session at this point to force nhibernate to fetch the data from the database again rather than retrieve it from its cache.

Test to prove that there was a different UnitOfWork created when created in another thread.
  110        [TestMethod]
  111         public void Must_HaveNewSessionPerUoWPerThread()
  112         {
  113             ContainerBootstrapper.BootstrapStructureMap();
  114             //Create this instance on this thread.
  115             var uoW = ObjectFactory.GetInstance<IUnitOfWork>();
  116             IUnitOfWork uoW2;
  117 
  118             var thread = new Thread(x =>
  119             {
  120                 uoW2 = ObjectFactory.GetInstance<IUnitOfWork>();
  121                 Assert.AreNotSame(uoW, uoW2);
  122                 Assert.AreNotSame(uoW.CurrentSession, uoW2.CurrentSession);
  123             });
  124             thread.Start();
  125         }
with this test I am thinking along the lines I could use the UnitOfWork per HttpRequest using MVC some where along the lines, creating the UnitofWork in ActionExecting maybe and the commit/rollback on what ever the opposite one is. When I get to working that out I will post that next I think.

Changes I would like to make for an MVC web application.
I will get round to bloging what I did for this, but for short I am considering removing the UnitOfWork and Repository all together and let StructureMap create the Session and inject it into the controller constructors when they are created, but my only hesitation in this is that it will couple NHibernate to the controllers as they will need an ISession injected into them and also need to manage the Transaction.

Monday, 28 February 2011

Just a quick fix, just a quick fix, boom! Game Over Man!... Game Over...

What are these quick fixes? Are they the start of the end? Or is it already too late, as when you've found there are a few quick fixes, does that mean there are thousands of them in already, more than likely yes!

What causes them?

  • Friday afternoon? 
  • No time as other things are important to get done? But what is more important than the current fix you are doing, if you have to rush it to get onto something else, then don't do it!
  • Because it doesn't break any unit tests? Are then the tests written correctly, if they are stopping quality being writing?
  • Is it the lack of pride and care in what one is doing, or any thought for one's colleagues as one is not going to be around long enough when these fixes come back to bite you in the ar!*e!

All these questions and no answers, not sure I can give any answers yet, but if I find some I will surely post back here.

Is this what agile is? Do a fix in the first place you can see the easiest place? Or is it to refactor code into the correct places to fix the issue, maybe its neither?

What do the sum of these quick fixes add up too? I tell you what! A bloody mess of looking at random, undocumented code here, there and everywhere, slow down of progress, and skewed estimations. Code spread, where these fixes are not structured in the correct layer! More than likely more fixes will be required to fix the fixes! Superb! That's some special mess!

Are developers being continuously squeezed to write code to be “finished” rather than “completed with quality”? Or do developers wear blinkers and only see progress as a happy product owner? Is there a way to prove this?

Time is always squeezed and quality drops! This will inevitably get worse over time ‘Mr Anderson’…
Well commented code, we hopefully don’t need too most of the time (well you shouldn't so much) as the code is readable (isn't it, you good coders you), but the more quick fixes (I suspect highly uncommented)… ...who knows what randomness is being produced.

I guess there is a time line where the quick fix is fine, for a small, completed, un-evolving project. Are there such projects, really?


I recently came across an interesting article and I haven't looked into it yet, but could be very interesting. Convincing team members that something is a good idea.

Saturday, 26 February 2011

Calling all Devs, Calling all Managers (if that's what you can call them)

Seriously! The guys in my links need to be followed by all Devs and Managers especially. I've only just started doing this reading myself, but quickly realising that these guys are well worth reading.

Just read them, they are not big articles. They make a lot of sense and are very experienced people, so why wouldn't we want to listen to them absolutely confuses me.

Its probably wise to be spending some time, reading at least one article a day, and/or learning one new feature of a piece of software that we use every day/week. Visual Studio or Resharper or maybe some software framework you are using, automapper, nhibernate, etc. I am trying to do this but not religiously yet. I will get there.

I have also just been recently told that  looking at somebody elses source code once a week, also helps. I have not done this yet but I think I am going to start. I'm going to start with Jimmy Bogard's Automapper. Take a look around see how he does things, learn any ideas from it hopefully and also how he writes his code and his unit tests, especially his unit tests as I'm finding this difficult to understand how these are meant to be written at the moment.

If I learn something I will report back on my blog some where hopefully.
I think I hear you ask where the hell do you get the time to do any of this, well don't worry I am also asking myself this question, and now I am writing a blog too! I still want to do all the above and more...

I'll be adding more links to articles I find in here and to 'My Links' also.

Hope you find something useful from this, or if you have any more useful links, let me know and I'll have a read and add them :-)

Some links...

Stand Up Meetings
http://codebetter.com/jameskovacs/2011/03/28/stand-up-meetings-are-about-more-than-standing/

Martin Fowler
http://martinfowler.com/bliki/TradableQualityHypothesis.html
http://martinfowler.com/bliki/TechnicalDebt.html

Friday, 25 February 2011

42, 1, 0, temp1, fred, squid, WTF!

STOP IT! STOP IT! STOP IT!

Seriously what do these numbers mean to anyone else looking at your code, or in fact to yourself when you come back in a week or two (in my case a day)?

Damn magic numbers and random variable names, awesome tactics if you want to spend time looking at the same code day in and day out trying to figure out what they mean, especially when the same number means two different things in the database or even three. Genius!

Use an enum damn it! Give those numbers meaning! Tell me what they are! Tell yourself what they are! Rather than me/you hunting through the damn code to try and work out what they mean!

Name your variables something useful, and your methods too!

not so nice way...

   15         public void CheckEngineManagement()
   16         {
   17             //Call something to get the data of the engine.
   18             var engineData = GetEngineData();
   19 
   20             if (engineData.State > 0)
   21             {
   22                 if (engineData.State == 1)
   23                 {
   24                     //Do some engine checks for oil,
   25                     //seatbelt checks etc, blah blah,
   26                     //or something else
   27                 }
   28             }
   29         }

I seem to be stuck in the car world at the moment, I will have to think of some better examples.
So there are the different types of EngineData coming back from the database, all in the same table with a column to state the different type. Maybe bad maybe not, but I am trying to find an example.

I get my engine data back for a particular car, ferrari engineData, superb, then I do a check on the State if it's less than zero don't do anything, if it's 1 then do something. IF IT'S 1, IF IT'S 0 WTF does that mean? The door is open, ignition is on, car started, what!? Especially for different engine data 1 could mean something else and it probably does when written magically!

nicer way hopefully...

    8     public enum CarState
    9     {
   10         CarLocked,
   11         PassengerOpen,
   12         DriverDoorOpen,
   13         KeyInIgnition,
   14     }


   23         public void CheckEngineManagement()
   24         {
   25             //Call something to get the data of the engine.
   26             var engineData = GetEngineData();
   27 
   28             if (engineData.State != CarState.CarLocked)
   29             {
   30                 if (engineData.State == CarState.DriverDoorOpen)
   31                 {
   32                     //Do some engine checks for oil,
   33                     //seatbelt checks etc, blah blah,
   34                     //or something else
   35                 }
   36             }
   37         }

Ignore the nasty if nesting, I will have to think of a better example, but I can't at the moment I am fuming!
I have taken away all the nasty numbers, now you can read that the car is locked or the driver door is open and see what its trying to do and why its doing its checks for oil, seatbelt checks etc. not having to spend a larger amount of time understanding the whole code to work out what the numbers are and why they are there!

Sooner or later those ifs would have ended up all over the place nested like crazy with a mix of the engine data type amongst it all no doubt, can you imagine trying to read all that lot with just numbers?

Give me a slap for nesting if's like that, probably could have used a switch or probably even something else. Or suggest a better idea for my demonstrations. Or just a slap anyway. I am just trying to get some of the simpler things across at the moment.

Thursday, 24 February 2011

Polymorphism, really... what's that...? omg you need a slap in the face!

Well it begins...
Before I start I have to admit I am also guilty of this but it needs to come out.

Why the hell do I have to see code with 4 million if and switch statements, especially when its switching or if'ing on an enum called <some name>Type and of course to get me more mad, yes its in the base class too, what a genius, what the hell are you doing!

Yes that's right, it even has the postfix of "Type", surely that has to give some kind of clue, that hmmmm, maybe this enum your switching on, shouldn't be there, and yes you can do it without having to switch, that's what polymorphism helps with, let me try to demonstrate...

Its not a superb example, but its the first thing I could think of, hopefully I can change it to something better when I can think of something, but for now I am hoping I can get some of the point of polymorphism across.

not so nice way...
    8     public enum CarType
    9     {
   10         Ferrari,
   11         MorrisMinor,
   12         SomethingElse
   13     }
   14 
   15     public class Car
   16     {
   17         public CarType CarType { get; set; }
   18 
   19         public void StartCar()
   20         {
   21             switch (CarType)
   22             {
   23                 case CarType.Ferrari:
   24                     //Car Senses key fob.
   25                     //Car starts.
   26                     break;
   27 
   28                 case CarType.MorrisMinor:
   29                     //Key fob turned.
   30                     //Car starts.
   31                     break;
   32 
   33                 case CarType.SomethingElse:
   34                     //Some random stuff to get this car to start
   35                     break;
   36 
   37                 default:
   38                     //Do some default stuff to start all other cars.
   39                     break;
   40             }
   41         }
   42     }
   43 
   44     public class Ferrari : Car
   45     {
   46         public Ferrari()
   47         {
   48             CarType = CarType.Ferrari;
   49         }
   50     }
   51 
   52     public class MorrisMinor : Car
   53     {
   54         public MorrisMinor()
   55         {
   56             CarType = CarType.MorrisMinor;
   57         }
   58 
   59     }
   60 
   61     public class SomethingElse : Car
   62     {
   63         public SomethingElse()
   64         {
   65             CarType = CarType.SomethingElse;
   66         }
   67 
   68     }
   70 
   71     //Some code somehwere to start the car you have.
   72     var ferrari = new Ferrari();
   73     var morrisMinor = new MorrisMinor();
   74     var somethingElse = new SomethingElse();
   75     ferrari.StartCar();
   76     morrisMinor.StartCar();
   77     somethingElse.StartCar();

So this has the 3 types of cars, and they all should start in a different way. When you create an instance of these cars and call StartCar they all call the same method, which then switches on some dodgy enum to distinguish the types, pffff.

OK it works but a car doesn't need to ask itself if its a ferrari, or a morris minor. What happens if a new car comes out does that mean all the other cars then need to be upgraded to then ask itself if its the new car on the market? Therefore, increasing the switch/if statement every time. Sounds like that could be a nightmare to me.

a nicer way...

    8     public class Car
    9     {
   10         public virtual void StartCar()
   11         {
   12             //Do some default stuff to start all other cars.
   13         }
   14     }
   15 
   16     public class Ferrari : Car
   17     {
   18         public override void StartCar()
   19         {
   20             //Car Senses key fob.
   21             //Car starts.
   22         }
   23     }
   24 
   25     public class MorrisMinor : Car
   26     {
   27         public override void  StartCar()
   28         {
   29             //Key fob turned.
   30             //Car starts.
   31         }
   32     }
   33 
   34     public class SomethingElse : Car
   35     {
   36         public override void  StartCar()
   37         {
   38             //Some random stuff to get this car to start
   39         }
   40     }
   41 
   42 
   43     //Some code somehwere to start the car you have.
   44     var ferrari = new Ferrari();
   45     var morrisMinor = new MorrisMinor();
   46     var somethingElse = new SomethingElse();
   47     ferrari.StartCar();
   48     morrisMinor.StartCar();
   49     somethingElse.StartCar();        


Ok here I have completely removed the enum, as its completely not needed. We already have the type, its a Ferrari, or MorrisMinor, the base class (Car) doesn't care.

I have made the StartCar method a virtual method so all the base classes can now implement their own implementation, they have the knowledge on how to start themselves. So if a new car comes along they can then implement their own StartCar method, and no other car needs to know about it. If StartCar isn't implemented then the default one in the base class will be used.

Look no more switch or if, its all gone. You now don't need to read complex code, well it wasn't complex as it was but when new types start appearing it will creep in there.

I hope my explanation makes some sense, if you like, don't like, or would like to suggest something, let me know either way, or of course just slap me! I am learning here too :-) I think I can probably go into some more depth on how it works but at the moment I think I will leave that for now, hopefully there is enough there to understand the basics of getting rid of them nasty if's and switches.

I am not sure if there is any kind of excuse to have to do the "not so nice way...", maybe I am missing something, but I know its easily done, done it myself. Maybe its a lack of time and pressure and your brain only thinks like a 'C' coder in straight lines (sorry 'C' coders out there I used to be one too, very long time ago, and if I am wrong there, please tell me and give me a slap!). I really don't know as I am sure the second way is actually less code and thinking.

That's another thing what gets on my tits too is seeing OO code written like 'C' (before I explode screaming, I will have to save that for another blog)

Hmmmm, I wonder if its possible to write code without if's, yes ban them, maybe bring a flag out in the compiler you can turn them off! I think that's another post rant too.

I can't believe I keep generating new ideas for a blog post without having even thought about it before. This bloging/ranting is superb! I recommend you try it.

Hopefully I will get to some more complex things in the future, but I guess I am learning to write too at the moment.