Latest Blog Posts

Block or blacklist IP addresses/referral URLs in ASP.NET MVC with TrafficCop

Posted on Friday, 22 May 2015

Since starting to blog almost a year and a half ago my traffic has slowly but steadily grown month on month. In addition to this growth in blog traffic I've also noticed a sharp rise in the amount of referral spam I'm getting. At first it started off slowly but having looked back over a recent month's worth of traffic it's getting out of control - so much so that it's really starting to mess with my website's analytics.

What is referral spam?

Wikipedia sums up referral spam quite nicely:

Referrer spam (also known as log spam or referrer bombing) is a kind of spamdexing (spamming aimed at search engines). The technique involves making repeated web site requests using a fake referer URL to the site the spammer wishes to advertise.

As you can see from the screenshot taken directly from my Google Analytics account over the month, alot of hits are coming directly from referral spammers, specifically spammers trying to advertise ther social media buttons share buttons.

Having looked at solutions to prevent referral spamming, or at least stop it block it from Google Analytics, I came up with nothing. Google Analytics offers means of filtering out traffic from selected referrers but that involed setting up different filter profiles and given the amount of referral spam I'm getting I feel it's going to be a constant battle. So instead, over the course of a few evenings and work lunch breaks I created a simple solution to manage the referral spam more effectively and with finer control.

TrafficCop to the rescue!

Over the past week during the evenings and work lunchbreaks I've been working on TrafficCop; a simple package that once included in your project allows you to create rules/policies that each HTTP request is checked against. Requests that match the policy can then have a specific action performed against them.

Full instructions can be found on its GitHub page here but I'll give you a basic run through as to how it can be set up below. Before we go into detail though, I'd like to highlight that this is an early version so changes may occur.

Block bad IP addresses in ASP.NET MVC

In this example imagine we wanted to block or blacklist certain IP addresses, preventing them from accessing our website.

First of all we would need to create a TrafficCop registry that we register with TrafficCop. A registry contains our various profiles (policies) that we want to screen our traffic against. You can register as many policies as you'd like within your Traffic Cop registry.

Step 1: Creating your TrafficCop Registry

You can see below that I'm register two policies, BlockBadWebsitePolicy and RedirectReallyBadWebsitePolicy

public class ExampleRegistry : TrafficCopRegistration
{
    public ExampleRegistry()
    {
        this.RegisterRoutePolicy(new BlockBadWebsitePolicy());
        this.RegisterRoutePolicy(new RedirectReallyBadWebsitePolicy());
    }
}

Step 2: Creating a policy to register with TrafficCop

Before we can register our policies with TrafficCop we first need to create them. Creating policies is easy; simply create a policy class that derives from TrafficCopRoutePolicy.cs, doing this forces you class to implement two methods, one for screening each HTTP request and the other for performing an action on requests that matched the screening.

In this example I'm screening traffic for incoming requests from IP address 22.231.113.62 and if matched, display a 404 Page Not Found error. If you wanted to block a range of IP addresses then you could add further logic to the Match method such as reading IP addresses from a database or text file then caching the results in HttpRuntime.Cache to speed up further policy matches.

public class BlockBadWebsitePolicy : TrafficCopRoutePolicy
{
    public override bool Match(IRequestContext requestContext)
    {
        bool isBadTraffic = (requestContext.IpAddress == "22.231.113.64");
        return isBadTraffic;
    }

    public override void MatchAction(object actions)
    {
        var act = actions as TrafficCopActions;
        if (act != null) act.PageNotFound404();
    }
}

Final Step: Register our configuration with our application

Now that we've successfully configured our TrafficCop policies and registration we have to set TrafficCop up in our ASP.NET MVC application. To do this we need to register TrafficCop within our application's Global.asax.cs file. First within the Application_Start method, passing our custom TrafficCop registry that we created earlier in Step 1, like so:

protected void Application_Start()
{
    ...
    TrafficCop.Register(new ExampleRegistry());
    ...
}

Then we need to set TrafficCop to watch every HTTP request by calling its Watch method within the Application_BeginRequest method of our Global.asax.cs file.

protected void Application_BeginRequest()
{
    TrafficCop.Watch();
}

Now, any request that comes in that matches the policy we've set will automatically be handled by TrafficCop, allowing you to shape traffic as you see fit.

As mentioned above, this is the first early release so be prepared for possible changes; however if you have any improvements or changes you'd like to see made then please feel free to leave them in the comments or submit a pull request via TrafficCop's GitHub page.

That's all for now!

ObjectFactory replacement in StructureMap 3 - What you need to know

Posted on Wednesday, 29 Apr 2015

When StructureMap 3 was released early last year the ObjectFactory.cs class included an Obselete message that read "ObjectFactory will be removed in a future 4.0 release of StructureMap. Favor the usage of the Container class for future work". This harmless message caused a lot of confusion amoung some of StructureMap's users, followed by countless posts on StackOverflow looking for replacements and ways to update configurations to remove any dependencies and references to StructureMap's Object Factory.

Having had this question myself and having spent a reasonable amount of time reading suggestions and solutions online along with doing what I can to help other's with the same questions on StackOverflow I felt it would be a good idea to to collate this information into one helpful post for anyone else with the same object factory replacement questions.

Why remove ObjectFactory in the first place?

One question I've been seeing a lot of is why remove the ObjectFactory in the first place?

To cut a long story short, as StructureMap's author Jeremy Miller clearly points out in his Google Group's post, referencing the ObjectFactory anywhere in your code tightly couples your code to the ObjectFactory and thus, StructureMap. Doing this completely defeats the purpose of dependency injection - the problem that StructureMap set out to solve in the first place so the move makes total sense.

For those unsure of what I'm referring to then I'll go into a little more detail.

The problem with ObjectFactory

StructureMap aims to solve the problem of managing your application's dependencies, there are three main types of dependency injection methods that are all supported by StructureMap and other Inversion of Control Containers - these are Constructor Injection, Setter Injection and Interface Injection. I won't go into detail about these DI methods as I assume if you're reading this article then you've setup StructureMap with some knowledge of dependency management, however if you are unsure then this Wikipedia page sums these up the various types of dependency injection up quite nicely.

All of these methods of dependency injection are perfectly valid, some better more preferable than others (I say more preferable because they all have their place given the context they're used in). Ultimately these three methods of dependency injection all achieve the task of reducing the number of dependencies within a class.

In order to take advantage of the above methods of dependency injection you have to have some form of parent object that's responsible for creating an intance of the class and resolving any dependencies it may have. ASP.NET MVC comes with extension points that you can tie your IoC Container of choice into resulting in dependencies such as those injected into a controller being resolved via your IoC container.

This is all well and good, but what happens when you're working on a class or module that doesn't allow you to resolve dependencies using your configured IoC container (ASMX Web Services are especially guilty of this as it was written at a time when IoC containers a new concept and as a result the architecture doesn't provide you with any means of integrating an IoC container and using it to its full potential).

When this happens you're left to wrestle with the application to try and manage dependencies the best you can. Previously this is where the ObjectFactory would come in as it's a static instance that you could call form anywhere in your codebase and use it to resolve the calling class's dependencies. This pattern is commonly known as the Service Locator pattern and whilst it might appear harmless at first, using it can quickly become problematic for many reasons, so much so that the Service Locator pattern is known as an anti-pattern - primarily because of the tight couple that is created between your class and the ObjectFactory (amoung other reasons).

Bye-bye ObjectFactory. Now what alternatives do I have?

Generally speaking you should always favour constructor injection for dependencies; Martin Fowler sums this up quite nicely in this post where he says:

Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there's more than one way to do it, create multiple constructors that show the different combinations.

ASP.NET MVC and WebAPI provide you with the necessary endpoints to achieve this in the majority of cases such as Controllers and any dependencies within them. However there are certain areas of ASP.NET MVC and WebAPI where constructor injection isn't quite so simple, and in some circumstances - impossible. So at this point we need to re-evaluate where we're using the ObjectFactory because in some instances we can remove the reliance on the ObjectFactory from our code. A prime example of this is attributes:

Dependency Injection Friendly Attributes

One area you frequently see the use of StructureMap's ObjectFactory are within attributes, and whilst it's encourged that your attributes do not contain behaviour (something injecting dependencies into an attribute often hints at) there are means of harnessing constructor injection within attributes as described in Mark Seeman's Passive Attributes blog post without introducing behaviour into your attributes.

If no other form of dependency injection is possible

If you've exhausted all possible avenues for managing your class's dependencies without the need for a service locator then unfortunately the only option you're left with is to create your own instance of the ObjectFactory as StructureMap's creator, Jeremy Miller stated with the following response to this question on Twitter.

Assembly scanning isn’t cheap and you (almost?) always wanna cache the results. So, yeah, in that case you’re going to have to write your own ObjectFactory. Someday all that bad old MS tech will go away.

With this advice coming from the horse's mouth so the speak, the following is a simple implementation (taken from this StackOverflow answer following a discussion on the creation of a container with the answer's author) of what the ObjectFactory is essentially doing that you can use in your code.

public static class ObjectFactory
{
    private static readonly Lazy<Container> _containerBuilder =
            new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);

    public static IContainer Container
    {
       get { return _containerBuilder.Value; }
    }

     private static Container defaultContainer()
     {
        return new Container(x =>
        {
               // Load your configuration
         });
     }
}

I would suggest you adapt the code above to suit your needs to prevent yourself duplicating your SM configuration.

Conclusion

People have questioned why the ObjectFactory must be removed from StructureMap, suggesting that it should be left in and used at the user's own peril; however I'm in favour of removing it as it makes you stop and think about your application's architecture. By removing the ObjectFactory we're also forced to further decouple our application from StructureMap by creating our own service locator meaning if you every decide to switch to another IoC Container then you won't have to go through your application picking out the ObjectFactory.

My first code contributions to an open source project

Posted on Monday, 30 Mar 2015

Release 2.5.0 of the Shoudly assertion framework is a bit of a significant release for me. Not because it introduces some great enhancements to what's already a fantastic library 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 contributing 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?

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 have recently fallen in love with .NET and C#. During my time programming I'm ashamed to say that I've not contributed to any projects in what I would consider a meaningful manor. When I look at what's held me back it generally boils down to the following two reasons:

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 extremely 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.

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