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

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

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.

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:

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.

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:

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:

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

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:

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…

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

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 any type 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.


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.

My experiences programming on a Surface Pro 3


Last week I decided to pick up a Surface Pro 3. I’ve been following the Surface Pro hardware line for some time now but have been reluctant to commit to one as there were certain factors in the previous incarnations that meant it probably wasn’t the best choice for me at the time.

With the Surface Pro’s third iteration, all of the niggles I had with them were gone so I finally decided to jump in.

In order to fund the Surface Pro 3 I decided to part with my existing portable development machine – my Macbook Pro Retina that I was running Windows 8.1 on via Bootcamp.

Over the past few years my Macbook Pro has proven to be a great development laptop so making the choice to switch to a Surface Pro 3 wasn’t an easy choice to make, and despite receiving glowing reviews I couldn’t find any reviews or comments from a software developer’s perspective on how it performs as a development machine. So having lived with the Surface Pro 3 for a week or so now I decided to highlight what I feel the pros and cons of the Surface Pro 3 are from a software developer’s perspective, and how it performs as a portable development machine.

If you’re reading this and unaware as to the hardware specifications/features of the Surface Pro 3 then you’ll probably find more suitable information somewhere else. This post presume you already know the stats of the Surface Pro 3 and are keen to find out how it performs as a development machine.

Programming using the Surface Pro 3 keyboard and trackpad

My first concern when committing to the Surface Pro 3 was the keyboard. As any software developer will know, the keyboard is his main tool so it’s important that it’s responsive and comfortable to type on for long periods of time. Being a bit of a shortcut addict it was also important for me that the keyboard not be too small as to force my hands into weird positions when pressing some of the shortcuts I’ve grown to rely on.

Thankfully I was pleasantly surprised. Naturally it took me a short while to feel comfortable touch typing on the keyboard, especially when programming and requiring the use of certain special characters, but before long I was programming away without and concerns. Only occasionally hitting the wrong key – but that will work itself out in due time.

The keyboard is just the right size to feel familiar to the faster typers out there and provides a good level of feedback with a satisfying “click” as you press each key.

As for the track pad, I wouldn’t go as far as saying it’s terrible – but it’s certainly not the best trackpad I’ve used. It’s perfectly fine for navigating around Visual Studio or IntelliJ IDEA but it can feel a little unresponsive at times.

Typing on your lap (or lapability as Microsoft call it)

One of the criticisms of the Surface Pro 2 was the difficultly in typing on your lap. Because the keyboard clips into place by a strong magnet and the screen’s kick stand only had 3 points at which it could be moved to, it made typing very difficult due to the limited angles.

Thankfully this has been sorted in the Surface Pro 3. With the kick stand being adjustable to any level, you can lower or raise the screen to any level that suits you. What’s more is the keyboard has an additional magnet in it that allows the keyboard to be docked at a slight angle to further aid the positioning of the keyboard to a suitable level based on how or where you’re sitting.

In fact, as I write this I’m laying in bed with the keyboard comfortably on my lap with no movements or fear of the keyboard become disconnected from the display screen.

One of my fears before purchasing the Surface Pro 3 was the strength of the keyboard magnet. I was concerned that if, for some reason, I were to knock the screen that the magnet wouldn’t be strong enough to keep the display from disconnecting and falling over, possibly onto the floor. Thankfully I quickly realised this should not be a concern as the magnet is incredibly strong and holds the keyboard and display firmly together. On the contrary it actually requires quite some force in order to separate the screen from the keyboard.

Is the Surface Pro 3 screen too small for software/web development?

Before committing to selling my Macbook Pro Retina to fund my Surface Pro 3 purchase, I did have concerns about whether the screen would be large enough for programming on. The Surface Pro 2’s screen was a little too small for my taste, but Microsoft have increased the size of the screen for the Surface Pro 3, providing me with more than enough screen real-estate to write code without the need for constantly scrolling across or up and down the page.

Running Visual Studio on the Surface Pro 3

Hardware wise, the Surface Pro 3 model I decided to go for was the i5, 8gb of memory and 256GB SDD drive, which was actually a downgrade from the i7 Macbook Pro Retina I was using before – but the additional portability of the Surface Pro 3 made the sacrifice one I was happy to make.

The majority of my development time on the Surface Pro 3 has been some rather large Visual Studio 2014 projects, followed by some Android programming in IntelliJ IDEA. During my time programming I’ve yet to experience any slow compile times. Visual Studio is a power-house of an IDE and loves to gobble up memory, but this doesn’t appear to hamper the Surface Pro 3. All in all, I’ve not noticed any performance difference between the Macbook Pro Retina and the Surface Pro 3 when programming and compiling applications.

Below is a screenshot of the system resources with Visual Studio 2013 and SQL Server running; as you can see there’s more than enough memory and CPU remaining to ensure build times are fast and the system remains responsive.


Additional ports

As someone who does a lot of Android development I was a bit disappointed to see that the Surface Pro 3 only features one USB port. As someone who prefers to test his Android apps against a real phone rather than the Android emulator it’s a slight annoyance that there isn’t a t least one more port available. This would save me from having to lug a USB adapter around with me.


Ultimately I’m extremely happy with my purchase of the Surface Pro 3 and I don’t have any regrets about selling my Macbook Pro Retina to pay for it. The Surface Pro 3 is a fantastic device that I find myself using more and more, both as a laptop and a tablet.

The fact that the Surface Pro 3 is more portable than my Macbook Pro means that I take it everywhere with me, allowing me to have a sneaky coding session when I have a bit of spare time.

Edit: If you’re considering purchasing the Surface Pro 3 as a development laptop then I highly recommend you listen to Scott Hanselman’s latest Hanselminutes podcast ‘Selecting the Ultimate Developer Laptop with Damian Edwards‘ where he and Damian Edwards openly talk about how they find the Surface Pro 3 a great development laptop.

Microsoft Azure launches Search as a service

Having only recently been switched on to how powerful and surprisingly cost effective Microsoft’s Azure services can be, I was delighted to log into Twitter this evening to be greeted with a tweet highlighting the launch of Azure’s new Search service.

Having had experience with how difficult effective search can be, it’s great to see that Azure have tackled this and turned what’s usually a complex problem into an easy service solution. And best of all? It’s free for smaller sites.

At the moment Azure’s search as a service is in preview stage, though I’ll be interested to see if they introduce any more pricing tiers considering the jump between them as highlighted below:

Storage 50 MB 25 GB per unit
Queries per Second* N/A 15 per unit
Documents Hosted** 10,000 Documents
3 Index Limit
15 Million per unit
50 Index Limit
Scale Out Limits N/A Up to 36 units
Price per Unit per Hour Free £0.107 / hour
(~£80 / month)

In the mean time though I’m most definitely going to give Azure’s search as a service a try for a few projects I’m currently working on and will no doubt report back my experiences here.

You can read more about Azure’s Search as a service preview here with information on the existing pricing structure available here.


ASP.NET Naming Conventions – how to avoid calling everything a service

Naming things can be tricky. I’ve found that when I’m creating a new class the first class name that pops into my head is usually one that doesn’t describe the function and purpose of the class I’m creating adequately enough. It usually takes a few moments of stopping and thinking to myself “What can I call this class that will describe its role clearly to other developers and/or consumers of this API, class or interface – something succinct and no longer than 4 words long” (4 words or less is a general rule of thumb I’ve picked up throughout my years programming that seems to hit the sweet spot).

Over time I would start to notice patterns occurring. For instance when developing web based applications following a typical n-tier application structure I’ve noticed it becomes very easy to label everything at the service/business logic level a ‘service’. With this in mind I started to do a little googling for naming ideas and found this little gem of a question on every developer’s favourite site that highlights a whole range of different naming ideas and conventions that might help describe that class you’re creating perfectly.

These are:

  • Coordinator
  • Builder
  • Writer
  • Reader
  • Handler
  • Container
  • Protocol
  • Target
  • Converter
  • Controller
  • View
  • Factory
  • Entity
  • Bucket
  • Attribute
  • Type
  • Helper
  • Collection
  • Info
  • Provider
  • Processor
  • Element
  • Manager
  • Node
  • Option
  • Factory
  • Context
  • Designer
  • Editor

Sessions in ASP.NET MVC using Dependency Injection

Storing and reading data from a session in ASP.NET MVC

A common approach I see whilst browsing tutorials or StackOverflow questions relating to sessions in ASP.NET MVC is the following:

And then retrieving session data like this:

What’s the problem with this?

Whilst this solution works, there’s improvements that can be made. Take a look at the code for a moment and try and think of what problems doing the above could lead to as the project started to mature.

First of all, what happens if we want to modify the what information gets stored in the session? Or even worse, we want to switch from session based storage to database storage? Ultimately we’d have to spend a great deal of time going through any controller that references the session and make changes.

Ultimately, what we’re doing by accessing the Session object directly from within the controller is breaking the D (dependency inversion) of the SOLID principles – a set of five principles of object-orientated programming and design aimed at encouraging the creation of extensible, flexible and testable software; something all developers should strive to do.

What is the Dependency Inversion principle?

Once of the most memorable definitions of dependency inversion that I’ve heard and which has stuck with me is:

“Program to an interface, not an implementation”

In the context of the code sample above, by directly programming against the Session object (an implementation) we’re creating a dependency within our controller. We can avoid doing this by using an interface type to abstract and encapsulate the session’s implementation details – allowing us to programming against some kind of simplified interface. Doing this leads to a loosely coupled controller that’s not directly depending on the existence of the Session object, but instead depends a type that implements our IUserInformation type.

This powerful thing about this is the controller does not need to be concerned about the implementation details, meaning we could easily switch the implementation to read the data from a database instead of a session object – and we wouldn’t have to touch anything in the controller.

This also makes the controller far more testable as we can easily mock the session’s abstraction.

Ok, I’m following so far. So how do we ‘invert’ our controller’s dependencies?

There are multiple types of dependency injection but the most common pattern for this type of challenge is constructor injection using an Inversion of Control Container.

In this example I’m going to use StructureMap as my IoC container of choice as it’s one I’m most comfortable with and prefer using in my day-to-day life.

The first step is to include the Nuget package for both StructureMap and StructureMap.Web. Now we’ve got the StructureMap packages we need to hook Structuremap into ASP.NET’ MVC’s dependency resolver by creating a new class (In this instance I called it StructureMapDependencyResolver.cs) and implementing the IDependencyResolver from the System.Web.Mvc package like so:

Once this is done simply add our DependencyResolver to the Application_Start method within Global.asax.cs, like so:

Now that StructureMap is hooked up to our ASP.NET MVC application, all that’s left to do is define our dependencies by creating our WebsiteRegistry.cs class that extends StructureMap.Configuration.DSL.Registry.cs, like so:

Once we’ve added our Registry we need to define how our instance of IUserInformation is constructed. In this case we want to deserialize our session object and cast it to an instance of IUserInformation.

We can now refactor our ExampleLoginController.cs file to move the dependencies outside of the controller and program against the IUserInformation interface.

Golden Nuget Package #1: RouteDebugger by Phil Haack

Whilst working on a side project written in ASP.NET MVC (version 5), I ran into some routing issues that involved routes just flat out not working. To make matters worse I was using Areas which add a little more complexity to routing (not much, but just enough to spice things) by splitting routes up into separate areas.

After spending about an hour trying to figure out why my route wasn’t working I decided to pull out the Google-fu to look debugging ASP.NET MVC routes, which is when I came across a golden nuget package written by Phil Haack called RouteDebugger.

Setup was simple, and after downloading the RouteDebugger Nuget package via Visual Studio’s awesome Nuget Package Manager tool and enabling it within the Web.config configuration file by adding the following it was up and running.

Now when you fire up your application you’re greeted with a useful debugging pane located at the bottom of your page (see below) showing you exactly what route your current page URL matches and which ones they don’t. In my instance this proved extremely valuable as I was able to very quickly identify that my route was being matched to a far more vague route before it was being hit.


Creating reusable HTML components in ASP.NET MVC using Razor

Whilst working on a side project I started to notice I was using a lot of the same HTML to create floating boxes. Whilst these boxes looked the same, the content of them changed quite dramatically; for instance, some of the content boxes contained forms, others contained straight text, like so:

As my side project progressed and grew, I found myself making more and more modifications to these HTML components so I started to look how I can encapsulate the component for greater flexibility and extensibility as my project progressed.

The solution I ended up with was creating a HTML extension modelled off of the way the the Html.BeginForm() extension works, by writing directly to the view’s context and then returning an instance of IDisposable, with the call to disposing of the context writing the closing HTML statements of my component to the view context – essentially wrapping the contents passed into the HTML extension in my HTML component.

Below is an example of what the code looks like:

Using this new HTML extension I’m now able to reuse my HTML component and fill the panel’s content in with whatever I please, like so: