Russell East's blog

thoughts |> share |> ignore

  • I have come across a common scenario while developing an ASP.NET MVC application. This being testing Actions that require the user to be authorised and / or requires permissions to execute methods  that are locked down with principal permissions.

    Here as an example of a controller with an action that is firstly decorated with the “Authorize” attribute (ASP.NET MVC filter) that requires the user to be in a specified role.

    [Authorize(Roles="Client Administrators")]
    public ViewResult Edit(int clientId)
    {
        return View("Edit");
    }

     

    While I was writing a test for an Action that needed the user to be Authorized . I   created implementations of the IIdentity and IPrincipal interfaces that I could use to satisfy this requirement. Although this worked, it was not reusable. When you set principle, you should apply it to the current AppDomain instead of the current thread as the every thread created in your AppDomain will have the principal set automatically. Once you have set the principle you cannot apply my than once as it will throw an exception. It is also a problem is you try to reset the principal to null.

    To add to matters, is was not long before I needed to satisfy principal permissions. My Principal and Identity implementations needed to be more flexible.

    So the answer was to create a utility that firstly set the AppDomain to use my principal implementation and allow each and every test to arrange the state of the principal. For each and every test  I also want to write the minimum amount of code by only writing one line of code.  This line of code would be amongst NBehave and RhinoMocks code that have their own fluent interfaces so I want my line of code to fit in with the fluent style. Below are three ways I want to my utility.

    //1
    TheCurrentUser.Instance.IsAuthenticated().And.IsInAllRoles();
     
    //2
    TheCurrentUser.Instance.IsAuthenticated()
        .And.IsInThisRole("System admins")
        .And.IsInThisRole("developers")
        .And.IsInThisRole("power users");
     
    //3
    TheCurrentUser.Instance.IsNotAuthenticated();

     

    So I started to create this utility by placing its into its own assembly. The root object is the “TheCurrentUser” object. Its the only public class in the assembly and is used as  a singleton. It creates and hosts three objects references and sets the IPrincipal implementation to the current AppDomain.

    using System;
    using System.Security.Principal;
     
    namespace RussellEast.Principal.Utility
    {
        public class TheCurrentUser
        {
            static readonly TheCurrentUser instance = new TheCurrentUser();
     
            private IPrincipal principal;
            private IAuthenticationOptions options;
            private ISecurityContext context;
     
            private TheCurrentUser()
            {
                BuildObjectGraph();
                SetAppDomainPrincipal();
            }
     
            static TheCurrentUser() { }
     
            public static IAuthenticationOptions Instance
            {
                get { return instance.Options; }
            }
     
            public IAuthenticationOptions Options
            {
                get { return options; }
            }
     
            private void BuildObjectGraph()
            {
                context = new SecurityContext();
                principal = new FakePrincipal(context);
     
                options = AuthenticationOptions.Create(context);
            }
     
            private void SetAppDomainPrincipal()
            {
                AppDomain.CurrentDomain.SetThreadPrincipal(principal);
            }
        }
    }

     

    The fluent interface uses a context object (that holds the state as its passed around) that is injected into  various objects that are explained below. The context object implements the following interface.

    using System.Collections.Generic;
     
    namespace RussellEast.Principal.Utility
    {
        internal interface ISecurityContext
        {
            bool IsAuthenticated { get; set; }
            bool IsInAllRoles { get; set; }
            List<string> Roles { get; set; }
            void Reset();
        }
    }

     

    This is the concrete implementation of the ISecurityContext interface.

    using System.Collections.Generic;
     
    namespace RussellEast.Principal.Utility
    {
        class SecurityContext : ISecurityContext
        {
            public bool IsAuthenticated { get; set; }
            public bool IsInAllRoles { get; set; }
            public List<string> Roles { get; set; }
     
            public void Reset()
            {
                IsAuthenticated = false;
                IsInAllRoles = false;
     
                if (Roles != null)
                {
                    Roles.Clear();
                }
            }
        }
    }

     

    Back to the “TheCurrentUser” object, the instance property returns an object that implements the following interface below.

    (Although this object is a singleton, the pattern would be to return the singular  instance of the singleton, i have not done this as the singleton does nothing but host objects and be the root object for the fluent interface.)

    namespace RussellEast.Principal.Utility
    {
        public interface IAuthenticationOptions
        {
            IAuthorisationRouter IsAuthenticated();
            void IsNotAuthenticated();
        }
    }

     

    My concrete of the above  interface is as follows:

    namespace RussellEast.Principal.Utility
    {
        class AuthenticationOptions : IAuthenticationOptions
        {
            private readonly IAuthorisationRouter router;
            private readonly ISecurityContext context;
            private AuthenticationOptions(ISecurityContext context, IAuthorisationRouter router)
            {
                this.context = context;
                this.router = router;
            }
     
            public IAuthorisationRouter IsAuthenticated()
            {
                ChangeSecurityState(true);
     
                return router;
            }
     
            public void IsNotAuthenticated()
            {
                ChangeSecurityState(false);
            }
     
            private void ChangeSecurityState(bool isAuthenticated)
            {
                context.Reset();
     
                context.IsAuthenticated = isAuthenticated;
            }
     
            public static IAuthenticationOptions Create(ISecurityContext context)
            {
                var roleAuthorisation = new RoleAuthorisation(context);
                var router = new AuthorisationRouter(roleAuthorisation);
     
                return new AuthenticationOptions(context, router);
            }
        }
    }

     

    As you can see from the code, the AuthenticationOptions class is passed an instance of the security context and an instance of the IAuthorisationRouter.

    The responsibility of this class is to reset the context and set a new authentication value. This class also contains a “Factory Method” that is used to create an instance of this object.

    The “IsAuthenticated” method returns the next link in the method chain being the “IAuthorisationRouter”.

    namespace RussellEast.Principal.Utility
    {
        public interface IAuthorisationRouter
        {
            IRoleAuthorisation And { get; }
        }
    }

     

    The “IAuthorisationRouter” purpose in life is to provide a linkage in the method chain. Here is the concrete implementation.

    namespace RussellEast.Principal.Utility
    {
        class AuthorisationRouter : IAuthorisationRouter
        {
            private IRoleAuthorisationController roleAuthorisation;
     
            public AuthorisationRouter(IRoleAuthorisationController roleAuthorisation)
            {
                this.roleAuthorisation = roleAuthorisation;
                this.roleAuthorisation.Router = this;
            }
     
            public IRoleAuthorisation And
            {
                get { return roleAuthorisation; }
            }
        }
    }

     

    I am using constructor injection as much as possible. It was not so clear cut with this object as the AuthorisationRouter exposes an instance of “RoleAuthorisation” which implies that it has knowledge of it. The “RoleAuthorisation” exposes an instance of the AuthorisationRouter. So both need to know about each other.  I am using interfaces to define the overall fluent interface so I want to keep it clean from any implementation that is needed to wire references to together. So the solution is to create another interface that is only used by a specific consumer  (Interface Segregation Principal). Because I need two instances of different objects that need to know about each other, I have to construct one object first that then inject that into the other object when its be instantiated. Then I use a setter (setter injection) to provide the reference of the second object back to the first object.

    namespace RussellEast.Principal.Utility
    {
        internal interface IRoleAuthorisationController :
            IRoleAuthorisation, ISettableRouter
        {
        }
    }

     

    Here is the “ISettableRouter” interface:

    namespace RussellEast.Principal.Utility
    {
        internal interface ISettableRouter
        {
            IAuthorisationRouter Router { set; }
        }
    }

     

    Here is the “IRoleAuthorisation” interface.

    namespace RussellEast.Principal.Utility
    {
        public interface IRoleAuthorisation
        {
            void IsInAllRoles();
            IAuthorisationRouter IsInThisRole(string role);
        }
    }

     

    I have a concrete class “RoleAuthorisation” that implements the “IRoleAuthorisationController” interface. Its responsibility is to manage the list of roles.

    using System.Collections.Generic;
     
    namespace RussellEast.Principal.Utility
    {
        class RoleAuthorisation : IRoleAuthorisationController
        {
            private IAuthorisationRouter router;
            private readonly ISecurityContext context;
     
            public RoleAuthorisation(ISecurityContext context)
            {
                this.context = context;
            }
     
            public IAuthorisationRouter Router
            {
                set { router = value;  }
            }
     
            public void IsInAllRoles()
            {
                context.IsInAllRoles = true;
            }
     
            public IAuthorisationRouter IsInThisRole(string role)
            {
                if (!string.IsNullOrEmpty(role))
                {
                    if (context.Roles == null)
                    {
                        context.Roles = new List<string>();
                    }
     
                    if (!context.Roles.Contains(role))
                    {
                        context.Roles.Add(role);
                    }
                }
     
                return router;
            }
        }
    }

     

    That’s all the interfaces and classes needed to build the fluent interface. The last objects needed is the Principal and Identity objects, which reads its values from the context.

    using System.Security.Principal;
     
    namespace RussellEast.Principal.Utility
    {
        class FakePrincipal : GenericPrincipal
        {
            private readonly ISecurityContext context;
     
            public FakePrincipal(ISecurityContext context) : base(new FakeIdentity(context), null)
            {
                this.context = context;
            }
     
            public override bool IsInRole(string role)
            {
                if (context.IsAuthenticated)
                {
                    return context.IsInAllRoles ? true : context.Roles.Contains(role);
                }
     
                return false;
            }
     
            class FakeIdentity : GenericIdentity
            {
                private readonly ISecurityContext context;
     
                public FakeIdentity(ISecurityContext context) : base("Fake user")
                {
                    this.context = context;
                }
     
                public override bool IsAuthenticated
                {
                    get { return context.IsAuthenticated; }
                }
             }
        }
    }

     

    Although a lot of code is written for the fluent interface which took two hours to build from scratch, I have a very flexible utility that I know I am going to use a lot and not just with ASP.NET MVC. The only refactoring that I want to perform is to change the name of some of the interfaces as I feel that they could be better described. To finish this post, here is an example using this utility in a unit test.

     

     
            [Specification]
            public void Should_be_able_to_edit_a_client()
            {
                ViewResult result = null;
     
                story.WithScenario("editing a client")
                    .Given("an instance of the controller", () => controller.ShouldNotBeNull())
                    .And("the current user belongs to the 'client administrators' role", () =>
                    {
                        TheCurrentUser.Instance.IsAuthenticated()
                            .And.IsInThisRole("Client Administrators");
     
                        //NOTE: these two lines are not needed, just  validating the utility.
                        Thread.CurrentPrincipal.Identity.IsAuthenticated.ShouldBeTrue();
                        Thread.CurrentPrincipal.IsInRole("Client Administrators").ShouldBeTrue();
                    })
                    .When("the Edit action is invoked", () =>
                    {
                        result = controller.Edit(1) as ViewResult;
                    })
                    .Then("verify that the user is directed to the right view", () =>
                    {
                        result.AssertViewRendered().ForView("Edit");
                    });
     
            }

     

    For a better understanding of the unit test above, please read this post

  • I have recently been going hammer and tongs with ASP.NET MVC. One of the selling points for ASP.NET MVC is its testability, so while I have been learning this technology, I have found a couple of annoyances.

    When you create a new ASP.NET MVC project, the wizard in VS2008 asks you if you want to create a test project. If you do create the test project, you get a couple of pre made tests that really don’t portray good TDD and because you only get a couple of tests, you have low code coverage and have untested code. I have had to back peddle  tests for the existing code.

    For doing any development with ASP.NET MVC, the MvcContrib project is an absolute must. The MvcContrib project contains general features that really improve your development, Dependency Injection, type safety, a Grid and much more. I found that the MvcContrib examples, are so straight forward that in 60 seconds of eyeballing the code I could understand it fully.

    Keeping to the subject, MvcContrib provides a library that really help when it comes to testing. I have been developing with MonoRail fairly solidly for the last 6 months or so and their are similarities between the Castle test classes and the Library from MvcContrib.

    To make things more real world:

    • My project is using Unity for its IoC container and I am injecting dependancies into my controllers (again the MvcContrib provides libraries that make this easy to implement). 
    • For writing my tests/specs, I am using NBehave, NUnit and RhinoMocks 3.5. 

    I started rewriting the tests for the HomeController because is was the easiest. The tests check that the controller displays the right view.

    using System.Web.Mvc;
    using RussellEast.Mvc.Controllers;
    using MvcContrib.TestHelper;
    using NBehave.Narrator.Framework;
    using NBehave.Spec.NUnit;
    using NUnit.Framework;
    using Specification = NUnit.Framework.TestAttribute;
    
    namespace RussellEast.Mvc.Tests.Controllers.Home
    {
        [TestFixture]
        public class When_displaying_home_pages : SpecBase
        {
            private HomeController controller;
            private Story story;
            private TestControllerBuilder builder;
    
            [Story]
            public override void MainSetup()
            {
                base.MainSetup();
    
                story = new Story("Home page");
    
                story.AsA("user")
                    .IWant("to go to the home page")
                    .SoThat("i can start using the application");
    
                PrepareController();
            }
    
            private void PrepareController()
            {
                builder = new TestControllerBuilder();
    
                controller = builder.CreateController();
            }
    
            [Specification]
            public void Index()
            {
                ActionResult result = null;
    
                story.WithScenario("home index page")
                    .Given("the controller has been prepared", () => controller.ShouldNotBeNull())
                    .When("the user navigates to the index view", () => result = controller.Index())
                    .Then("verify that the result is correct", () => result.AssertViewRendered().ForView("Index"));
            }
    
            [Specification]
            public void About()
            {
                ActionResult result = null;
    
                story.WithScenario("about page")
                    .Given("the controller has been prepared", () => controller.ShouldNotBeNull())
                    .When("the user navigates to the about view", () => result = controller.About())
                    .Then("verify that the result is correct", () => result.AssertViewRendered().ForView("About"));
            }
        }
    }

    The controller code is:

     

        public class HomeController : Controller
        {
            [Authorize, DefaultAction]
            public ActionResult Index()
            {
                ViewData["Title"] = "Home Page";
                ViewData["Message"] = "Sample text being displayed";
    
                return View("Index");
            }
    
            public ActionResult About()
            {
                ViewData["Title"] = "About Page";
    
                return View("About");
            }
        }

    Note: to order for the above tests to pass, you need to supply the name of the view to render.

    The tests above cover the behaviours for the HomeController which are very basic, so to raise the bar. The ASP.NET MVC project template comes with an AccountController that works with a membership provider and Forms Authentication. The controller has a constructor that accepts two parameters. Because the “System under test” is the Account Controller i am going to stub the dependencies and write tests for the “Login” and  “Logout” actions.

     

    using System.Web.Mvc;
    using System.Web.Security;
    using RussellEast.Mvc.Controllers;
    using MvcContrib.TestHelper;
    using NBehave.Narrator.Framework;
    using NBehave.Spec.NUnit;
    using NUnit.Framework;
    using Rhino.Mocks;
    using Specification = NUnit.Framework.TestAttribute;
    
    namespace EWS.Steeple.Tests.Controllers.Authentication
    {
        [TestFixture]
        public class When_authenticating : SpecBase
        {
            private AccountController controller;
            private IFormsAuthentication formsAuthentication;
            private MembershipProvider membershipProvider;
    
            private Story story;
    
    	[Story]
            public override void MainSetup()
            {
                base.MainSetup();
    
                story = new Story("Authenticating");
    
                story.AsA("known user to the system")
                    .IWant("to be authenticated")
                    .SoThat("i can use the system");
    
                PrepareController();
            }
    
            private void PrepareController()
            {
                TestControllerBuilder builder = new TestControllerBuilder();
    
                formsAuthentication = MockRepository.GenerateStub();
                membershipProvider = MockRepository.GenerateStub();
    
                controller = builder.CreateController(new object[] {formsAuthentication, membershipProvider});
            }
    
            [Specification]
            public void Should_log_in_with_user_name_and_password_while_not_caching_details()
            {
                string username = string.Empty;
                string password = string.Empty;
                bool rememberMe = false;
    
                ActionResult result = null;
    
                story.WithScenario("log in with validate details")
                    .Given("a controller instance", ()=> controller.ShouldNotBeNull())
                    .And("a user name", () => username = "Username")
                    .And("a password", () => password = "password")
                    .When("i attempt to log in", () =>
                    {
                        membershipProvider.Expect(x => x.ValidateUser(username, password)).Return(true);
                        formsAuthentication.Expect(x => x.SetAuthCookie(username, rememberMe));
    
                        result = controller.Login(username, password, rememberMe, string.Empty);
                    })
                    .Then("redirect user to the home page", () =>
                    {
                        result.AssertActionRedirect().ToAction(x => x.Index());
    
                        formsAuthentication.VerifyAllExpectations();
                        membershipProvider.VerifyAllExpectations();
                    });
            }
    
            [Specification]
            public void Should_sign_out_and_return_to_login_when_logging_out()
            {
                ActionResult result = null;
    
                story.WithScenario("log out and return to login view")
                    .Given("a controller instance", () => controller.ShouldNotBeNull())
                    .When("i log out", () =>
                    {
                        formsAuthentication.Expect(x => x.SignOut());
    
                        result = controller.Logout();
                    })
                    .Then("i expect to be sent to the login view", () =>
                    {
                        result.AssertActionRedirect().ToAction("Login");
    
                        formsAuthentication.AssertWasCalled(x => x.SignOut());
                    });
            }
        }
    }

    Some points to be aware of.

    • I have used two different ways to test the ActionResult was a redirect. The first and my preferred way is using the generic controller type and the lambda expression. I have been forced to use the string argument approach due to the fact that the “Login” action is overloaded. It complained when trying to use a lambda approach.;-(.
    • MvcContrib test library provides a “TestControllerBuilder” that not only creates that instance of the controller, but mocks out the HttpContext, Sessions and form data. The docs for MvcContrib explains all. I have used this in my “PrepareController” method. 
    • The default code in the AccountController has not been changed to suit these tests.
  • Introduction

    This is the first post of this series about implementing fluent finders and repositories, I am going to expand my current repository and finder implementation which is explained here. I recommend that you read this post (precursor) as this series continues on from this post and the code examples.

    The objectives for this series are:

    • Create a fluent interface on the finders
      • Chain the find methods so that you can find on more than one method (method chaining).
      • Create an interface for sorting.
      • Create an interface for paginating the results.
    • Allow a service request (coarse grain) to be mapped to a specific fluent-interface call.
      • Based on information provided to a service as a request object, determine the right strategy for satisfying the request.
      • Execute the relevant strategy to perform the relevant queries
      • Return the query results to service method that was called.
      • The service method will return results as a response object.
    • Drive out these behaviours using TDD/BDD.

    The outcome of this work will allow you write something like:

    repository.find.ByThis(somevalue).AndFind.ByThat(someOtherValue).SortBy(aField, InAscendingOrder).Paginate.WithPageSize(10).ShowPage(1);

    Before I start, one of the main benefits of a fluent interface is that you create an API that guides and limits the decisions that can be expressed in a logical order. So the interface needs to limit the options as the expression flows, which ultimately means you need to plan out the branching and the interfaces for each branch and decisions to ensure that public interface is meaningful to its context.

    Table of Contents

    Precursor

    Part 1  (this post)

    • Refactoring the existing interfaces to provide interface segregation.
    • The Query Command
    • Method Routing
    • Method Chaining

    Refactoring

    Following on from the precursor, I need to stop my “IApplicationUserFinder” from implementing the “IEntityFinder” interface. The reason for this is the the  “IEntityFinder” interface exposes a property called DataSource. The published Fluent interface will want to expose the Find methods but not the DataSource property. So a bit of interface segregation is needed here to expose the right interface to the relevant consumer. While doing this refactoring, I decided that the name of the “IEntityFinder” is not right so I have renamed it to “IQueryableDataStore”. Although I have changed these interfaces around my concrete class  ApplicationUserFinder still need to implement both. So I have created yet another interface called “IQueryableApplicationUserFinder” which implements the “IQueryableDataStore” and “IApplicationUserFinder” interfaces. Now the ApplicationUserFinder class just implements IQueryableApplicationUserFinder. If I have scrambled your brain up, hopefully the code snipets below will make things clear.

        public interface IQueryableDataStore where Entity : EntityBase // was IEntityFinder
        {
            IQueryable DataSource { get; set; }
        }
    ...
        public interface IQueryableApplicationUserFinder :
            IApplicationUserFinder,
            IQueryableDataStore
        {
        }
    ...
     public class ApplicationUserFinder : IQueryableApplicationUserFinder
    ...

    Now, how is this used. The ApplicationUserFinder is injected into the ApplicationUserRepository and then exposed via a getter (all by interfaces).  With the “IQueryableApplicationUserFinder” now in play, here is the revised code snippet for the repository (remember to change your IoC container to accommodate these changes).

        public class ApplicationUserRepository : EntityRepository,
            IApplicationUserRepository
        {
            private readonly IQueryableApplicationUserFinder finder;
    
            public ApplicationUserRepository(IPersistanceRepository repository,
                IQueryableApplicationUserFinder finder) : base(repository)
            {
                this.finder = finder;
    
                this.finder.DataSource = Query();
            }
    
            public IApplicationUserFinder Find
            {
                get { return finder; }
            }
        }

    At this point, all my unit tests pass and application runs the same as it did before this refactoring.

    The Query Command

    Regardless of the expression that you can write using the fluent-interface, it needs  an end at some point. The Query Command objects is responsible for executing the query and return the result. I am using “Linq for objects” to write my queries and passing an IQueryable around under the covers, the execution of the queries is deferred until a method is called on it like “ToList()”. Calling the “ToList()” method will execute the underlying query.  I have  created a command object (based on the command pattern) to expose an “Execute” method that is going to return an IEnumerable<Entity>. The reason for returning “IEnumerable<Entity>” is that you have a vast about of extension methods that you use to execute the query. For example “ToList()” and “FirstOrDefault”. We can create the Query Command now and integrate it into the fluent-interface later with out much effort.

        public interface IQueryCommand where Entity : EntityBase
        {
            IEnumerable Execute();
        }
    
        public class QueryCommand : IQueryCommand
        {
            private readonly IQueryableDataStore queryableDataStore;
    
            public QueryCommand(IQueryableDataStore queryableDataStore)
            {
                this.queryableDataStore = queryableDataStore;
            }
    
            public IEnumerable Execute()
            {
                return queryableDataStore.DataSource.AsEnumerable();
            }
        }

    So how can the fluent-interface get to this endpoint? Answer: we need an object to return it, so we can call it. I have defined this as “MethodRouter”.

    Method Router

    The method router exposes the actions that could be performed after a find method is called. As this is based on my previous post Implementing the Repository and Finder Pattern, I am going to change the original unit tests to drive out the method router. Here is the original specification for the “ApplicationUserFinder” class.

        [TestFixture]
        public class When_executing_queries_against_application_users
        {
            private ApplicationUserFinder finder; // subject under test
    
            [SetUp]
            public void Setup()
            {
                finder = new ApplicationUserFinder();
    
                finder.DataSource = GetStubbedCollection();
            }
    
            [Test]
            public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
            {
                ApplicationUser result = finder.ByLoginName("Test.User3");
    
                Assert.That(result.LastName, Is.EqualTo("User3"));
            }
    
            [Test]
            public void Should_return_a_user_by_token()
            {
                ApplicationUser result = finder.ByToken(Guid.Empty);
    
                Assert.That(result.LastName, Is.EqualTo("User2"));
            }
    
            [Test]
            [ExpectedException(typeof(ArgumentNullException))]
            public void Should_fail_if_supplied_null_login_name()
            {
                IQueryable users = GetStubbedCollection();
    
                ApplicationUser result = finder.ByLoginName(null);
            }
    
            private IQueryable GetStubbedCollection()
            {
                List users = new List
                {
                    new ApplicationUser { FirstName = "Test", LastName = "User1", LoginName="Test.User1", Token = Guid.NewGuid() },
                    new ApplicationUser { FirstName = "Test", LastName = "User2", LoginName="Test.User2", Token = Guid.Empty},
                    new ApplicationUser { FirstName = "Test", LastName = "User3", LoginName="Test.User3", Token = Guid.NewGuid()},
                    new ApplicationUser { FirstName = "Test", LastName = "User4", LoginName="Test.User4", Token = Guid.NewGuid()},
                    new ApplicationUser { FirstName = "Test", LastName = "User5", LoginName="Test.User5", Token = Guid.NewGuid()}
                };
    
                return users.AsQueryable();
            }
        }

    As you can see from the above tests, each find method returns the result as a single domain entity. I now want to return an interface of the Method Router instead. The Method Router at point will expose the QueryCommand so that I still execute the queries and keep the code in a “close to working” state at all times.

    To start with, I defined the MethodRouter interface “IApplicationUserFinderActions”

        public interface IApplicationUserFinderRouter
        {
            IQueryCommand Output { get; }
        }

    Now, I need to change the return types in the IApplicationUserFinder to now return the IApplicationUserFinderRouter instead.

        public interface IApplicationUserFinder
        {
            IApplicationUserFinderRouter ByLoginName(string loginName);
            IApplicationUserFinderRouter ByToken(Guid token);
        }

    At this point, things a little broken, so I need to change the concrete ApplicationUserFinder class to implement the changes made to the interface. To do this the concrete finder will need to know about the Method Router class. The method Router’s responsibility is to act as a hub to link object instances together. With this in mind, the MethodRouter class will need to know about the finder and the QueryCommand class. Still being mindful of the fluent interface and members it exposes, I need to ensure that the QueryCommand knows about the IQuerable instance held in the finder without coupling the objects together. To achieve this, I going to use the same technique I used in the Refactoring effort being the i return different interfaces to different parties. I have created another interface “IFindableApplicationUserFinderRouter” that implements IApplicationUserFinderRouter with an additional member.

    Here is the new interface

        public interface IFindableApplicationUserFinderRouter
            : IApplicationUserFinderRouter
        {
            IQueryableApplicationUserFinder Finder { get; set; }
        }

    Here is the concrete class ApplicationUserFinderRouter at this point.

        public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
        {
            private IQueryCommand queryCommand;
    
            public IQueryableApplicationUserFinder Finder { get; set;}
    
            public IQueryCommand Output
            {
                get
                {
                    if (queryCommand == null)
                    {
                        queryCommand = new QueryCommand(Finder);
                    }
    
                    return queryCommand;
                }
            }
        }

    Here is the changed ApplicationUserFinder

        public class ApplicationUserFinder : IQueryableApplicationUserFinder
        {
            private readonly IFindableApplicationUserFinderRouter router;
            private IQueryable users;
    
    	
            public ApplicationUserFinder(IFindableApplicationUserFinderRouter router)
            {
                this.router = router;
                this.actions.Finder = this;
            }
    	
    
            public IQueryable DataSource
            {
                get { return users; }
                set { users = value; }
            }
    
            public IApplicationUserFinderRouter ByLoginName(string loginName)
            {
                if (string.IsNullOrEmpty(loginName))
                {
                    throw new ArgumentNullException("loginName");
                }
    
    	    
                users.Where(u => u.LoginName == loginName).FirstOrDefault();
    
                return router;
            }
    
            public IApplicationUserFinderRouter ByToken(Guid token)
            {
                users.Where(u => u.Token == token).FirstOrDefault();
    
    		
                return router;
            }
        }

    Here is a snippet of how one of the unit tests is looking.

    	[SetUp]
            public void Setup()
            {
                router = MockRepository.GenerateStub();
    
                finder = new ApplicationUserFinder(router);
    
                finder.DataSource = GetStubbedCollection();
            }
    
            [Test]
            public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
            {
                ApplicationUser result = finder.ByLoginName("Test.User3").Output.Execute().FirstOrDefault();
    
                Assert.That(result.LastName, Is.EqualTo("User3"));
            }

    At this stage is hard to see the advantage of this apart from separating out code. The next step is to allow the find methods to be chained together (method chaining).

    Method Chaining

    The IApplicationUserFinderRouter interface is going to allow the finder to be returned from a property. This is pretty simple stuff. Below is the interface with the new property and the concrete class implementing this addition member.

        public interface IApplicationUserFinderRouter
        {
            IQueryCommand Output { get; }
            IApplicationUserFinder AndFind { get; }
        }
    
        public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
        {
            private IQueryCommand queryCommand;
    
            public IQueryableApplicationUserFinder Finder { get; set;}
    
            public IQueryCommand Output
            {
                get
                {
                    if (queryCommand == null)
                    {
                        queryCommand = new QueryCommand(Finder);
                    }
    
                    return queryCommand;
                }
            }
    	
            public IApplicationUserFinder AndFind
            {
                get { return Finder; }
            }
        }

    This now allows the find methods to be chained so you can write the following code

            [Test]
            public void Should_return_a_user_when_finding_by_Login_name_and_token()
            {
                ApplicationUser result = repository
                    .Find.ByToken(Guid.Empty)
                    .AndFind.ByLoginName("Test.User2")
                    .Output.Execute().FirstOrDefault();
    
                Assert.That(result.LastName, Is.EqualTo("User2"));
            }

    That concludes this post, the next part of this series will cover paginating the results returned from the underlying query.

  • I have my ever growing pet project that I have been playing about with for the last year. Its main purpose is a learning tool where I can try a few things out etc. I have been dabbling with the following view technologies.

    • WPF
    • Silverlight
    • Winforms
    • MonoRail
    • ASP.NET MVC

    A common saying I here a lot is ” One Architecture can not fit them all”, this is very true. I learnt a long time ago, that development is not about technology, its about principles and practices. I follow guidance from the OO and agile worlds. In these worlds, we have design patterns. The granddaddy pattern of them all is MVC. I have used MVC for years with varying technologies but mainly with winforms.

    Although MVC as pattern is not technology driven, its fare to say that you would want to get the best out of the view technology that you are using. To do this, you have to use an MVC variation/implementation that suits that technology. For example, the best technology on the list above for data binding is WPF, so if you want to lever the data binding in WPF then implement either the MVVM / Presenter Model, Supervising controller patterns.

    I started using WPF at first, and I admit, I got caught up in an implementation that brought the best out of WPF. I was quite pleased with myself. I used the MVVM pattern, used XAML throughout my views had no code behind (apart from implementing an interface so I could pull it from my IoC container).

    Then along come silverlight 2.0 and I thought I would have a play. In was not nice, downsizing the data-binding, lack of commands etc. Bottom line, its  another technology, I had to implement another variation of MVC to get the best out of silverlight. This was of course was not desirable.

    Although my project is purely for play time, I have no deadlines to meet, but I was getting frustrated with the little progress I have made over a number of weeks plus adding  up the learning time I was burning up with WPF and Silverlight. So I decided to help me bash some more code out and flush out my UI requirements I started to create my views in winforms. The tactic was to build a working prototype in winforms  and then revisit either silverlight or WPF at a later date and swap the views out.

    Now by this time, I did not want to use the data binding in winforms (another story). So crack open another MVC implementation, this time I favoured Passive view (MVP). I wanted to keep my views as dumb as possible (which is good goal to have) and drive my views and presenter logic out using TDD. I found this to be the quickest pattern to code. In this pattern, the presenter tells the view what to do via an interface that the view implements. Although this means putting code in the code behind, I found that I was only using one line of code in each method and using simple property getters and setters.

    On reflection of putting in winforms, I found that I was still getting the best from the technology and it felt cleaner. I am in good position now to plug in WPF again and keeping my presenters the same. But I have parked that idea for the time being while I build up some knowledge about ASP.NET MVC. I have been doing MonoRail development for the last 6 months so its not that strange to me.

    Question: Do I want to develop new controllers and actions in ASP.NET MVC or reuse my existing presenters? Answer: its worth a go, and see if I integrated them to work with each other 😉

    To conclude. The big thing that I have learned from this effort is to use the right patterns where needed and don’t be driven by technology, stick to patterns and concepts instead, because they last longer then any technology.

  • To follow on from my short and brief post nHibernate mapping files no more, I have implemented fluent-nhibernate very successfully and easily in my own application. In this example I am going to implement the ApplicationUser, Title and Role domain entities. All my entities derived from a abstract class called EntityBase. This base class is very little, it holds an Id (int) property and an abstract method “IsValid()”.

    public abstract class EntityBase
    {
        private int id;
    
        protected EntityBase() : this(0) { }
    
        protected EntityBase(int id)
        {
            this.id = id;
        }
    
        public int Id
        {
            get { return this.id; }
        }
    
        public abstract bool IsValid();
    }

    I will start with the simplest class first being the Title class.

    public class Title : EntityBase
    {
        public string Name { get; set; }
    
        public override bool IsValid()
        {
            return !string.IsNullOrEmpty(Name);
        }
    }

    Before I do the mapping for the title class, I need to put the mappings in the right place. I have a Repository layer that contains all my repositories for all of my root entities. All of my repositories inherit from “EntityRepository” which is has a dependency on an implementation of IPersistenceRepository. This is my own interface that does not expose any leaky abstractions from a technology like nHibernate.

    So getting to the point, I have an assembly called “RussellEast.Repositories” and a “RussellEast.Repositories.NHibernate” assembly which references the “RussellEast.Repositories” assembly as it holds the IPersistenceRepository interface. The “RussellEast.Repositories.NHibernate” has a class called “NHibernateRepository” which implements the IPersistenceRepository interface. The RussellEast.Repositories.NHibernate is the only assembly in my solution to know about nhibernate so I am going to place all my maps in this assembly under a folder called “Maps” and reference the Fluent-nHibernate assembly.

    To implement Fluent-nhibernate there is not a need to use the repository pattern, I am a big fan of DDD so I do. I just wanted to explain where I was going to place my mappings as I don’t want them in my core application or in my domain model.  For my information on how I have created my repositories, please read my previous post Implementing the Repository and Finder patterns.

    Enough with the ramblings, here is the mapping for the Title entity

    using FluentNHibernate;
    using FluentNHibernate.Mapping;
    using RussellEast.Domain.People;
    
    namespace RussellEast.Repositories.NHibernate.Maps.People
    {
        public class TitleMap : ClassMap<Title>
        {
            public TitleMap()
            {
                Id(x => x.Id).Access
                    .AsReadOnlyPropertyThroughLowerCaseField()
                    .GeneratedBy.Identity();
    
                Map(x => x.Name).CanNotBeNull().WithLengthOf(20);
            }
        }
    }

    If you can see from the TitleMap, I am mapping the Id to my Id readonly property in my EntityBase class that the Title entity derives from. The Fluent interface allows me to set up the access for nhibernate to populate it and generation for my Id. The Map method wires up the Name property and sets the field size and not null constaint. (sorry for stating the obvious).

    Now for the Role Entity.

    public class Role : EntityBase
    {
        public string Name { get; set; }
        public bool IsSystemRole { get; set; } 
    
        public override bool IsValid()     
        { 
            return !string.IsNullOrEmpty(Name);
        }
    }
    

    Not much different from the Title Entity, just the additional “IsSystemRole” property. Here is the mapping class.

    public class RoleMap : ClassMap<Role>
    {
        public RoleMap()
        {
            Id(x =>x.Id).Access
                .AsReadOnlyPropertyThroughLowerCaseField()
                .GeneratedBy.Identity();
            Map(x =>x.Name).CanNotBeNull().WithLengthOf(50);
            Map(x => x.IsSystemRole);
        }
    }
    

    This is similar to the TitleMap, so not much to learn here. So now to the ApplicationUser entity. An ApplicationUser is a person, i have other domain entities in my application that are people, so i have an Person entity.

    using System.Text.RegularExpressions;
    
    namespace EWS.Portcullis.Domain.People
    {
        public abstract class Person : EntityBase
        {
            private string email;
    
            public Title Title { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
    
            public string Email
            {
                get { return email; }
                set 
                {
                    if (IsEmailValid(value))
                    {
                        email = value;
                    }
                }
            }
    
            protected bool IsEmailValid(string value)
            {
                const string pattern = @"^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
    
                bool isValid = true;
    
                if (!string.IsNullOrEmpty(value))
                {
                    Regex regex = new Regex(pattern);
    
                    isValid = regex.IsMatch(value);
                }
    
                return isValid;
            }
        }
    }
    

    My ApplicationUser entity derives from Person

        public class ApplicationUser : Person
        {
            public string LoginName {get; set;}
            public int Salt { get; set; }
            public string Password { get; set; }
            public DateTime LastLoggedIn { get; set; }
            public Guid Token { get; set; }
            public IEnumerable Roles { get; set; }
    
            public override bool IsValid()
            {
                return (!(string.IsNullOrEmpty(FirstName) 
                    || string.IsNullOrEmpty(LastName)));
            }
        }
    

    My ApplicationUserMap looks like this.

        public class ApplicationUserMap : ClassMap
        {
            public ApplicationUserMap()
            {
                Id(x => x.Id).Access
                    .AsReadOnlyPropertyThroughLowerCaseField()
                    .GeneratedBy.Identity();
                Map(x => x.FirstName).CanNotBeNull().WithLengthOf(100);
                Map(x => x.LastName).CanNotBeNull().WithLengthOf(100);
                Map(x => x.Email).WithLengthOf(100);
                Map(x => x.LoginName).WithLengthOf(50);
                Map(x => x.Password).WithLengthOf(255); 
                Map(x => x.Salt);
                Map(x => x.LastLoggedIn);
                Map(x => x.Token);
                References(x => x.Title);
                HasManyToMany(x => x.Roles).AsBag();
            }
        }
    

    As you will see, I use the References method to map the Title association. As for Roles, I have an ApplicationUser that can belong to many Roles and a Role can have many ApplicationUsers. I define this association using the HasManyToMany method and set as “AsBag”. This works great as my Role property in the ApplicationUser is type of IEnumerable. This is nice side effect here is that I don’t have to have a specialised collection type like “ISet” in my domain layer.

    The final bit of code needed is to configure NHibernate which is shown in the code snippet below.

    private static readonly ISessionFactory sessionFactory;
    private ISession currentSession;
    
    static NHibernateSessionLocator()
    {
        sessionFactory = GetConfiguration().BuildSessionFactory();
    }
    
    private static Configuration GetConfiguration()
    {
         Configuration cfg = new Configuration().Configure();
    
         string mappingAssembly = ConfigurationManager
              .AppSettings["NHibernate.Mapping.Assembly"];
    
          var persistenceModel = new PersistenceModel();
    
          persistenceModel
               .addMappingsFromAssembly(Assembly.Load(mappingAssembly));
          persistenceModel.Configure(cfg);
    
          return cfg;
    }
            
    public ISession ActiveSession()
    {
         if (currentSession == null)
         {
             currentSession = sessionFactory.OpenSession();
         }
    
          return currentSession;
    }
    
    public void CloseActiveSession()
    {
    	...
    }
    
    public void UpdateDatabaseSchema()
    {
         Configuration cfg = GetConfiguration();
    
         SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);
    
         schemaUpdate.Execute(true, false);
    }
    

    The UpdateDatabaseSchema method is not part of my application but when i add a new entity and Map to my application i run this method from debug mode as it outputs the SQL DDL commands to the output window, which i use to create my tables. Here is a snippet of my application config file:

    <appSettings>
        <add key="NHibernate.Mapping.Assembly" 
            value="RussellEast.Repositories.NHibernate"/>
    </appSettings>
    

    Using fluent-nhibernate has made my life so much easier.  I applaud the developers that created this.

  • Introduction

    Over the last year I have been developing my own application using Domain Driven Design (DDD). I am also working on products in my day job that uses DDD. In the last month, myself and my fellow developers that I work with, went on a little journey to find the right way to implement the repository pattern including queries. My fellow devs and I wanted a solution to achieve the following goals:

    • A solid OO approach that was not bound to a specific technology. Meaning that we could develop this in C# or Java or what ever language.
    • No leaky abstraction. For example, we are using nHibernate at the moment, but in the future we might choose to use a different Object Relational Mapper (ORM). We don’t want our Repository or Finder interface to expose Nhibernate interfaces like “ISession” or “ICriteria”.
    • A repository per aggregate root.
    • No code duplication
    • Fully testable, driven out by our unit tests and me able to mock out the dependancies.
    • Friendly to our Inversion of Control (IoC) framework (ninject, spring.net and castle Windsor etc)
    • Provide a fluent interface to our repositories.

    None of us are new to the Repository pattern or ways to implement query objects, so we all have ideas and existing code for tackling this. Combined we come up with this.

    In my own application, my implementation used extension methods, its worked well, but because extension methods are static, i had no way of mocking them out  with Rhino mocks. This was not a showstopper, but meant that when i was writing unit tests in my service layer for example i have to set up the data to satisfy the logic in the extension methods.

    Throughout the rest of this post, i will be using code from my own application.

    The desired result


    Here is an example of how we intent to use our repositories:

    
    ApplicationUser user = applicationUserRepository
        .Find.ByLoginName(request.LoginName);
    
    

    As you can see the repository has a find property on it that exposes a  ByLoginName method that takes a string argument and returns a single ApplicationUser object.

    Entity Implementation


    The ApplicationUser is a Entity, all of my Entities inherit from a base class called EntityBase:

    public abstract class EntityBase
    {
        private int id; 
    
        protected EntityBase() : this(0) { } 
    
        protected EntityBase(int id)
        {
            this.id = id;
        } 
    
        public int Id
        {
            get { return this.id; }
        } 
    
        public abstract bool IsValid();
    
        ...
    }

    Not much to it this, all my entities have an identity and i want all my entities to be able to state if the data they contain is valid

    Repository Implementation

    All of my repositories extend a base IRepository interface.

    public interface IRepository<T> where T : EntityBase
    {
        T Get(int id);
        void Save(T entity);
    }

    As you can see the generic type is constrained by the EntityBase type. The IRepository interface is not used directly outside of my repository layer, but is extended by the typed Repository interfaces:

    public interface IApplicationUserRepository : IRepository<ApplicationUser>
    {
        IApplicationUserFinder Find { get; }
    }

    In my application, I use dependency injection so my repositories are injected using the typed interface.  IApplicationUserRepository has one member being the Finder interface (more on that below).

    One of my objectives was to remove duplicate code, in my effort to do this, i have an abstract class in which all my repositories inherit from.

    public abstract class EntityRepository<T> : IRepository<T> where T : EntityBase
    {
        protected readonly IPersistanceRepository repository;
    
        public EntityRepository(IPersistanceRepository repository)
        {
           this.repository = repository;
        }     
    
        public virtual T Get(int id)
        {
           return repository.Get<T>(id);
        } 
    
        public virtual void Save(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            } 
    
            if (entity.IsValid())
            {
                 repository.Save(entity);
            }
        } 
    
         protected IQueryable<T> Query()
         {
             return repository.Query<T>();
         }
    
     }

    This class must be supplied an instance of IPersistanceRepository.  Here is the IPersistanceRepository interface

    public interface IPersistanceRepository
    {
        T Get<T>(int id);
        void Save<T>(T entity);
        IQueryable<T> Query<T>();
    }

    A concrete implementation of the  IPersistanceRepository interface is the technology / ORM specific stuff. I am using NHibernate 2.0, so my concrete implementation is called “NHibernateRepository”. By using the IPersistanceRepository interface i am keeping the specifics abstracted away inside the concrete class. I have been able to successfully swap my IPersistanceRepository instance from NHibernate to a DB4o implementation with ease and no effect to my repositories.

    Finder Implementation

    Like the IRepository interface is used as a base interface, i also have a base IEntityFinder interface which again is not directly used outside of my repository layer.

    public interface IEntityFinder<T> where T : EntityBase
    {
        IQueryable<T> DataSource { set; }
    }

    As you can see, the interface has a DataSource property of IQueryable, the reason for this is that I am using System.Linq in my project which I will come onto later. But its purpose is to give the Finder a datasource. Now for the IApplicationUserFinder interface.

    public interface IApplicationUserFinder : IEntityFinder<ApplicationUser>
    {
        ApplicationUser ByLoginName(string loginName);
    
        ApplicationUser ByToken(Guid token);
    }

    The typed Repository

    Now for my implementation of my typed Repository.

    public class ApplicationUserRepository : EntityRepository<ApplicationUser>, IApplicationUserRepository
    {
        private readonly IApplicationUserFinder finder; 
    
        public ApplicationUserRepository(IPersistanceRepository repository, IApplicationUserFinder finder)
            : base(repository)
        {
            this.finder = finder; 
    
            this.finder.DataSource = Query();
        } 
    
        public IApplicationUserFinder Find
        {
            get { return finder; }
        }
    }

    This repository derives from EntityRepository and implements IApplicationUserRepository. Its constucted with its dependencies being injected. The Finder instance has it datasource set to IQuerable<ApplicationUser>.

    The typed finder

    using System.Collections.Generic;
    using System.Linq;
    
    public class ApplicationUserFinder : IApplicationUserFinder
    {
        private IQueryable<ApplicationUser> users; 
    
        public IQueryable<ApplicationUser> DataSource
        {
            set { users = value; }
        } 
    
        public ApplicationUser ByLoginName(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
            {
                throw new ArgumentNullException("loginName");
            } 
    
            return users.Where(u => u.LoginName == loginName).FirstOrDefault();
        } 
    
        public ApplicationUser ByToken(Guid token)
        {
            return users.Where(u => u.Token == token).FirstOrDefault();
        }
    }

    What do we have then

    We have our entity, repository and Finder created. The repository and Finder have typed interfaces, which means i can wire these up in my IoC container. My IEntityFinder interface sort of went against my goal of no leaky abstraction as its using System.Linq, but i think i can live with myself. By having my finder implement an interface i could have different concrete implementations.

    My finder is returning a single instance of ApplicationUser. I could have finder methods that return Iquerable that allows for method chaining etc. Plus i have not allowed for “And”, “Or” or “Not” as that is a different topic. But i have a base to work on.

    nibernate repository

    To be more code complete here is a snippet of my NHibernate repository that returns the initial query. I am using nhibernate 2.0 with nhibernate.linq.

        using System.Linq;
        using NHibernate;
        using NHibernate.Linq;
    
        public class NHibernateRepository  : IPersistanceRepository
        {
            private readonly ISessionLocator sessionLocator;
    
            public NHibernateRepository(ISessionLocator sessionLocator)
            {
                this.sessionLocator = sessionLocator;
            }
    
            public T Get<T>(int id)
            {
                ISession session = sessionLocator.ActiveSession();
    
                return session.Get(id);
            }
    
            public void Save<T>(T entity)
            {
                 ...
            }
    
            public IQueryable<T> Query<T>()
            {
                var qry = from t in sessionLocator.ActiveSession().Linq()
                          select t;
    
                return qry.AsQueryable();
            }
        }

    The beauty of this that the NHibernate specific code is in one place, my repositories and finders have no knowledge of nhibernate. In my finders, i am using linq for objects and lambda’s for my logic. Because i am using IQuerable, i can build up the query through my finders and the execution is deferred until i call a method like “ToList” or “First” etc. The queryProvider in nhibernate.linq builds the sql statement and hits the database once with the specific query.

    Finally a big thank you to Neil Martin and Tim Escott for their involvement on this. Please read this post “Creating Fluent finders and repositories part 1 which continues from this post.

  • My holy grail is finding the right solution for working with database / persistence technologies. Looking back at over my career (all 13 years of it) I have been on this quest for most of it, but more actively in my .Net years. Before .NET I used be a VB/ASP guy using SQL Server  and database access was easy, ADO commands and recordsets talking to stored procedures (sprocs),  it was simple building applications in a data centric manor.  Then .NET 1.0, I jumped straight into .NET and ADO.NET from one of the early beta’s . Microsoft brought datasets to the table (or tables to the dataset) that changed the way we went about accessing data from a data store. By .net 1.1, I favoured data-readers over datasets, but my real concerns at this point was about the many lines of duplicate code I was writing. Here was the key moment.

    The search started for a database access framework that removed the duplicated ADO.Net and kept data access in its own layer and generally make my life easier. I had mainly been developing applications using MS SQL server so sprocs were the API to the database and always a must do (every developer and DBA I worked with and knew had brought into the fact that sprocs were the right way to communicate with MS SQL server and would laugh at anyone who thought different). I had at the time reviewed code generation tools that I could point at my database tables and after watching a lovely progress bar, produced all my sprocs for CRUD behaviour accompanied by a C# class file for each table in my database. Although it worked and built a big percentage of an application for me, it was very procedural and still was not satisfied with it as a solution.

    I then developed 2 different applications to address this. My first attempt was to create a business object template and a stored procedure template, then write my own code generator to fill in the gaps. This did work, but was still to procedural. My second app was to use an Aspect Oriented approach using reflection. This also worked and I was very proud of my creation. I showed this to a couple of developers I was working with at the time and they slammed it and I took it to heart. Looking back at this now, I wish I took their criticism with a pinch of salt as they showed me no better alternative and now I know they opinions were wrong. Effectively I development my own Castle ActiveRecord sitting on top of ADO.NET using sprocs.

    Along came .NET 2005, along side digging deep into the world of OO, Java, design patterns, Agile, TDD, XP  and all the new stuff in C# 2005. My data access quest was still unfinished so I entered the quest again. There was huge amount of business application frameworks on the market. I reviewed and experimented with many frameworks from the Enterprise data access block, .Net tiers, CSLA etc. I still felt that I was on a false trail.

    From the start of my quest in the .net age to where I was in 2005, my goals had changed. I no longer brought into the belief that sproc’s are truly wonderful and all the other propaganda around them. I developed my application around the domain problem not the database schema. In fact, I didn’t even care what my database technology was. I finally found Object Relational Mapping (ORM) as the right way to address my needs.

    Thinking that my quest was coming to an end I faced a new problem . I was working in Microsoft shops and although I brought into ORM, no one else did. Trying to educate people came with resistance. Some people believe what they once learned, and are closed minded to new ideas and generally don’t question their current methods.  This problem spanned into another problems:

    1. Gaining ORM experience in a commercial project becomes hard to get.
    2. The problem is not just getting ORM buy in from others in the business, but getting people to think  “domain centric” instead of a “data centric” .

    I had to admit, faced with these problems I was close to jumping out of land of Microsoft and into the world of Java where ORM and many other development approaches are openly encouraged. Before I jumped the fenced, the whispering of LINQ and WPF has kept my feet in the land of Microsoft. Knowing that Microsoft will be releasing their own ORM tool the commercial uptake of ORM will increase in time as it did with TDD and MSTest. Happier times lie ahead.

    Its 2008, I practice Domain Driven Design (DDD) and have been building up my experience in nHibernate (I found learning Castle ActiveRecord first a good help). I am working with nHibernate in my day job and in my opinion nHibernate is still the powerhouse ORM for .NET. I have used Linq for SQL and I think its a good starting point for developers getting into ORM but nHibernate suites Domain Driven Design out of the box, you can bend Linq for SQL for DDD by using mapping files to kept for domain objects persistent ignorant as well as using the Repository pattern but its still second place to nHibernate. Linq for Entity has been long awaited, its big product it still too early for me to pass judgement.

    NHibernate is still not perfect, working with XML mapping files is not fun. I have been using Fluent-nHibernate which replaces the XML mappings with lambda’s and has a DSL for creating a map for you entities. Creating queries with DetachedCriteria is not as nice as writing a linq query but if you achieve this with nNibernate.Linq.

    I think i have found my holy grail (at last) using Fluent-nHibernate , Linq for Objects and nNibernate.Linq with the Repository and Finder pattern, which I will be providing code examples in my next post.

  • During an evenings coding, I ran into a typical problem with an nhibernate mapping file, (it was a spelling mistake) I had one of those moments when you go onto google to see if any one has come up with something smart to tackle this. I design from the the domain model  first so i was not looking for a code generator that you point at a database and way it goes. I was looking for a OO approach to this that removed xml from the mix.

    It was a successful google search, I came across Fluent-NHibernate.

    This sample code snippet was enough to stop my search and get me excited.

    public CustomerMap : ClassMap<Customer>
    {
      public CustomerMap()
      {
        Id(x => x.ID);
        Map(x => x.Name);
        Map(x => x.Credit);
        HasMany<Product>(x => x.Products)
          .AsBag();
        Component<Address>(x => x.Address, m =>
        {
            m.Map(x => x.AddressLine1);
            m.Map(x => x.AddressLine2);
            m.Map(x => x.CityName);
            m.Map(x => x.CountryName);
        });
    }

    What appeals to me about this code above:

    • The fluent interface and the use of lambda’s makes it very readable.
    • As its a class, I can group all my map objects into a single assembly. Then let the concerning layer in my application reference it, keeping my domain model persistent ignorant. (Before I came across “Fluent nHibernate” I was going to resort to using attributes)
    • Thinking ahead, when/if I refactor my entities, resharper will also make changes to map objects.
    • I am a TDD/BDD practitioner, Its an object, i want to put my mapping logic under test.
    • Lastly, no need for xml mapping files any more.

    So I read some more, downloaded the code and had a play.

    You can get an idea of how this works in about 5 minutes by running the quick start. The instructions and general documentation on this site is a little light on the ground and not much more info on the web at the moment to give more depth on the usage of this API.  The quick start uses a Cat object as the entity to persist.  I don’t really come across to many cats, dogs or other animals in programming so I wanted to used a real life example to get a better feel for it. At the moment to get assemblies, you need to checkout the code from the svn truck and compile the code yourself.

    Running the Quick start

    To aid the quick start instructions

    1. Create a new folder on PC and checkout the code from the SVN trunk “http://code.google.com/p/fluent-nhibernate/source/checkout&#8221;.
    2. From your working folder. Open up the quickStart solution and build it.
    3. As the context is ORM you need a database to push and pull data from. I had an instance of sql express to hand, so I created a blank database called “test”.
    4. Back to Visual studio, in the “FluentNNibernate.QuickStart” project, change the connection string in the app.config to point to your database.
    5. The quick start does not have an UI to use, but its behavior is expressed in the integration tests. Open up “QuickStartTester.cs”, find the “Export_Schema” method (which is decorated with the Explicit nunit attribute) and run the test (I used Test driven .net to run the test). This will create a new table in your database.
    6. Now run the “Can_Persist_Cat” test method. This tests creates an instance of Cat, populates it and saves, it. Lastly the test, pulls the data from the database by the id and compares the ids.

    This is a very simple test but enough to wet my appetite. I have a working example using more business like entities on this post here Implementing Fluent-nHibernate.

  • In my own learning of WPF or any technology that I learn, I use the same approach and design principles that I would for a technology I know inside out. I have used winforms for years and I would be modest to say I know how to design a winform application the right way. It would be the approach I would use if I was developing an application in java swing. I would at the forefront of my design use the “model view controller” (MVC) pattern. The MVC pattern has been around since I was born and has been discussed and debated to death over the years. MVC aside I would use a number of other design patterns that fit the  bill for concern situations. For example: I would use command objects to do certain actions which could be wired up to menu items and/or buttons.

    Model View Controller

    The MVC pattern is a compound pattern, meaning that MVC is made up of other design patterns used together. MVC is made up of the “Mediator” and the “Observer” patterns (I and not going to discuss the details of these patterns as I want to keep to the subject matter, for more information on this patterns I recommend the Gang of Four web site and I might put a post together in the future).

    Although MVC is a well established pattern, I have read other blogs and stuff in forums and the opinion of what MVC is, is very mixed. MVC in the .NET world seems to have become more wide spread over recent years which is good but MVC is not just about “Separation of Concerns” which some people I have worked along side believe. I can not remember where I got this from but the rules I follow are:

    • Model = what it is.
    • View = what it looks like.
    • Controller = what it does.

    MVC is a pattern and as such is a guideline and the implementations of the pattern vary. Variations of MVC exist like “Model-View-Presenter” (MVP) and “ModelView-ViewModel” (MVVM). In a very brief explanation:

    MVC – The view sits at the top of the architecture, the controller sits below the view. The model sits below the controller. So the view knows about the controller, the controller knows the model. The view is notified when the model changes.

    MVP – The controller is replaced with a presenter. The presenter sits at the same level as the view. The presenter listens to the events of both the view and the model and mediates the interactions between both the view and model.

    MVVM – The controller is replaced with a view model. the view model sits below the UI layer. The view model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The view model pulls its data from the model(s) below.

    I read a blog by Josh Smith on “the code project” once where he talked about MVC and WPF and he stated “lower the flamethrower”. I echo his comments.

    If you put ten software architects into a room and have them discuss what the Model-View-Controller pattern is, you will end up with twelve different opinions. … Some of the purists out there will inevitably have qualms with what I refer to as “MVC”. Feel free to leave a flaming comment on the message board at the bottom of this Web page. I will gladly entertain different perspectives on what MVC means, but keep in mind that I do not care.

    Data-binding

    The word Data-binding used to bring back bad memories of using data-binding in older technologies. In Winforms .net 2.0, it was not perfect, it was ok for simple things like binding data grids and text boxes and drop down boxes but using a date time picker was painful. The .net framework contains a number of interfaces and classes (“system.componentmodel”) that allowed you to implement better data-binding support in your own objects.  Using a custom implementation of the observer pattern with a hybrid of the data-binding interfaces was more desirable in winforms. (the memories, the pain).

    But in WPF, no need to be down about data-binding, because it is excellent. Though it has a learning curve.

    Data-binding is in its own right an implementation of MVC. the view are the controls that are shown in UI. the model is the object you are binding to and the controller is the data-binding component. I think its important to think about data-binding in this way.

    Why is MVVM different

    I believe that MVVM pattern was developed by some Microsoft developers a few years ago when developing Expression Blend. The main difference with MVVM to MVC is that the ViewModel is built to serve the view and provide the view with the data and commands it needs. The viewModel is not a general object that could serve different views but is bespoke for each view. For the TDD’ers out there its easy to define the behaviour of a viewmodel and test using a test first approach. The ViewModel is a model for the view. And the real power comes in when you bind your ViewModel to your view in WPF.

    The key thing to remember is that you have one and only one ViewModel per view. The view model communicates with the model (business logic, services whatever below it). The view does not need to know about any else in your architecture. Another major plus point is that you do not any code behind your view and the data-binding deals with the communication to the view model and what ever the view model exposes.

    Thats it for a quick overview. I have a draft post that i am working on that will put this into concrete code.