Monday, November 28, 2011

Implementing a different kind of Service Pattern

For the past few months I've investigated many different types of patterns I can implement in my projects; like Repository Patterns, Unit of Work Patterns, Service Patterns etc. After plenty of research, late nights and a gazillion units of black coffee; I finally came across a some sort of hybrid solution that works for me in many different scenarios.

Being aware that a specific pattern to follow is purely dependant on the particular solution, I wanted to be comfortable with a rock solid "generic" implementation that can be used across many types of applications like ASP.NET MVC, WPF, Silverlight & WindowsPhone.

The main reason for this was to make the code more unit testable using mock-ups, this can be implemented easier because everything is very loosely coupled and is utilising the beauty of dependency injection (DI).

I want to mention that the following "pattern", if you will; is only a suggestion to those who feel daring and in need for something fresh & different. Your comments are more than welcome.

What we'll build

Okay, don't get bored so soon! Let me walk you through the whole thing.

This is a typical ASP.NET MVC implementation, I haven't tried using this in other frameworks yet but I'm very confident that it should work just as well.

Scanning the diagram from the bottom, you'll first notice the database. This can be any source of data (SQL, XML files etc.)

Next, there's two IDataContext implementations: MockDataContext and DataContext. This serves as the data access layer to our store and can be anything from EntityFramework, NHibernate etc. Note that the MockDataContext does not have any connections to a data store as this will be fabricating mock data for our unit tests.

    public interface IDataContext
        IQueryable<T> All<T>() where T : class;
        IQueryable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class;
        T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class;
        T Add<T>(T entity) where T : class;
        T Update<T>(T entity) where T : class;
        T Remove<T>(T entity) where T : class;
        bool SaveChanges();

By implementing the Factory Pattern, it allows us to create an disposable instance of different IDataContext implementations, in turn better managing database connections & utilising connection pooling.

The only responsibility of the IDataContextFactory implementation, is to create the applicable instance of the data contexts to be consumed.

    public interface IDataContextFactory
        IDataContext Context { get; }   

    public class DataContextFactory : IDataContextFactory
        public IDataContext Context
            get { return new DataContext(); }
We all may be familiar with the next item, the Service; that houses all the business logic of each unit of work. The InvoiceService implements IInvoiceService which forces an property of type
IDataContextFactory named "factory". 

    public interface IInvoiceService
        IDataContextFactory factory { get; set; }
        Invoice GetInvoice(string invoiceNumber);
        bool SaveNewInvoice(Invoice newInvoice);

    public class InvoiceService:IInvoiceService
        private IDataContextFactory _factory;
        public IDataContextFactory factory
            get { return _factory; }
            set { _factory = value; }
        public Invoice GetInvoice(string invoiceNumber)
            using (var context = factory.Context)
                var invoice = context.Find<Invoice>(i => i.InvoiceNumber.Equals(invoiceNumber,  StringComparison.OrdinalIgnoreCase));
                return invoice;
        public bool SaveNewInvoice(Invoice newInvoice)
            using (var context = factory.Context)
                var invoice = context.Add<Invoice>(newInvoice);
                return invoice != null;

All the classes mentioned above, lives in the Domain layer of the solution. The next few items is applicable for a ASP.NET MVC implementation:

I'm not going into detail of MVC, but the general rule of thumb is to keep your views skinny, have thin controllers and fat models (View Models). It's also best practise to have a ViewModel for every View so that unit testing is possible on your view logic.

Keep the behavior logic in the Controllers, view logic in the ViewModels & business logic in the Domain.

Moving on, The InvoiceController consumes a service of type IInvoiceService. (Not to be confused by an web & WCF service, the term "service" here merely acts as a host of business specific tasks exposed by the contract IInvoiceService

The Controller contains many Actions that is responsible for relaying commands, DomainModel-ViewModel mappings & showing certain Views depending on request. In this case, an Action in the
InvoiceController can decide to pass the ViewModel to either a Desktop or Mobile View.

The Controller's Action method may use the helper class InvoiceComposer to map from Domain Models to ViewModels and back. There are many Object Mappers available like AutoMapper.

    public class InvoiceController : Controller
        private readonly IInvoiceService invoiceService;
        public InvoiceController(IInvoiceService invoiceService)
            this.invoiceService = invoiceService;
        public ActionResult Details(string invoiceNumber)
            var domainModel = invoiceService.GetInvoice(invoiceNumber);
            var viewModel = domainModel.ToViewModel();
            if (Request.Browser.IsMobileDevice)
                return View("Invoice.Mobile", viewModel);
            return View(viewModel);
        public ActionResult Save(InvoiceViewModel viewModel)
            var domainModel = viewModel.ToDomainModel();
            return View(viewModel);

Wiring everything together
By utilising the beauty of dependency injection, we can create a container that houses the configuration mappings of contracts to the implementation classes. In return, we just expect the different types concerned to be magically instantiated for us by the Dependency Resolver. No ugly "Object reference not set to an instance of an object" exceptions (or at least if the DI is setup correctly).

In this example, I'll be using MEF (no not the drug) for the DI framework. MEF is obviously short for Managed Extensible Framework and is way more than just an Dependency Injection engine.

Note the [Import] & [Export] attributes on the code above. This tells MEF to Export the implementation class as type of the contract specified and imports the instance of the implementation class when required.

I don't want to steal Steve Job's line here but... There is one more thing...

Unit Testing
Having our code so loosely coupled means better unit testing which means more rock solid systems which means happier clients which means more money :)

Okay but its not all about the money, it's about that air punch at the end of the day when you feel you just created the best and cleanest system in the world.

Going into no detail here is what a typical unit test may look like with mocking in place:

        public void GetInvoiceTest()
            var invoiceService = new InvoiceService();
           //This MockDataContextFactory also implements IDataContextFactory
            invoiceService.factory = new MockDataContextFactory();
            string invoiceNumber = "INA001";
            var expected = new Invoice
                       { Id = 1, InvoiceNumber = "INA001", Amount = 100 };
            var actual = invoiceService.GetInvoice(invoiceNumber);
            Assert.IsInstanceOfType(actual, typeof(Invoice));
            Assert.AreEqual(expected, actual);

 So there you go. Another mouth-full from me.

I hope that this may help everyone else interested. Like I said, I urge my fellow Ninjas to please feel free to comment, correct my possible wrongs or even elaborate on a possible other solution. This works perfectly for me.

Till next time...


Tuesday, November 22, 2011

Jump Start your next project with Nuget

In between the company end-year functions, demanding clients and of course my fabulous life :) , I've deceided to do some blogging again. In fact, it's been a while since any Ninja laid a finger on a keyboard here, (or an iThing)...

A while ago I came across a cool little thing called "NuGet" (pronounced new-get). No, it's not the kind of things you get from Mc Donalds. According to the website, NuGet is a Visual Studio extension that makes it easy to install and update [open source] libraries and tools in Visual Studio. But, I believe they're being modest. It's way more cooler than what meets the eye.

Okay, so whats all the fuss about? Well, the main idea behind it is to allow you to install any files (libraries, media, code files etc) into your project / solution in a managed way with versioning & dependency detection. In the NuGet world, these files are bundles into things called "packages".

When you use NuGet to install a package, it copies the [library] files to your solution and automatically updates your project (add references, change config files, etc). If you remove a package, NuGet reverses whatever changes it made so that no clutter is left

There is a wide variety of libraries ready to be downloaded & used (3680 to be exact) from the offical NuGet Package Source. You can even create your own package source that can be hosted to be available externally or internally on your intranet - I will get to this later.

So, let's install NuGet...

Obviosly, first you need to open every Ninja's biggest asset: Visual Studio 2010.

1. Open up the 'Extension Manager' from the Tools menu

2. Under the Online Gallery section, search for "NuGet" and click "Download"

After downloading, "reading" the legal stuff & installing, you need to restart VS for the changes to take effect.

That's it, now we have NuGet installed & we can get "Nugetting" :)

For this example, I'm going to create a blank web forms project (yes I said web forms) and install "EntityFramework.Patterns" onto it. This is only to show the functionality of NuGet.

1. After you've created a blank project, right-click on 'References' there is an additional item "Manage NuGet Packages" - Click it. (or if you're using a touch screen, I rest my case)

2. Next you will be presented by the main NuGet Manager

3. From the 'Online' section (on the left), search for "EntityFramework.Patterns" and hit "Install"

Note that EntityFramework 4.1 is required for this library to work (under dependencies). But have no fear NuGet handles it for us:

That's it... So if we go back to our little sample project you will notice that a few references were added including a packages.config file. (Also note that some content has been added to the web.config file)

There is of coarse an alternative "Ninja" solution to do all this, by using the Library Package Manager Console (Tools > Library Package Manager > Package Manager Console). Just type:

Install-Package EntityFramework.Patterns

You can now use the installed library in your code. Im not going into how we use EntityFramework.Patterns, but hopefully you get the idea.

But, where is the actual packages? If you go to your solution folder, you will note a "packages" folder. When you open it up, you'll notice all the packages that is installed in the solution. So best checking this folder into TFS!

Now, for the cool stuff... Creating your own package...

Creating your package is exactly like adding files to a ZIP file. But in this instance, the "zip" file is called a NuGet Package file (*.nupkg). There is also a specifications file called a NuSpec file (*.nuspec) that contains all the meta data of the package like version information & dependencies etc.

There are many ways of creating and publishing your packages:

The Ninja Way
The Easy Way

You can also host your own package feed

You can view a variety of videos available on this subject

So, Ninjas... Now you have no excuse to deliver the "best in the business" code. Get coding away... Get packaging away and make your life easier with NuGet.

Follow me on Twitter @FanieReynders

Until next time..... Cheers.

Thursday, November 3, 2011

A really handy "cheat-sheet" for Razor

I came across this cool syntax table that can come in quite handy when one is working with Razor in ASP.NET:

Web Forms Equivalent (or remarks)
Code Block
  int x = 123;
  string y = "because.";
  int x = 123;
  string y = "because.";
Expression (Html Encoded)
<span><%: model.Message %></span>
Expression (Unencoded)
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text>
<% if (foo) { %>
  Plain Text
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
Same as above
Email Addresses
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the
@@foo to display the value
of foo</span>
@@ renders a single @ in the response.
Server side Comment
This is a server side
multiline comment
This is a server side
multiline comment
Calling generic method
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
  Func<dynamic, object> b =
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.

Of coarse this is only like a basic set, but here is a link with a full reference to Razor.