Latest Blog Posts

My first code contributions to an open source project

Posted on Monday, 30 Mar 2015

Pull request #199 to the Shouldly unit testing library is a bit of a significant pull request for me. Not because it introduces any new killer features or fixes any bugs, but because it marks what I feel is my first real contribution to an open source project.

I recently blogged about my targets for 2015, one of which was to make a concerted effort to get more involved in the open source community; more specifically - to start to contribute and give back to projects that I've been using and taken so much from. Having been programming for a number of years now, why has it taken so long to get around to giving back to the community?

What's taken so long?

I've been programming in one form or another for about a decade now, and professionally for 8 of the 10 years. I first started with PHP, then eventually moved onto writing Java for the purposes of Android development, and after having fell in love with it, .NET and C#. During this time programming I'm ashamed to say that I've not contributed to any projects in any meaningful manor for a number of reasons, these boil down to:

Focusing too much on personal side projects
Side projects are a great way to learn new technologies, however they do come with its own set of downsides when it comes to progression as a developer, these are:

  • You don't get the exposure to other people's code (and thus new techniques and alternative or better ways of doing things) that you do when collaborating on a project.
  • Unless you're working on a project you plan on open sourcing yourself AND it becomes hugely popular you don't get feedback and critique on your code.

    Now don't get me wrong, I'm not saying working on side projects is a bad idea, side projects are a fantastic way to improve on your existing skillset - I'm merely saying that a variety of project types can lead to a more varied array of learning avenues.

Just not good enough (aka imposter syndrome):
Like many software developers I suffer from imposter syndrome:

Impostor syndrome is a psychological phenomenon in which people are unable to internalize their accomplishments. Despite external evidence of their competence, those with the syndrome remain convinced that they are frauds and do not deserve the success they have achieved. Proof of success is dismissed as luck, timing, or as a result of deceiving others into thinking they are more intelligent and competent than they believe themselves to be.

When I look at some of the great open source projects I use it's really difficult not to compare your ability as a software developer with those that can create and craft such an awesome piece of software - ultimately this comparison can cause you to feel like you're not good enough to contribute to a project, in which case my thought process was often "I'm not a good enough developer, maybe once I've improved will I give contributing back a try".

My first pull request

In order to start contributing to a project you have to find a suitable open source project, and naturally it always helps if it's one you've already got experience with and use on a day to day basis. In this instance, whilst developing this blog I stumbled upon a unit testing assertion library called Shoudly.

What is Shouldly?

Shoudly's focus is to provide a more natural assertion framework to developers, turning a normal asserstion into a far more natural and readable alternative. Take the following examples for instance:

// Your typical assertion
Assert.That(contestant.Points, Is.EqualTo(1337)); // Produces a rather unhelpful error message "Expected 1337 but was 0"

Compare the above example to Shoudly:

// The Shouldly way!
contestant.Points.ShouldBe(1337); // Produces "contestant.Points should be 1337 but was 0"

I don't know about you but I know which test arrangement and test failure message I'd rather work with - and having been using Shoudly extensively for writing unit tests for my blog it was the natural fit - what's more is there were plenty of "Up for Grabs" issues available on Shouldly's Github page that were suitable for someone new to the codebase, so I took my pick and got stuck in.

A few hours later, once I'd finished working on the chosen issue, I re-ran the unit tests I proceeded to send my first pull requst. 

At this point I feel it's worth mentioning that Shouldly's author Jake Ginnivan has been a massive help in helping me understand some of the more challenging aspects of Git (such as rebasing commits in order to keep a project's Git history in good shape). Jake was more than happy to help me with any questions or problems I had and offered advice and help without making me feel like I was a nuisance as I fumbled my way around Git.

Moving forward

Overall I found contributing to Shouldly an extremel rewarding experience that I plan on continuing to persue. Hopefully once the set of issues that I'm currently working my way through are completed there will be more issues that I'll be able to pick up.

If anyone reading this is considering taking their first steps in contributing to open source projects then I would most definitely recommend it. Start small like I did by picking relatively easy tasks and then start to work your way up.

Presentation from a recent Introduction to Typescript talk I gave

Posted on Thursday, 26 Mar 2015

Recently I stumbled upon a local web development meetup that I've started to attend. It's a great group of people from various different backgrounds such as Java, PHP and .NET. The meetup is kindly hosted by a local Performance and Governance management software vendor who not only hosts the event but also supplies beer and pizza to the attendees.

At a recent meetup there was a call for volenteers to perform a small 15 minute grok talk on any software development related subject that would suit the range of developers that attend the meetup, so I decided to put myself forward and do a talk on TypeScript. Given the time constraints I decided not to go too deep into the internals of the language but instead opt to provide the attendees with general overview of what TypeScript is, what problems it solves and how it can increase maintainability of large Javascript heavy applications.

Overall I felt the talk went well with a healthy number of questions asked at the end of it that I tried my best to answer. There was, however, one instance where I slipped up as a result of misunderstanding what was a very straight forward question; however this was the first talk I've given so I'm not going to be too harsh on myself. Giving the talk made me realise how much I enjoy talking about software development and has certainly made me keen to give more talks in the future.

The presentation can be found on my GitHub account or you can view the presentation slides on Google Drive here.

Changing StructureMap configuration at runtime

Posted on Tuesday, 24 Feb 2015

Lately I've been (re-)reading Mark Seemann's fantastic Dependency Inection in .NET book. I originally bought the book when I first started learning ASP.NET MVC and IoC container usages and whilst I learned a lot from it at the time, the fact that I'd not been exposed to IoC containers for long enough meant that some content didn't sink in. Ultimately this comes down to the fact that when you can relate things to real life experiences your ability to remember the solution is far better than if you've never run into the issue before.

Having been using ASP.NET MVC and taking full advantage of IoC Containers for sometime now I've found going back through the book far mre rewarding beneficial as I have those dependency management scars that I can related to. 

Fast forward a few days and as I'm performing my regular sweep of the StructureMap related questions on StackOverflow (I find spending time participating in the SO community by answering questions a great way to learn) I came across a question titled How to inject different instance(s) for different context in ASP.NET MVC using StructureMap?. Having read the question and the problem the user was tackling, it quickly became apparent that I'd just finished reading a chapter that demonstrated a viable solution to such a problem, and have ran into this very same problem but in a different form before.

Before diving into the solution, let's look at the problem in a bit more depth.

A bit more about the problem

The problem the author of the post in question was experiencing was that they needed to inject a different type of data storage mechanism depending on configuration data. In this particular case the author wanted to switch a storage mechanism from a database to file storage at the flick of a switch. Whilst this is quite a specific problem, it's a common hurdle that anyone writing an application of any size will encounter eventually, which ultimately boils down to how do I configure StructureMap during runtime?

I've run into this exact same problem during previous projects in the following instances:

  • Switching an image store from database or file storage to CDN storage based on configuration.
  • Reading application settings from a database or your application's web.config.

The Solution

In order to switch data stores during runtime we need to be able to switch an interface's implementation on the fly and a design pattern that can help us achieve such is the the Abstract factory pattern.

What is an abstract factory?
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn't know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

Our abstract factory will be responsible performing a runtime check to see whether the file store should be a database or the file system - or any other file store for that matter. One we know what type of file store is to be used our factory can create an instance of our stoage implementation that will will implement an interface that all of our persistance options will have to implement.

We will then hook our abstract factory up to StructureMap to ensure that our factory's dependencies can be injected and that our factory can return the correct storage implementation based on the runtime configuration settings. Let's begin!

First of all we need to create our Abstract factory:

public class DataStoreAbstractFactory
{
    public DataStoreAbstractFactory(IRepository repository)
    {
        /* Dependencies that are required to determine persistence implementation can be injected here; these dependencies will be managed by our IoC Container (StructureMap in this case) */
    }

    public IDataStoreInstance ConfigureStorage()
    {
/* This is the method that does most of the work, it will determine our settings at runtime and create an instance of the appropriate storage based on our configuration. */ 
    }
}

You'll notice that our abstract factory returns an in implementation of IDatastoreInstance; this interface is the contract that defines our storage implementation.

Below is a rather simplified example of our IDataStoreInstance interface the data storage implementation, but it's enough to give you an idea of how it would work.

public interface IDataStoreInstance
{
    void Save();
}
public class DatabaseStorage : IDataStoreInstance
{
    public DatabaseStorage(IRepository dbStoreRepository){
    }

    public void Save()
    {
        // Implementation details of persisting data in a database
    }
}

public class FileStorage : IDataStoreInstance
{
    public FileStorage(IRepository fileStoreRepository){
    }

    public void Save()
    {
        // Implementation details of persisting data in a file system
    }
}

Registering our Abstract factory with our IoC Container

Now that we've setup our abstract factory and added all of the implementation details for creating the appropriate instance of our IDataStoreInstance interface depending on the configuration, all that's left to do is hook it up to our IoC Container of choice. In this instance I'm using StructureMap as it's one I'm most familiar but any IoC Container will do the trick.

When we configure our IoC Container we want to ensure that any instances of IDataStoreInstance are created by our ConfigureStorage method within our DataStoreAbstractFactory class; the code sample below demonstrates how can do this in StructureMap:

public class StorageRegistry : Registry
{
    public StorageRegistry()
    {
        ...
        this.For<IDataStoreInstance>().Use(ctx => ctx.GetInstance<DataStoreAbstractFactory>().ConfigureStorage());
        ...
    }
}

By using StructureMap's GetInstance<> method we're able to let StructureMap manage the creation of our Datastore factory and the dependencies it relies on, allowing us to inject our configuration implementation that we'll use to check the file storage type at runtime. These dependencies can then be passed into our IDataStoreInstance.

Usage

Now, when we inject an implementation of our IDataStoreInstance interface our Datastore abstract factory is called into action and returns the appropriate data store implementation based on our configuration and we can continue to program against our IDataStoreInstance interface without having to worry about the underlying implementation.

public class UpdateController : Controller
{
    public IDataStoreInstance StorageInstance { get; set; }

    public UpdateController(IDataStoreInstance storageInstance)
    {
        StorageInstance = storageInstance;
    }

    [HttpPost]
    public ActionResult Index()
    {
        ...

        this.StorageInstance.Save();

        ...
    }

    ...

}

 

New website, now Azure powered

Posted on Wednesday, 11 Feb 2015

In the beginning

When I first decided to start a development blog I wasn't sure as to how much time I'd be able to dedicate to it and was concerned that, like many blogs online, my post frequency would start out string but begin to dwindle over time until it was never touched again.

With this uncertainty in mind, I didn't want to spend too much time putting together a blog so I bought a domain and setup WordPress on my Linux VPS with a simple, only slightly customised template with the intention to see how I got on.

Fast forward just over a year now and I'm still blogging with reasonable frequency and feel I have gotten to a point where I feel it's safe to say that I won't be stopping any time soon. The rewards of blogging about programming related subjects have become clear to me and I've learned a great deal from investigating a subject enough to confidently write a blog post; and with this in mind I decided it was time to commit to spending some time and effort in updating my upgrading my blog to aid reader retention and act a platform for me to continually develop and evolve over time.

About the new blog

Whilst I was perfectly happy with WordPress as a blogging platform (I have reservations about the language used to create it but that's another story!), I was keen to develop a solution in ASP.NET, and whilst conscious that I did not want to reinvent the wheel, I built myself a simple administration area that I can use to create and maintain posts. I've also been looking at other design patterns and techniques over the past few months and creating a blog seemed the perfect way to put some of them to practice and live with them a while to see their worth.

For those interested in what I used under the hood, below is the technology stack and why I chose to use them:

ASP.NET MVC

Being an ASP.NET developer MVC was an obvious choice. It's a great, extensible framework that I love the more and more I use. I was tempted to dive into using ASP.NET MVC vNext but I decided to wait a bit until I cross that bridge, but it's certainly something I entend on doing.

Dapper ORM

Initially I started out using Entity Framework, but given the simplicity of the blog and desire for speed, decided to give StackOverflow's Dapper ORM a try. It's a mega lightweight ORM created and used internally by StackOverflow who built it with speed in mind. I've really enjoyed using it and will no doubt be using it couldn't recommend it enough when simplicity and speed are what you're after. As an example of what Dapper does, among many of the other benefits, Dapper allows you to easily hydrate POCO objects like so:

public class Dog
{
    public int? Age { get; set; }
    public Guid Id { get; set; }
    public string Name { get; set; }
    public float? Weight { get; set; }

    public int IgnoredProperty { get { return 1; } }
}            

var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });

dog.Count()
    .IsEqualTo(1);

dog.First().Age
    .IsNull();

dog.First().Id
    .IsEqualTo(guid);

Dapper also allows you to map a single row to multiple objects and allows you to process multiple result grids in a single query.

MediatR

This was an interesting choice and proved a real eye-opener to me.

I've always found software architecture an interesting subject and one that I've always gravitated towards, and being a frequent reader of Jimmy Bogard's blog (creator of AutoMapper, and technical architect at Headsprings in Austin,Texas), I found his Putting your controllers on a diet blog posts particularly interesting as they introduced me to Command - Query Separation (CQS), and an alternative approach to the typical n-tier architecture that any enterprise developer will be familiar with - and Mediatr is a 

Being a separate subject in itself that deserves its own blog post, CQS is the process of breaking a solution down into simple, isolated Command or Queries; in this instance, using Jimmy Bogard's MediatR library. When you do this you realise that the service layer becomes redundant and your code can becomes far more succinct and expressive.

Azure

I've been playing around with Azure for sometime now and decided to use it as my hosting provider. Using a shared instance that costs just a few pounds a month, Azure has done a great job in removing many of the issues you can have when setting up a website.

Personal targets and goals for 2015

Posted on Wednesday, 21 Jan 2015

With 2014 now out of the way I always feel like it's a good idea to start 2015 with a blog post outlining my targets and goals for next year ahead.

As a software developer, the main benefit you get from setting yourself yearly goals like this is it forces you to look at your existing strengths and weaknesses (we all have weaknesses, we just need to be honest about them) and areas that you feel can be improved. This means that throughout the year as you work towards improving these areas that are lacking, you're focused on exactly were you need to spend time to improve to ensure that year on year you're going in the right direction and that in 3 years time when you look back at yourself 3 years ago, you'll see that you have improved and haven't stagnated.

I always feel it's important to set yourself only a few goals, 3 or 4 at the most. Setting yourself anything more can start to become unrealistic and can often result in you not spending enough time on each goal, or spreading your time to thin, resulting in no noticeable improvement over the year.

So here are my goals for 2015:

Goal 1: Get dangerous with Javascript

Whilst I've always been comfortable writing JQuery, and to a lesser form Javascript; I've always felt that my knowledge in the area was patchy. I can get by with it, but I feel there is room for improvement.

As I consider myself a polyglot programmer I feel being dangerous with Javascript will be another string to my bow as a software developer for the following reasons:

  • Whether you love or hate Javascript, there's one thing for sure and that is that it's here to stay.
  • Javascript is a great transferable skill to have. You may move from one language to another (say C# to Java, or .NET to Play Framework or Ruby), but providing you're still working on a web stack then your Javascript skill remain.
  • I strongly believe that having strong front end skills is a great way to separate yourself from other developers.

So this year my main goal is to improve really develop my Javascript knowledge and skills.

Goal 2: Contribute to more open source projects

Having always been a great supporter of the open source software movement (not to mention a consumer of open source software too!) this year I'm keen to find some projects to get involved in. I'm also keen to get working on developing and open sourcing some more projects.

Whilst I have contributed to open source projects in the past, I don't feel I've added as much value as I could do. Generally a lot of my contributes have been documentation and UI related issues, which, whilst important - don't give you the added valuable feedback and learning you gain when committing code and having other developers review your code.

As well as contributing to existing open source projects, I'm also keen to start a few of my own. Whilst I do have one or two projects currently on my GitHub account that have users, I'm keen to write some more as I find writing a plugin or a piece of software that other's find useful is a rewarding experience.

(Since writing this post I'm already on my way to acheving this goal which you can read about here).

Goal 3: Increase the frequency of my blog posts

Another of my goals this year is to increase the frequency of my blog posts.

Having only started blogging this year I've found it an incredibly rewarding and valuable experience. It's great getting feedback from other people and writing blog posts about programming topics really does help drill the subject matter into your brain.

When starting out blogging I felt no one would take much interested in some of the subjects I wanted to discuss - especially when you take into consideration the plethora of other great resources/developer blogs online. Yet I've been pleasantly surprised by the attention some of the posts has received. So this year I'm going to try and improve on the frequency of my blog posts.

I'd really like to achieve a blog post a week but whether I can get my thoughts out on paper that quickly is another story.

Bonus Goal: Achieve over 8,000 points on Stack Overflow

Over the past few months I've become quite active on Stack Overflow. I particularly enjoy answering questions relating to StructureMap. At the time of writing I have 2,266 points to my name - with an aim of making it to 8,000 by the end of the year. This, I feel is going to be a challenging figure to reach, but one that is achievable.

I've found that Stack Overflow is another great resource to learn from. Especially when answering questions that you have no solid knowledge of as they force you to research the subject enough to construct a solution to the user's problem.

Conclusion

So, there we have it; my 3 (4 including the bonus) goals to aim for this year. I've tried not to have too many as I don't want to spread my time to thin, and I feel each goal requires enough work to make achieving it a challenge, yet providing me with enough value that by the end of the year I'm a better developer than I am at the start.

I used to use a mug for every beverage, now I use this!

Posted on Sunday, 11 Jan 2015

I wouldn't normally create a blog post about a mug, but as a programmer I thought this programmer's "Cup of type T" was clever enough to merit sharing it with my readers.

I originally spotted it at a zazzle.co.uk, but having read less than enthusiastic reviews about the store and the quality of their service offered I decided to look elsewhere. Ultimately I ended up getting it printed myself via vistaprint.co.uk for about the same price.

Harnessing your IoC Container to perform application event tasks in ASP.NET MVC

Posted on Monday, 29 Dec 2014

I've always found software architecture a fascinating subject, and one area I'm particularly interested in at the moment is dependency management.

Recently I've been reading a lot about IoC patterns and best practices, and being a subscriber to PluralSight.com I stumbled across a fantastic course by Matt Honeycutt titled "Build Your Own Application Framework with ASP.NET MVC 5". The video course presented a whole array of work that can be done to increase productivity within ASP.NET MVC, and one part of the course that particularly stuck out was the use of start-up tasks.

As an aside, I would highly recommend checking out Matt Honeycutt's course if you've got an active subscription. For those who do not have a PluralSight subscription then PluralSight offer a free trial so you can sign up and watch the course for free. It's 3 hours 25 minutes in length and packed full of tips for modifications, functionality and extensions that can make you more productive in ASP.NET MVC.

The problem

As an ASP.NET MVC application grows so does the use of the application event methods accessible from Global.asax.cs such as Application_Start, Application_BeginRequest, Application_EndRequest and so on. After a while these methods can become unmanageable and messy as more and more functionality is tied into the application events.

Let me demonstrate with an example. Take this simple Application_start method:

protected void Application_Start()
{
     IContainer container = StructureMapCoreSetup.Initialise();
     container.Configure(c => c.IncludeRegistry<DefaultRegistry>());

     StructureMapResolver = new StructureMapDependencyResolver(container);
     DependencyResolver.SetResolver(StructureMapResolver);

     ViewEngines.Engines.Clear();
     ViewEngines.Engines.Add(new RazorViewEngine());

     AreaRegistration.RegisterAllAreas();

     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
}

If you look closely you'll see that this method is responsible for the following actions:

  1. Setup our IoC container (in this case it's StructureMap)
  2. Register it with ASP.NET MVC's dependency resolver
  3. Clear existing view engines and explicitly add Razor
  4. Register all areas of the application
  5. Register any global filters
  6. Register the application routes
  7. Finally register the application's Javascript and CSS bundles

Even with these reasonably tidy 7 steps, you can see how the method has the potential to become quite convoluted.

The solution

One such way to keep these application event methods in shape and prevent your global.asax.cs class becoming a god object  is to harness the power of your IoC container and break the functionality down into modular tasks. These tasks can then by loaded by your IoC container and executed at the correct stage of the life-cycle of a page request. Let's take a look at how we can do this.

First we're going to use a simple implementation of the command pattern to define our task execution interfaces:

public interface IExecutable
{
    void Execute();
}

Now we've created our role interface we also need to create an interface for the various stages of the application's life-cycle that we wish to fire off tasks during.

public interface IRunAtStartup : IExecutable
{
}
public interface IRunOnEachRequest : IExecutable
{
}
public interface IRunAtEndOfEachRequest : IExecutable
{
}

From here we can begin to categorise our methods into nice, well organised classes based off of the interface they implement.

For instance, I often move all of the basic framework set-up tasks into their own FrameworkTasks.cs  class like so:

public class FrameworkSetupTask : IRunAtStartup
{
    public void Execute()
    {
        AreaRegistration.RegisterAllAreas();

        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

In addition to this if my project has various AutoMapper profiles then I'll move them into their own start-up task class that's fire off when the application is run:

public class AutoMapperProfiles : IRunAtStartup
{
    public void Execute()
    {
        Mapper.AddProfile(new CoreAutoMapperProfile());
        Mapper.AddProfile(new CartAutoMapperProfile());
        Mapper.AddProfile(new ProductAutoMapperProfile());
    }
}

Setting up your IoC container to execute the tasks

Now we've abstracted our various application life-cycle tasks we can use our IoC container to load and execute the tasks based on their interface type.

In the following example you'll notice that I'm using StructureMap as my IoC container. You may also notice that I'm favouring the nested container per HTTP request approach - this is a personal choice of mine so it's possible that your setup may vary. Other than this difference there shouldn't be much to change in the following examples.

The Task Runner method
The task runner is the method responsible for loading and executing the tasks accordingly. You'll notice the argument to the TaskRunner method is a nullable container. This is so I can pass a (nested) container as an argument (see Application_Start as an example), otherwise the TaskRunner method will use an existing instance of the nested container that's set up within my StructureMapDependencyResolver  class.

public class MvcApplication : HttpApplication
{
    public static StructureMapDependencyResolver StructureMapResolver { get; set; }

    protected void Application_Start
    {
        ...

        StructureMapResolver = new StructureMapDependencyResolver(container);

        var serviceLocatorProvider = new ServiceLocatorProvider(() => StructureMapResolver);
        container.Configure(cfg => cfg.For<ServiceLocatorProvider>().Use(serviceLocatorProvider));

        DependencyResolver.SetResolver(StructureMapResolver);

        TaskRunner<IRunAtStartup>(container.GetNestedContainer());
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        StructureMapResolver.CreateNestedContainer();

        TaskRunner<IRunOnEachRequest>();
    }

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        TaskRunner<IRunAtEndOfEachRequest>();
    }

    private static void TaskRunner<T>(IContainer container = null)
    {
        if (container == null)
        {
            container = StructureMapResolver.CurrentNestedContainer;
        }

        foreach (var taskInstance in container.GetAllInstances<T>())
        {
            var task = taskInstance as IExecutable;
            if (task != null)
            {
                task.Execute();
            }
        }
    }
}

As you can see our HttpApplication events are far cleaner now than they were before and will continue to remain manageable as the project grows and further functionality is added that requires hooking up to the HttpApplication events.

Conclusion

As demonstrated, creating event tasks is straight forward and can easily be set up with any IoC container. If you're using StructureMap and instead opting to use an IoC Container such Ninject or Unity then it should be easy enough to create a similar TaskRunner  method.

You'll notice that for this example I've set up event tasks for the main HTTP events (Application_Start , Application_BeginRequest and Application_EndRequest) but this pattern can easily be applied to some of the other HttpApplication events such as Application_Error.

I've used this approach in various ASP.NET MVC projects with great success. The only drawback I've been aware of is the fact that you lose the ability to instantly see what occurs during your application events as they've now been moved into their own classes, though I feel this is a minor setback for the tidiness of the approach.

As mentioned earlier in my post, I would definitely recommend checking out the PluralSight course if you can.

Worth a watch: John Sonmez on creating a test automation framework using Selenium

Posted on Monday, 24 Nov 2014

Unit tests are great at testing individual, isolated pieces of functionality and go a long way in instilling confidence when writing code and especially when modifying or maintaining and existing code base. Another valuable form of testing is Test Automation; and if you've ever worked with automated tests before you'll no doubt agree that coupled with unit tests, test automation goes an extra mile in ensuring you've got maximum test overage of your system.

Test automation, much like writing unit tests, requires an initial upfront investment in writing the actual tests - but once created, these tests become increasingly valuable as your project grows and ages. However, unlike unit tests there is an even greater investment required in creating the initial framework with which to build your automation tests upon. This important step requires a good deal of thought and planning to ensure the tests you write are as efficient and maintainable as possible.

Is this additional investment I talk of worth it in the long run? I certain think so and many others that have experience with test automation would also agree.

Luckily there's a great talk by John Sonmez from SimpleProgrammer.com that takes you through how to create a Test Automation framework that I acts as a great foundation to write succinct, yet maintainable automation tests efficiently.

Improving upon ASP.NET MVC's default display annotation convention

Posted on Tuesday, 04 Nov 2014

ASP.NET MVC is great at taking a lot of the grunt work out of creating forms. However, one area that I've always felt was lacking is the way ASP.NET MVC handles outputting form property names.

As it stands, ASP.NET MVC's default behavior when outputting property names (using @Html.LabelFor() for example) is to output the property name as is. For instance, below highlights how the property name would appear if being output via a LabelFor() HTML helper.

public class ExampleViewModel
{ 
    public string Surname { get; set; } //Output: "Surname"

    public string FirstName { get; set; } //Output: "FirstName"

    public string age { get; set; } //Output: "age"
}

Whilst the output of the Surname property is fine, given that it's a single word; you'll notice that the output of the FirstName property is less than desirable and should instead be displayed as two separate words if it is to be read correctly.

If you wish to update the way the FirstName property is displayed within a view then the common solution is to use the ASP.NET's Display annotation like so:

public class ExampleViewModel
{ 
    [Display(Name = "Surname")]
    public string Surname { get; set; } //Output: "Surname"

    [Display(Name = "First Name")]
    public string FirstName { get; set; } //Output: "First Name"

    [Display(Name = "Age")]
    public string age { get; set; } //Output: "Age"
}

Why I'm not a huge fan of Display annotations

Whilst this solution will work, I'm not a huge fan of it as I generally try avoid muddying my objects with annotations if I can; especially annotations that are view specific such as the Display annotation.

Whilst I appreciate this is a view model, containing data that is destined for the view, I would argue that a view model's purpose is to represent only the data - rather than how it is displayed or formatted within the UI. That's what HTML is for, marking up our data. If we were to output the view model above via a Restful API or web service then our display annotations suddenly become irrelevant.

Another issue with the overuse of data annotations is they can really start to get messy. Take the following model for instance.

public class LoginModel
{
    [Display(Name = "Account User Name")]
    [Required(ErrorMessage = "Please fill in your user name.")]
    [MaxLen(30)]
    public string AccountUserName { get; set; }

    [Display(Name = "Account Password")]
    [Required(ErrorMessage = "Please fill in your password.")]
    [MaxLen(30)]
    public string AccountPassword { get; set; }
}

Instead I tend to favor a conventional or configuration approach to such a problem - and thankfully, due to ASP.NET MVC's extensibility, we can create our own conventional approach to displaying property names without the need to pollute our view model or data transfer objects with UI specific Display annotations.

Harnessing the power of the ModelMetaDataProvider

In order to apply our conventional approach to display properties within ASP.NET MVC we first need to look at where the display data is coming from when using an extension method such as the  @Html.LabelFor() extension used in our example above.

If we dig into the LabelFor extension (I use ReSharper which has a built in .NET de-compiler) you'll see the LabelFor accesses the display property via an implementation of ModelMetadataProvider:

internal static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, IDictionary<string, object> htmlAttributes, ModelMetadataProvider metadataProvider)
{
     return LabelExtensions.LabelHelper((HtmlHelper) html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData, metadataProvider), ExpressionHelper.GetExpressionText((LambdaExpression) expression), labelText, htmlAttributes);
}

After a little further digging you'll find that the ModelMetadataProvider is a base class of DataAnnotationsModelMetadataProvider. If you take a moment to take a look at the DataAnnotationsModelMetadataProvider class and its implementation you'll clearly see how ASP.NET MVC is accessing the Display attributes value and then returning an instance of ModelMetadata, which eventually ends up within the view helper and gets output in the view.

With this in mind, all we have to do in order to create our own conventional approach is create our own ModelMetadataProvider instance that overrides the current behavior and then register it with ASP.NET MVC.

Creating our own convention based ModelMetadataProvider

In my implementation, whilst I favor conventions over Display attributes, there may be instances where I will want to use a Display attribute, so I'm going to create a new class that extends ASP.NET MVC's existing DataAnnotationsModelMetadataProvider implementation.

After a little work this is what I ended up with:

public class ConventionalModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        ModelMetadata modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        if (modelMetadata.DisplayName == null)
        {
            modelMetadata.DisplayName = modelMetadata.PropertyName.SplitWords();
        }

        return modelMetadata;
    }
}

As you can see, all I'm doing here is calling the base (DataAnnotationsModelMetadataProvider) class' implementation of the CreateMetadata method and updating the DisplayName  property if it's not set. This means that if the DataAnnotationsModelMetadataProvider class we're extending does not find a Display data annotation on the property then it will return null. Then in our implementation we're simply getting the property name from the ModelMetadata  class and using an extension method I created (see below) to split the property name into words based on its upper-case letters, turning a string like "AddressLine1" into "Address Line 1".

public static class StringExtensions
{
    public static string SplitWords(this string value)
    {
        return value != null ? Regex.Replace(value, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ").Trim() : null;
    }
}

Registering our custom ModelMetadataProvider with ASP.NET MVC

Now all we have to do in order to use our conventional based approach to displaying property names is register our custom ModelMetadataProvider with ASP.NET MVC. This can be done by setting the Metadata provider within our website's Global.asax.cs class, like so:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        ModelMetadataProviders.Current = new ConventionalModelMetadataProvider();

        ...
    }
}

Once this is done you'll now be able to remove your Display annotations and have property names output as they are, but split by their uppercase letter, whilst still allowing you to override our conventional behavior using a Display attribute if you need to.

Taking the ModelMetadataProvider further

Custom ModelMetadataProviders are a great way to harness the power of ASP.NET MVC model metadata functionality and opens up an array of possibilities. For instance, you can easily see how you could extend our solution above to query a database for field names, allowing us to have database driven properties - this same direction can be used for multilingual sites!

I hope you've found this guide blog post helpful and if you have any questions then please feel free to ask them in the comments section below.

ReSharper not running your unit tests? This could be why...

Posted on Monday, 20 Oct 2014

Just last week I had an issue with ReSharper where it flat out refused to run my collection of unit tests. It was working fine, then suddenly it stopped and the bar within ReSharper's unit test window stayed grey whilst the spinning icon endlessly span within the parent unit class project.

After scratching my head trying to figure out what could have gone wrong, and trying multiple solutions following a bit of Google-fu (such as restarting Visual Studio, rebuilding my solution, running Visual Studio in administration mode and even restarting my computer) - I will still no closer to getting my unit tests running.

Eventually I managed to figure out what the problem was after I remembered that ReSharper had a cache that could be cleared from within ReSharper's options (Resharper > Options > Environment > General > Clear Cache), and after clearing ReSharper's cache and restarting Visual Studio I was able to run my unit tests once again without any hiccups.

It turns out that something must have happened that caused a corruption within ReSharper's cache resulting in it ignoring my unit tests.

Whilst I know this blog post is trivial, I know I'll most likely run into this issue again and feel I best document it just in case anyone else is experiencing similar issues.

About Me

I'm a software and web application developer living in Somerset within the UK and I love eating and sleeping software/web development. I stay up stupidly late most nights programming and consider myself lucky that I get to do what I love doing for a living. If I’m not found with my family then you’ll see me at my keyboard writing some form of code.

Read More

Feel free to follow me on any of the channels below.

 
 
profile for JoeMighty at Stack Overflow, Q&A for professional and enthusiast programmers

Recent Blog Posts