Monday, June 29, 2009

KandaAlpha now on codeplex

kandaalpha a go go
Monday, June 29, 2009 11:34:59 AM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Thursday, June 25, 2009

db4o POCO Repository using Visual Studio 2010 .Net 4.0 Beta 1 and ASP.Net MVC 1.0

Note: This article applies to beta software and comes with no warranty or support, use at your own discretion. You must have Visual Studio.Net 2010 Beta 1 installed on your machine to make use of the code.

KandaAlpha now hosted on CodePlex, download from http://kandaalpha.codeplex.com/

This is an article which builds on a previous post on domain drive design architecture using asp.net web forms and Entity Framework v4.0. now, we leverage that core architecture to have a db40 object database as the back end and an asp.net mvc web application at the front end.

  • db40 is an object database which means there is no mapping files, attributes or other ‘impedance mismatch’ between your c# classes and the ‘database’ itself. It’s mostly used in embedded scenarios but appears to be getting used in websites. I’ve only just scratched the surface with it here, but i think it’s very cool and i hope it gains more and more traction.
  • asp.net mvc is the latest and greatest presentation architecture for asp.net and includes great separation of concerns between the various layers. In the architecture presented here, the Views and Controllers are within the asp.net mvc web application and the Model is essentially the domain model (e.g. KandaAlpha.Domain.Model)

My previous post discussed the architecture presented here solely within the context of the Entity Framework 4.0. It was also limited to usage of Web Forms on the front end. This release includes that working example but also includes into the solution an asp.net mvc 1.0 application which builds on the architecture and is backed by a db4op powered repository.

The first things i did were:

  • Added an MVC application (KandaAlpha.UI.Mvc) which is the front end side of things, with controllers that dependency inject the services and repositories as before.
  • Implement new repository for db4o (sorry, in the application i misspelt and used a zero, doh!) in KandaAlpha.Infrastructure.Repository.db40.
  • Update the web.config of the mvc application (and associated tests project) to wire the Unity dependency injection so that the db4o repositories are returned for repository interface requests

Changes to Dependency Injection Approach – Service Location vs Constructor Injection

I released this post last night and then got some good feedback from Will Beattie about design smells around my choice of Service Locator pattern approach to the dependency injection within the mvc controllers. One other approach as discussed in this post’s comments is to use constructor injection dynamically on the controllers. So, you can see i’ve added a custom controller factory.

In addition, Will had commented ton the controller’s dependency on the repository layer. I wasn’t too fussed about this given repository is within the domain and simply consists of interfaces but i did break it out for completeness. Notice that this does mean you get duplicate interfaces on the service layer in many cases. In practice, i would be quite happy to expose repository through the service layer but made the change anyway for completeness.

It’s worth noting i do still make of the ServiceLocator pattern within the mvc controller factory itself and also within global.ascx.cs Application_End which is where i ‘clean up’ the Repository Context (e.g. kill to db40 database ‘connection’).

So in general, the trend seems to be to favour constructor injection but there will sill be scenarios where a service locator pattern can prove useful, particular when mocking/testing may not be required.

Unit Test Isolation

If you take a look at the unit test for the controller now you can see how easy it is to mock up the controller without recourse to any dependency injection. In fact, the test is failing because i haven’t gotten round to implement a SaveChanges() for the in simply memory repository i built.

Before the unit test was admittedly an integration test, and it appears cleaner now, although it would be more work to maintain an in memory repository for a larger more complex application, but more advanced mocking tools may help with that.

How the mvc project runs

When you run the mvc project, it simply displays 2 customers on the screen. I’ve also added a little update on one of the customers as you refresh the page, just to show how to save things back to the db40 file.

This all took less than 2 hours and i was very pleased to get things up and running so quickly. It hopefully shows you some of the power and flexibility of dependency injection and the domain drive approach as well as introduction you to how use such an architecture with technologies like asp.net mvc, db4o and entity framework.

Thursday, June 25, 2009 10:51:27 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Sunday, June 21, 2009

glorious winter day

what a fantastic sunny day it was today.. Winter? bollocks to that!

DSC00088DSC00085DSC00084DSC00083

Sunday, June 21, 2009 6:26:59 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, June 20, 2009

Zoo Pics

DSC00054DSC00053DSC00051DSC00069DSC00068DSC00066DSC00065DSC00063DSC00060

Litter everywhere daddy! Tidy Kiwi Tommy sorts the ‘naughty people’ out.

DSC00059

DSC00056

The Thinker…

DSC00082

Apparenlty they are pink because of what they eat (shrimps etc.). When i asked Annabel why we don’t go green from eating cabbage, she said “because we aren’t flamingos”. Fair enough really.

DSC00081

Tommy after his first chocolate paddle pop

DSC00079

 

DSC00078DSC00077DSC00076DSC00074DSC00072

Saturday, June 20, 2009 5:17:33 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Thursday, June 18, 2009

Some recent pics

DSC00047DSC00043DSC00042DSC00041DSC00039DSC00036DSC00035DSC00034DSC00031DSC00030DSC00025DSC00022DSC00021DSC00019DSC00014DSC00013

Thursday, June 18, 2009 10:28:08 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Monday, June 01, 2009

Kentico CMS 4.0 and Bounded Box Image Resizing

This article has code specifically for Kentico CMS 4.0 and can be used in a scenario where you have an image’s dimensions and want to ensure that the image fits into a known bounded box.

With Kentico CMS you retrieve images using a call to a handler at /CMSPages/GetFile.aspx. That page accepts parameters Height, Width and MaxSideSize. Height and Width can be fixed and specifying one and not the other will retain aspect ratio. MaxSideSize allows a single value to bound the height and width.

However, if you have a given bounded box on the page (e.g. say a 400 * 300 space) and you want to make sure an image fits inside that space whilst retaining aspect ratio there is no way to do this.

I’ve emailed this code to the Kentico support team to allow MaxHeight and MaxWidth properties so that we can do this. In the meantime this hack/fix within GetFile.aspx.cs code behind file will allow you to supply negative values for height and width which then act as a bounding box!

// HACK - Interpret MaxHeight and MaxWidth via negative Height and Width values (line 599)
if (this.Height < 0 || this.Width < 0)
    ApplyBoundingBox(atInfo.AttachmentImageHeight, atInfo.AttachmentImageWidth);

/// <summary>
   /// Custom Hack to interpret negative height and width values as setting bounding box
   /// </summary>
   private void ApplyBoundingBox(int imageHeight, int imageWidth)
   {

       if (this.Height >= 0 && this.Width >= 0)
           return;

       int maxHeight = 0;
       int maxWidth = 0;
       float ratio = 0;

       if (this.Height < 0)
       {
           maxHeight = this.Height * -1;
           this.Height = imageHeight;
       }

       if (this.Width < 0)
       {    
           maxWidth = this.Width * -1;
           this.Width = imageWidth;
       }

       if (maxHeight > 0 && this.Height > maxHeight)
       {
           ratio = (float)this.Height / (float)maxHeight;
           this.Height = maxHeight;          
           this.Width = (int)((float)this.Width / (float)ratio);
       }

       if (maxWidth > 0 && this.Width > maxWidth)
       { 
           ratio = (float)this.Width / (float)maxWidth;
           this.Width = maxWidth;
           this.Height = (int)((float)this.Height / (float)ratio);
       }

   }

Monday, June 01, 2009 11:43:47 AM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, May 30, 2009

Entity Framework POCO Repository using Visual Studio 2010 .Net 4.0 Beta 1

Note: This article applies to beta software and comes with no warranty or support, use at your own discretion. You must have Visual Studio.Net 2010 Beta 1 installed on your machine to make use of the code.

Update 25/06/2009: This article should be read first, however, see next article here which uses asp.net mvc and db4o object database with updated code now hosted at codeplex at http://kandaalpha.codeplex.com/
http://blog.keithpatton.com/2009/06/25/db4o+POCO+Repository+Using+Visual+Studio+2010+Net+40+Beta+1+And+ASPNet+MVC+10.aspx

Download KandaAlpha v1 Code Now

Introduction

Before i delve into the details, it’s worth providing a bit of context on this post. For a number of years i’ve been a big fan of ORMs (object relational mappers) for helping get in memory software objects into and out of databases.

I’ve gradually moved away from a data-centric view of the world, towards a transition to domain driven design methodologies in architecting more complex enterprise applications.

My ORM of choice has up until around a year ago been NHibernate. I used it for a few years and grew to love it’s power and flexibility. But it always felt and still is a bit of a black art to make sing. And the tool and Linq support has never really matured to a level where i thought it was really going to take off.

Then along came the Entity Framework from Microsoft. I compared it and NHibernate during the .net 3.5 SP1 beta period and concluded that whilst it was architecturally inferior in many ways to NH, the availability of a designer, integrateion with Visual studio and .net combined with the sheer muscle of Microsoft dollars convinced me to give it a shot.

It was a success and saved me a lot of time, although i did have some pain taking EF across tiers usign web services, although the pain would likely have been there but in a different way with NHibernate. You can see some relatively popular previous posts are related to EF, with the Vote of Confidence in EF (in riposted to Alt.Net’s Vote of No Confidence) and also the code for the Polymorphic Repository for Entity Framework 1.0 (or what is now being called 3.5!).

And now we have Entity Framework 4.0. It is abundantly clear that the EF team have listened, learned and produced an ORM to be proud of. Whilst there will likely be gripes in various camps, we now have full POCO (plain old CLR object) support, lazy (deferred) loading support, AND model first design which allows us to create domain models and have the database generated from that. Very cool indeed.

So that’s the introduction. What i’m attempting to do at this early stage is to clearly demonstrate a DDD inspired layered architecture which combines a Repository pattern, injection of control (IoC) using the Microsoft Unity Application Block (swap out for your favourite IoC) and an Entity Framework 4.0 repository implementation.

The Architecture

Presented below are 4 logical layers, Presentation, Application, Domain and Infrastructure (a good overview of the DDD Layers). The rectangles are logical components within each layer (represented in code as .net assemblies). The full head arrows are runtime dependencies between the various libraries which sit within a particular layer. The dotted lines represent runtime dependency injection via our inversion of control tool of choice.

IMG

The Presentation Layer contains a web application (MVC wasn’t available in the Vs.net 2010 Beta 1 so I just used a ‘normal’ web application).

Then we have an Application Layer which has a class library of interfaces to define the behaviour of the implementing services which are in another class library. The services are injected using IoC as implementations of the application interfaces (we’ll see how that’s done later using Unity). The application layer co-ordinates requests from the presentation layer and makes use of the Repository in doing so.

The Domain Layer contains our Domain Model and Repository. The domain model has no dependencies to any other component or layer. The Repository consists of interfaces which define the behavior of the Repository implemented which is injected using IoC. The Repository represents a ‘store’ view of domain objects, underpinned by some form of persistence framework in the Infrastructure layer.

Lastly we have an Infrastructure Layer. In our example architecture this is the Entity Framework repository implementation and persistence framework. The class library has classes which implement the Domain’s Repository interfaces as well as having dependencies on the core EF classes and libraries.

Overall, this is a relaxed layered architecture in the sense that we have decent separate of concerns between the layers but we do allow cross layer dependencies. For example the domain model types are used within the web application (rather than have an extra layer of interfaces or data transfer objects).

The key point in this architecture is that the means by which domain objects are persisted is separated from the domain objects themselves. In addition, we have a  Repository is defined within the domain layer, whilst its implementation is injected using IoC. The domain layer as a whole therefore has no awareness of or build dependency on the underlying persistence framework.

 

 

 

The Solution

SolutionStructure

Here is the architecture represented as a Visual Studio.Net solution. You can see that I’m using Solution Folders to represent the various layers and then using class libraries for each layer component with the exception of the presentation layer which is represented by an asp.net web application. KandaAlpha is just a sandbox prefix I’m using.

For completeness please do note the Base Libraries folder which simply contains the IoC facade to the Microsoft Unity Application Block and also a references project housing the Unity application block dlls.

 

 

 

 

 

 

The Client Code

This first bit of code is the client api view at the asp.net web application level.

// get the customer service using IoC (Unity)
var custService = IoCWorker.Resolve<ICustomerService>();

// get the customer repository from the customer service
var custRepository = custService.GetRepository();

// get all customers and bind to grid
dgCustomers.DataSource = custRepository.GetAll();
dgCustomers.DataBind();

// use a specific method on customer repository
var kp = custRepository.GetBestCustomer();

// display customer's full name
litCustomerName.Text = kp.FullName;

// demonstrate lazy/deferred loading (not for production!)
litFirstOrderTotal.Text += kp.Orders.First().OrderTotal.ToString();

The basic idea here is that we request a service from the IoC container, and the service then provides the ability to fulfill a particular orchestration or unit of work.

You can see from the code that the ICustomerService implementation allows us to get a repository implementation to get all customers, to get the best customer, and also to get the first order total of the best customer. Note how lazy/deferred loading is working for the last call.

And hey presto, a very exciting screen is produced. (Note that the database is stored within App_Data in the web project. This would obviously be a remote SQL server in a production environment, i just wanted to provide the source fully contained)

FinalPage

Wiring up Unity IoC

Here’s how the inversion of control is wired up. See the containers element were we set up a single container and then set up the container to wire particular class implementations as singletons for each particular interface we are interested in providing a service implementation for. Take a look at the small KandaAlpha.Ioc.IocWorker static facade class which combined with configuration initialises the container and provides the hook into resolving service implementations for interfaces via the Resolve<T>() method.

<unity>
    <typeAliases>
      <!-- Lifetime manager types -->
      <typeAlias alias="singleton"
           type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
               Microsoft.Practices.Unity" />
      <typeAlias alias="perThread"
           type="Microsoft.Practices.Unity.PerThreadLifetimeManager,
               Microsoft.Practices.Unity" />
      <typeAlias alias="external"
           type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
               Microsoft.Practices.Unity" />
      <!-- User-defined type aliases -->
      <typeAlias alias="ICustomerService"
      type="KandaAlpha.Application.Interfaces.ICustomerService, KandaAlpha.Application.Interfaces" />
      <typeAlias alias="CustomerService"
           type="KandaAlpha.Application.Services.CustomerService, KandaAlpha.Application.Services" />
      <typeAlias alias="IGenericRepository"
           type="KandaAlpha.Domain.Repository.IGenericRepository`1, KandaAlpha.Domain.Repository" />
      <typeAlias alias="GenericRepository"
           type="KandaAlpha.Infrastructure.Repository.EF.GenericRepository`1, KandaAlpha.Infrastructure.Repository.EF" />
      <typeAlias alias="ICustomerRepository"
           type="KandaAlpha.Domain.Repository.ICustomerRepository, KandaAlpha.Domain.Repository" />
      <typeAlias alias="CustomerRepository"
           type="KandaAlpha.Infrastructure.Repository.EF.CustomerRepository, KandaAlpha.Infrastructure.Repository.EF" />

    </typeAliases>
    <containers>
      <container name="containerOne">
        <types>
          <type type="ICustomerService" mapTo="CustomerService">
            <lifetime type="singleton" />
          </type>
          <type type="IGenericRepository" mapTo="GenericRepository">
            <lifetime type="singleton" />
          </type>
          <type type="ICustomerRepository" mapTo="CustomerRepository">
            <lifetime type="singleton" />
          </type>
        </types>
      </container>
    </containers>
  </unity>

Domain Model

Nice, POCO classes, nothing relating to persistence or Entity Framework in here, just as it should be. All is right in the world;)

using System;
using System.Collections.Generic;

namespace KandaAlpha.Domain.Model.Entities
{
    public class Customer : EntityBase
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName
        {
            get
            {
                return FirstName + " " + LastName;
            }
        }
        public virtual List<Order> Orders {get; set;}
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KandaAlpha.Domain.Model.Entities
{
    public class Order : EntityBase
    {
        public int OrderID { get; set; }
        public Customer Customer { get; set; }
        public decimal OrderTotal { get; set; }
    }
}

Domain Repository

So, IoC gives us an implementing class for ICustomerService which has a method GetRepository() which returns an ICustomerRepository implementation.

Leaving aside some of the wiring within the Application.Services component, let’s take a look a the ICustomerRepository interface defined within the Domain.Repository component

using System;
using KandaAlpha.Domain.Model.Entities;

namespace KandaAlpha.Domain.Repository
{
    public interface ICustomerRepository : IGenericRepository<Customer>
    {
        Customer GetBestCustomer();
    }
}

So, we have a single custom method on this repository, but most of the action is within the IGenericRepository<T>) class which defines our core repository behaviour as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using KandaAlpha.Domain.Model.Entities;

namespace KandaAlpha.Domain.Repository
{
    public interface IGenericRepository<T> : IRepositoryBase where T : EntityBase
    {

        /// <summary>
        /// Return strongly typed IQueryable
        /// </summary>
        IQueryable<T> GetQuery();

        /// <summary>
        /// Load entity from the repository (always query store)
        /// </summary>
        /// <typeparam name="T">the entity type to load</typeparam>
        /// <param name="where">where condition</param>
        /// <returns>the loaded entity</returns>
        T Load(Expression<Func<T, bool>> whereCondition);

        /// <summary>
        /// Provides explicit loading of object properties
        /// </summary>
        void LoadProperty(T entity, Expression<Func<T, object>> selector);

        /// <summary>
        /// Returns all entities for a given type
        /// </summary>
        /// <returns>All entities</returns>
        List<T> GetAll();

        /// <summary>
        /// Add entity to the repository
        /// </summary>
        /// <param name="entity">the entity to add</param>
        /// <returns>The added entity</returns>
        void Add(T entity);

        /// <summary>
        /// Save all changes from repository to store
        /// </summary>
        /// <returns>Total number of objects affected</returns>
        int SaveChanges();

        /// <summary>
        /// Mark entity to be deleted within the repository
        /// </summary>
        /// <param name="entity">The entity to delete</param>
        void Delete(T entity);

    }
}

As you can see from the Unity IoC configuration ICustomerRepository is wired up to CustomerRepository within the Infrastructure.Repository.EF component. You can see hopefully how you could modify this to be NHibernate, ADO.Net or an in memory provider for quick testing if needs be by just changing the IoC configuration.

EF Repository Implementation

The core job of the EF Repository implementation is to then implement the ICustomerRepository and IGenericRepository<T> interfaces.

2009-05-30_2303[1]

The CustomerRepository and GenericRepository classes also make use of a static ObjectContextManager class. This implements a lifecycle management pattern across the EF’s object context which is one per http request (if HttpContext.Current is available) or one per thread for non web applications.

The EF’s edmx model class goes in this class library too. I followed the very simple instructions around how to enable POCO support for Entity Framework which largely entailed switching off code generation in the properties window of the edmx, nice!

Note the hand crafted KandaAlphaContext class which allows me to specify exactly what happens when the context gets created, including lazy loading options as follows:

 

public KandaAlphaContext() : base("name=KandaAlphaEntities", "KandaAlphaEntities")
{
    _customers = CreateObjectSet<Customer>();
    _orders = CreateObjectSet<Order>();
    base.ContextOptions.DeferredLoadingEnabled = true; // lazy loading
}

There is lastly an HttpRequestModule class which simply kills the object context at the end of each http request. For non web applications you would explicitly kill the context at the end of each unit of work. (although i haven’t yet got a facade method for that on the repository as yet).

Summary

I’m a big fan of the new Entity Framework. I think that the EF team are going to get this release spot on and we’ll see Entity Framework really establish itself as the ORM of choice for Microsoft developers. It will be interesting to see what the Alt.Net community make of EF v2 (sorry v4!), but from what i can see they’ve hit all the right buttons this time around. We’ll likely be talking about specific features, or sql optimisation as opposed to core architectural gripes this time around i feel.

As a big NHibernate fan too, I’m disappointed that Microsoft can’t co-opt more proven open source software like with JQuery as it’s a real boon to the .net community to have these projects flourish.

Saturday, May 30, 2009 11:31:16 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [10]  |  Trackback
 Saturday, May 23, 2009

asp.net development on a mac

Well, sort off…

The idea is that you have designer types who hate windows and will get ill with prolonged usage. So as to make sure you have an adequate supply and flow of decent mark up coming your way as a developer it’s in your best interests to ensure designer type is safely ensconced within the comfort zone of single button mice and strange looking speakers.

We use team foundation server, otherwise known as TFS, which helps us to manage the source control of all our development efforts. In addition, it helps us manage work items (tasks and bugs) during software projects.

If you are on a Mac and are working with TFS, you need this:
http://www.teamprise.com/products/explorer/

OK, so you can work with source control and work items, big deal, how do you actually run an asp.net website?. Well, thanks to the wonders of virtualisation you simply run a windows vm with an iis website as required and give it an appropriate host header such as macdebug.projectname.mycompany.net. Ensure FTP server is running on your windows vm with an appropriate login so that you can copy files to this website via ftp from your Mac.

Now, back on your good old macintosh, you create a TFS workspace and get latest on your lovely TFS solution to have the files locally on your mac. You use your favourite text or html editor and work on the files, checking them out and in as required, and doing all your work items, great. Obviously visual studio is the tool of choice for .net development but if all your tasks are around working with content assets, mark up and styling related files then you don’t really need all that overhead.

All you need to do is ensure that for each change you make that you have an action to FTP the file that has been changed across to the IIS website via FTP automatically. This ensures that you have the IIS website running off your latest changes.

Last thing you need to do is create a hosts file entry on your mac to point macdebug.projectname.mycompany.net to the IP address of your windows vm. Then you can fire up safari and browse to http:macdebug.projectname.mycompany.net to see your asp.net website!

I’ll post up some visuals and details on the tools we’re using on the mac when I have them.

Saturday, May 23, 2009 6:41:29 PM (New Zealand Standard Time, UTC+12:00)  #    Disclaimer  |  Comments [0]  |  Trackback