Latest Blog Posts

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.

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.

9 ways I improved my productivity in Visual Studio 2013

Posted on Tuesday, 07 Oct 2014

Visual Studio is a powerhouse of an IDE. One of the first things I came to appreciate when I first starting learning C# and ASP.NET MVC was how great a developer tool Visual Studio was. It far exceeds previous tools I've used in other languages such as Java and PHP.

As with all IDEs I've used I've always been fond of trying to get the best from them in order to improve my productivity, so as soon as I started using Visual Studio I immediately started researching features and functions to aid my day-to-day development, and over time I've built up a repertoire of common shortcuts that help me spend more time writing software and less time navigating the Visual Studio functions and menus.

I've always believed that one of the best ways to improve your productivity is to optimise your workflow. To do this I like to pay attention to the tasks I regularly perform when programming and see what can change about these behaviors to speed them up. For instance, I noticed I was creating classes a lot, so I got into the habit of using Resharper's create class shortcut (ALT + Insert). This minor adjustment to my workflow dramatically reduced the time it took me to create a new class, whilst helping me stay in the zone by not having to break my concentration by taking my hands off of the keyboard and reaching for my mouse.

Optimising workflow is all about rewiring our habits and training our muscle memory so you get to a point where you're pressing shortcuts and performing tasks without needing to consciously stop and try to remember the necessary shortcut. This takes time, but only a few days of constant use.

With this in mind I've decided to highlight some of the shortcuts and functions that helped me the most in improving my productivity in Visual Studio 2013.

Visual Studio Productivity Tip 1: Get ReSharper

Without wanting to sound like an Jetbrains' salesman, I honestly believe the best thing I did to improve my productivity within Visual Studio is to start using Resharper. The folks over at JetBrains have done a fantastic job of implementing some real time-saving features into Visual Studio via their plugin. They offer a 30 day free trial so at the very least give it a try and you'll see what I mean.

If you don't believe me then watch the below video:

Visual Studio Productivity Tip 2: Learn to abuse Peek Definition

Peek Definition is a fantastic feature that really helped speed up my development. It particularly comes in handy if you’re working on a method that calls/references another class or method that you need to browse at or modify. Before Peek Definition was introduced in Visual Studio 2013 I would have to rely on Resharper’s CTRL + F12 shortcut that would take me to the implementation of the method or class – resulting in the whole class being loaded in another pane and breaking my flow.

With the introduction of Peek Definition into my workflow I’m now able to quickly open up the method/class using the ALT + F12 shortcut (I’ve changed it to ALT + Q for quicker single hand access) and analyse or make modifications to it without needing to leave the class I’m in. This helps keep me in the zone and focusing on what I’m doing.

Additional tip: Use the Esc key to close the peek definition window – this way your hands don’t have to leave the keyboard.

Visual Studio Productivity Tip 4: Switch between code tabs using CTRL + TAB

Another really useful feature is the ability to quickly switch between all open tabs within Visual Studio using the CTRL + TAB shortcut. Pressing this will open a popup window with all active (open) files that you can quickly navigate to using the up and down keys on the keyboard and then release to load the selected file.

What’s especially powerful about this feature is the fact that it automatically selects the last file you opened, meaning you can quickly press CTRL + TAB to go back to your previous file . This is particularly useful if I’m working between two classes such as an interface and an implementation of the interface.

Visual Studio Productivity Tip 4: Enable Enhanced Scroll Bar

I was using Visual Studio 2013 for about a year before I learnt of the new enhanced scroll bar feature, and after enabling it I quickly realised how much of a benefit using it over the traditional scroll bar would bring.

Not only does the enhanced scroll bar help you navigate your way around a class, but it also highlights any code changes you’ve made, along with errors, bookmarks and even your caret position.

You can enable the advanced scroll bar by right clicking the scroll bar within your code editor and selecting “Toolbar Options”. You can also access it via Tools > Options > Text Editor > All Languages > Scroll Bars.

Within the scoll bar’s options you have an array of choices allowing you to specify exactly what you’d like to see highlighted on the scroll bar. As I like to keep my code window as large as possible I opted for the narrower scroll bar that whilst still providing all of the normal feedback, doesn’t take up as much room as the medium or wide scroll bar.

Visual Studio Productivity Tip 5: GoToFile shortcut (using ReSharper)

As mentioned in tip 1, if you’ve got ReSharper installed then you’ve already got access to some fantastic time-saving shortcuts at your disposal that really go a long way at helping you improve your productivity when programming. One such shortcut that will dramatically improved my productivity was the use of Resharper’s GoToFile shortcut (CTRL + SHIFT + T).

The GoToFile shortcut is probably one of Resharper’s most powerful sortcuts that allows you to quickly locate anytype of file within your solution, including views, CSS files and Javascript files. What’re more is Resharper’s GoToFile dialog has the ability to pattern match all sorts of strings. For instance, if you wish to locate a class named “LoginRepository.cs” you only need type “lr” and Resharper will display a list of all files matching your query.

Visual Studio Productivity Tip 6: GoToDefinition shortcut (F12)

Another time saving shortcut that really helped me speed up my code navigation and saves  me from taking my hands off of the keyboard is the GoToDefinition shortcut (F12).

When your keyboard cursor is over a class definition, simply press F12 to quickly open the highlighted class. The same also applies for interfaces. Whilst this may seem like a simple shortcut, when using it becomes a habit you’ll realise how much time you’ve wasted navigating to a class via the mouse.

Visual Studio Productivity Tip 7: GoToFileMember shortcut (using Resharper)

Without wanting to make this post too Resharper focused, another great shortcut at the disposal of Resharper users is the GoToFileMember shortcut (ALT + \).

Using the GoToFileMember shortcut I’m able to quickly navigate to a property or a method in a few key strokes.

Simply press ALT + \ and you’re promptly greeted with a list of all of the classes methods and properties. In addition to this you can also quickly find the property or method you’re looking for via the GoToFileMember dialog’s search field.

Visual Studio Productivity Tip 8: Quickly create a constructor

I learned about this feature later on in my Visual Studio experiences, but it quickly became my staple way of creating constructors.

Next time you need to create a class constructor, instead of typing the entire constructor out type “ctor” and then hit the tab key immediately afterwards. This will instantly add a constructor to your class for you.

Visual Studio Productivity Tip 9: Quickly create properties

In addition to creating constructors as highlighted in the above tip, Visual Studio has a similar feature for properties.

Next time you need to create a new property simple type “prop” followed by hitting the tab key to quickly create a property. Typing the type and the pressing tab again will then automatically take you to the next definition along the declaration. You can also press Shift + Tab to go back to the previous definition.

Conclusion

So there you have it; quintessential tips that helped me to improve my productivity in Visual Studio 2013. Visual Studio is a feature packed IDE that can save you a lot of work. This is only the beginning of my journey to improve my productivity in Visual Studio.

If any of these features are new to you then the worst thing to do at this point is to try out the tips mentioned and leave it at that. Improving your productivity in a tool like Visual Studio doesn’t happen overnight and takes repetition to build these shortcuts into your muscle memory. But once they are well practiced you’ll really notice a difference in your workflow.

Don’t stop there. It’s always important to stop and take an honest look at your workflow and ask yourself “What tasks to I constantly repeat, and what an be done to reduce the time it takes to perform said tasks? Is there a shortcut or Visual Studio extension that I could learn or use to speed up the time it takes me to perform such an action? Generally I find the answer is yes!.

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