.net, C# tip, Clean Code, Dependency Injection, Inversion of Control, MVC

How to use NLog or Serilog with C# in ASP.NET Core

ASP.NET core is still pretty new – at the time of writing, it’s still only at Release Candidate 1. I downloaded it for the first time a few days ago to play with the sample projects, and was surprised (in a good way) by how much has changed in the default project for MVC6. Of course the standard way of using Models, Views and Controllers is still similar to how it was in recent versions of MVC – but, the project infrastructure and configuration options are unrecognisably different (at least to me).

One of the first things I do when I set up a new project is configure the instrumentation – namely logging. I’d read a new feature of ASP.NET Core is that it provides built-in interfaces for logging – ILogger and ILoggerFactory.

This is a nice feature and provides me with an opportunity to write cleaner code. In previous versions of MVC, if I’d injected a logger interface into my controller classes, I still needed to introduce a dependency on a 3rd party library to every class that used this interface. So even though I’m injecting a dependency using an interface, if I changed logging library, I’d have to modify each of these classes anyway. Of course I could write a wrapper library for my 3rd party logging library, but I’d prefer not to have to write (and test) even more code.

Having the logging interface built into the framework gives me the opportunity to clean this up. So if I now want to add logging to my controller, I can write something like the code below. You can see this doesn’t have a dependency on a 3rd party library’s namespace – just a namespace provided by Microsoft.

using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApplication.Controllers
    public class HomeController : Controller
        private ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger)
            _logger = logger;
        public IActionResult Index()
            _logger.LogInformation("Home controller and Index action - logged");
            return View();

For this post, I created a default MVC6 project, and modified the HomeController to match the code above – I just added the bold text.

So how can we integrate third party libraries into an MVC6 project?

Configure the default ASP.NET MVC6 project to use NLog

Let’s configure NLog first.

Install-package NLog.Extensions.Logging -pre
  • Then we need to add a configuration file – nlog.config – to the root of our project. You can get a perfect example from github here – just remember to change the file locations in this config file to directories that exist in your environment.
  • Finally, modify the Startup.cs file’s Configure method by adding a couple of lines of code.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

Now just run the project – notice I didn’t need to make any changes to my HomeController class. My project created a log file named “nlog-all-2016-03-27.log” which has the text:

2016-03-27 00:27:29.3796|WebApplication.Controllers.HomeController|INFO|Home controller and Index action - logged

Configure the default ASP.NET MVC6 project to use Serilog

Let’s say for whatever reason – maybe you want to use message templates to structure your logging data – you decide that you’d prefer to use the Serilog library instead of NLog. What changes do I need to make to my project to accommodate this?

Previously, if I’d wanted to change logging library, I’d have had to change every class that logged something – probably remove a namespace inclusion of “using NLog” and add a new one of “using Serilog”, and maybe even change the methods used to log information.

But with Asp.NET Core, I don’t need to worry about that.

  • First I need to install a pre-release nuget package for Serilog;
     Install-package Serilog.Sinks.File -pre
  • Next, I need to modify the Startup.cs file in a couple of places – the first change goes into the Startup method:
public Startup(IHostingEnvironment env)
    // For Serilog
    Log.Logger = new LoggerConfiguration()

The next change goes into the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

That’s it – after running the project again, I had logs written to the file at C:\users\jeremy\Desktop\log.txt, showing the entry:

2016-03-27 00:01:46.923 +00:00 [Information] Home controller and Index action - logged

Obviously I can also safely remove the NLog packages and configuration that this point.


So you can see the new ASP.NET Core framework has made it super easy to swap out logging library dependencies. A big advantage for me is that the logging interface used by each file is now part of the framework that Microsoft provide, which means my classes aren’t tightly coupled to an implementation.

.net, Clean Code, Security

Using C# to create a bitmap of a fingerprint from the BioMini scanner and Neurotec FFV SDK

Previously, I wrote about my experiences with the BioMini fingerprint scanner from Suprema and using it with the Neurotechnology Free Fingerprint Verification SDK. The last thing I mentioned in that post was that I’d research how to use these tools to scan a fingerprint and use .NET to generate a bitmap image of the finger that was scanned.

There is obviously a C# sample application bundled with the Neurotechnology FFV SDK – this is a Windows Forms application, and has quite a lot of functionality built around Enrollment (the act of scanning a fingerprint), Verification (the act of comparing a fingerprint to another), and storing fingerprints in a local database.

At this point, I am really just interested in scanning the fingerprint, and generating a bitmap of the scanned image. I wanted to cut through all of the extra sample applications code, and write the absolute bare minimum code necessary to do this. I also wanted to make this code clean – potentially with a view to creating a Nuget package.

First I designed what the interface needed to look like – I wanted to enroll a fingerprint, and create a bitmap file. Also, I wanted to make sure that the resources used by the library were released, so I knew I needed to implement the IDisposable interface. I designed my interface to look like the code below.

public interface IFingerprintScanner : IDisposable
    void CreateBitmapFile(string path);
    void Enroll();

Next I needed an implementation of enrolling a fingerprint and generating the bitmap image.

Enrollment and image generation is pretty straightforward – the Neurotechnology FFV documentation is extremely useful for this. There are three steps:

  • First create a scanning engine, based on the Nffv object in the FFV SDK. This object takes three parameters – the verification database name and password (which  I don’t care about, I just want to enroll), and a string representing the manufacturer code (for the BioMini scanner, the manufacturer code is “Suprema”);
_scanningEngine = new Nffv("FakeDatabaseName", "", _manufacturerCode);
  • Then call the Enroll method, which makes the scanner hardware switch on and wait for someone to put their finger on the screen. This returns an NffvUser object, which contains the information scanned in.
_scannerUser = _scanningEngine.Enroll(_timeout, out engineStatus);
  • Finally, I can then call the GetBitmap() method on the NffvUser object, which returns a Bitmap object.
var image = _scannerUser.GetBitmap();

I decided to create a scanner class that was abstract, which would take the manufacturer code as a parameter – the class looks like the code below:

public abstract class AbstractFingerprintScanner : IDisposable, IFingerprintScanner
    private Nffv _scanningEngine;
    private NffvStatus engineStatus;

    private NffvUser _scannerUser;

    private uint _timeout;

    private string _manufacturerCode;

    public AbstractFingerprintScanner(uint timeout, string manufacturerCode)
        _timeout = timeout;
        _manufacturerCode = manufacturerCode;

    public void Enroll()
        _scanningEngine = new Nffv("FakeDatabaseName", "", _manufacturerCode);
        // when this next line is executed, a signal is sent to the hardware fingerprint scanner to start detecting a fingerprint.
        _scannerUser = _scanningEngine.Enroll(_timeout, out engineStatus);

    public void CreateBitmapFile(string path)
        if (engineStatus == NffvStatus.TemplateCreated)
            var image = _scannerUser.GetBitmap();
            throw new Exception(string.Format("Bitmap was not created - Enrollment result status: {0}", engineStatus));

    public void Dispose()

        if (_scanningEngine != null)
            _scanningEngine = null;

This means that I can create a very simple concrete instantiation of the BioMini fingerprint scanner software:

public class BioMiniFingerprintScanner : AbstractFingerprintScanner
    private static string SCANNER_MANUFACTURER = "Suprema";

    public BioMiniFingerprintScanner(uint timeout) : base(timeout, SCANNER_MANUFACTURER) { }

And finally, the code I need to enroll and create a print becomes simple also:

static void Main(string[] args)
    uint timeout = 10000;

    using (var scanner = new BioMiniFingerprintScanner(timeout))
C# tip, Clean Code, MVC, Non-functional Requirements, Performance

Performance in ASP.net and C# – Bundling and Minification – Part #2

This is a very quick follow up to my earlier post on bundling and minification – an issue we found and the solution.

While examining the content of the (supposedly) bundled and minified resources, I noticed one of my CSS files wasn’t minified. It had the error message at the top of the file:

/* Minification failed. Returning unminified contents.

(2628,2): run-time error CSS1031: Expected selector, found '@charset'

After some investigation, we found that our CSS files (originally generated using SASS) had a header at the top of each file saying “@charset = ‘utf-8′”.

Removing lines like this allowed the contents to be minified. Deleting the line was fine, as we had the charset defined in our layout page meta data, and therefore this was already in the HTTP Headers for the page.

Hopefully this helps someone out there who’s having the same issue.

.net, C# tip, Clean Code, MVC, nuget, Solid Principles, WebActivatorEx

MVC Tip – Use WebActivatorEx to clean up your boot-strapping logic

The code snippet below shows the Application_Start method inside Global.asax.cs for a default MVC4 implementation.

protected void Application_Start()

In the default implementation, it looks alright – not too messy. But I’ve seen some implementations of this method which are much longer – code to manage NInject registrations, Automapper, and View Engines. So I’ve learned to see this method as somewhere that quickly starts to violate the Single Responsibility Principle.


It’s actually really easy to keep your code clean using WebActivatorEx. This is available as a nuget package that allows a class to be called either just before (or just after) application start-up.

You can install it to your project using the command in the Package Manager Console:

Install-Package WebActivatorEx 

Let’s look at de-coupling Application_Start from the reference to AuthConfig.RegisterAuth(). If we prefix the namespace with a call to WebActivatorEx (as shown below) this method will be called before the Application_Start method.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MvcApplication1.AuthConfig), "RegisterAuth")]
namespace MvcApplication1
    public static class AuthConfig
        public static void RegisterAuth()
            // ...authorization logic here...

I love this pattern because it means that the logic for calling the method at start-up is contained within the same method’s class. We don’t need to call it from the Application_Start method, so we’ve cleanly de-coupled two the classes from each other.

.net, Clean Code, Visual Studio, Visual Studio Plugin

VS2013 Extension (#3) – Clean your imported namespaces with Productivity Power Tools

This entry in the ‘Visual Studio Extension’ series is not really going to cover all the power tools in the Productivity Power Tools suite (which you can get here). I might blog about some of these later, but today I just want to cover what I think is a hidden gem in the suite which just doesn’t seem to get enough exposure.

Oftentimes when you inherit a legacy code-base that hasn’t been shown the love/technical review it deserved, each class header will looks something like this:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq;
using System.IO;
using Microsoft.Web.Infrastructure;
using System.Web.Mvc.Html;
using Newtonsoft.Json;

How many of these are really used?
And how many were made redundant when during refactoring?
And why are they out of order?

Ok, it’s fair to comment ‘what’s the big deal’ – they aren’t doing any harm, and when you compile the code they are removed anyway. But these unused imports are actually a big bugbear of mine.

  • If you don’t need to import some namespaces, they shouldn’t be there
  • It looks sloppy
  • It hides whether your class is obeying the Single Responsibility Principle – meaning if you’re importing lots and lots of namespaces, your class is probably doing more than one kind of thing
  • It’s so easy to fix, especially with the power tools extension.

Obviously in the usual Visual Studio IDE, you can right click on each class and fix them individually with the “Remove and Sort Usings” context command.

But why do this when you can do it at a project level, and do it for every class in the project?

And once you’ve cleaned your legacy project up, you can configure your settings so that every time you save, it cleans it up for you automatically!

You can read the Visual Studio team’s blog entry announcing this extension here.

You can watch the Channel 9 introduction to using the extension here.

.net, C# tip, Clean Code, MVC

MVC – Enhanced DropDownListFor – Part #2

In Part #1, I described a method signature for the Html.DropDownListFor static HtmlHelper method, which was:

@Html.DropDownListFor(m => m.UserId, m => m.UserNames, m => m.Id, m => m.Name)

In this part. I’ll write more about HtmlHelper extension method code to make this work.

That’s how you use it in Razor – but what does this method signature look like in the source code?

Each of the lambda expressions in the above method signature is an expression which is represented by Expression<Func<T1, T2>> expr. The first parameter will represent the name of the form field rendered, i.e. what the Id and Name values are for the Html <select> element. The second parameter represents the items in the <select> list. The third parameter is the property in the items from the above list which should be rendered in the value attribute of each of the <option> elements of the <select> list. The fourth parameter is the property in the items from the above list which should be rendered in the body, i.e. the innerHTML of each of the <option> elements of the <select> list. So the static extension method signature will have the this HtmlHelper<TModel> as the first parameter, with four expression parameters following, each representing one of the four lambdas in the code snippet above.

public static MvcHtmlString DropDownListFor<TModel, TListItemType, TItemId, TItemName, TSelectedValue>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TSelectedValue>> formFieldName,
            Expression<Func<TModel, List<TListItemType>>> items,
            Expression<Func<TListItemType, TItemId>> optionValueProperty,
            Expression<Func<TListItemType, TItemName>> optionInnerHTMLProperty)

Already this is starting to look quite complicated. But this is just a cleaner façade around something that is already possible. The body of this method really just gets the data required for the existing DropDownList function (which is within the System.Web.Mvc.Html.SelectExtensions namespace.) So we just need to code a conversion to the signature below.

return SelectExtensions.DropDownList(htmlHelper, formFieldName, selectList);

So let’s look at each of these parameters in turn, and how to populate them from our improved method signature. The HtmlHelper We already have this as a parameter to our overload, so we just pass it in without any modification.

The Form Field Name

Getting the property name as text is really easy – just use the ExpressionHelper on the formFieldName expression (in our example, this is m => m.UserId)

var formField = ExpressionHelper.GetExpressionText(formFieldName);

The Select List

It’s just as easy to get the selected model value from the formFieldName expression as well.

var formFieldValue = ModelMetadata.FromLambdaExpression(formFieldName, htmlHelper.ViewData).Model;

And we perform the same operation on the items expression, but just cast it as List<TListItemType>.

var itemsModel = ModelMetadata.FromLambdaExpression(items, htmlHelper.ViewData).Model as List<TListItemType>

So now we have the list, we need to convert it to a SelectList. To do this, we need to get the names of the methods used for the value and text fields. We can do this using the ExpressionHelper again.

var itemIdPropertyName = ExpressionHelper.GetExpressionText(optionValueProperty);
var itemNamePropertyName = ExpressionHelper.GetExpressionText(optionInnerHTMLProperty);

From this, populating the SelectList is a very simple operation:

var selectList = new SelectList(listItemsModel, itemIdPropertyName, itemNamePropertyName, selectedValueObject);

Final Things

The standard HTMLHelper extensions have some optional parameters, such as htmlAttributes. The DropDownList is no different – so I’ve added in the optionLabel and htmlAttributes parameters for completeness.

The Finished Code

/// <summary>
/// Returns a single-selection HTML &lt;select&gt; element for the expression <paramref name="name" />,
/// using the specified list items.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TListItemType">The type of the items in the list.</typeparam>
/// <typeparam name="TItemId">The type of the item identifier.</typeparam>
/// <typeparam name="TItemName">The type of the item name.</typeparam>
/// <typeparam name="TSelectedValue">The type of the selected value expression result.</typeparam>
/// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
/// <param name="formFieldName">Name of the form field.</param>
/// <param name="items">The items to put in the  HTML &lt;select&gt; element.</param>
/// <param name="optionValueProperty">The item identifier property.</param>
/// <param name="optionInnerHTMLProperty">The item name property.</param>
/// <param name="optionLabel">The text for a default empty item. Does not include such an item if argument is <c>null</c>.</param>
/// <param name="htmlAttributes">An <see cref="object" /> that contains the HTML attributes for the &lt;select&gt; element. Alternatively, an
/// <see cref="IDictionary{string, object}" /> instance containing the HTML attributes.</param>
/// <returns>A new MvcHtmlString containing the &lt;select&gt; element.</returns>
public static MvcHtmlString DropDownListFor<TModel, TListItemType, TItemId, TItemName, TSelectedValue>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TSelectedValue>> formFieldName,
    Expression<Func<TModel, List<TListItemType>>> items,
    Expression<Func<TListItemType, TItemId>> optionValueProperty,
    Expression<Func<TListItemType, TItemName>> optionInnerHTMLProperty,
    [Optionalstring optionLabel,
    [Optionalobject htmlAttributes)
    var formField = ExpressionHelper.GetExpressionText(formFieldName);
    var itemIdPropertyName = ExpressionHelper.GetExpressionText(optionValueProperty);
    var itemNamePropertyName = ExpressionHelper.GetExpressionText(optionInnerHTMLProperty);
    var listItemsModel = GetModelFromExpressionAndViewData(items, htmlHelper.ViewData) as List<TListItemType>;
    // if the list is null, initialize to an empty list so we display something
    if (listItemsModel == null)
        listItemsModel = new List<TListItemType>();
    var selectedValueObject = GetModelFromExpressionAndViewData(formFieldName, htmlHelper.ViewData);
    var selectList = new SelectList(listItemsModel, itemIdPropertyName, itemNamePropertyName, selectedValueObject);
    return SelectExtensions.DropDownList(htmlHelper: htmlHelper, name: formField, selectList: selectList, optionLabel: optionLabel, htmlAttributes: htmlAttributes);
/// <summary>
/// Gets the model from expression and view data.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TSelectedValue">The type of the selected value expression result.</typeparam>
/// <param name="expressionThatDefinesTheModel">The expression that defines the model.</param>
/// <param name="viewDataDictionary">The view data dictionary.</param>
/// <returns>System.Object.</returns>
private static object GetModelFromExpressionAndViewData<TModel, TSelectedValue>(Expression<Func<TModel, TSelectedValue>> expressionThatDefinesTheModel, ViewDataDictionary<TModel> viewDataDictionary)
    var metaData = ModelMetadata.FromLambdaExpression(expressionThatDefinesTheModel, viewDataDictionary);
    return metaData.Model;
.net, Clean Code

MVC – Enhanced DropdownListFor – Part #1

This is the first in a couple of posts where I overload Html.DropDownListFor to a signature that makes more sense to me.

Part #1 is about explaining the problem and creating a more friendly extension method signature.

Part #2 is about structuring the project and creating the actual code.

The addition of the enhanced HTML helpers in MVC2 made a massive difference to code readability and robustness, going from (as an example)



@HTML.TextBoxFor(m => m.UserName)

In both cases, the HTML rendered is:

<input id="UserName" name="UserName" type="text" value="the user name" />

With HTML.TextBoxFor, we get rid of the hard-coding and replace with a nice clean (and compiler friendly) lambda. I guess I have always wondered what the logic was for suffixing the original extension methods with “For”, but it’s become the accepted idiom to suggest that the extension contains a lambda.

However, from my own experience, and from speaking to others, there’s one enhanced extension method which still causes confusion among developers – DropDownListFor.

I think this is because the DropDownListFor extension doesn’t obviously follow the same method pattern abstraction as the others (nobody said it should – I’m not criticising).

So when you consider HTML.TextBoxFor(m => m.UserName), the lambda serves two purposes:

  1. The property name becomes the form field used for the HTML component’s Id/Name value.
  2. The contents of the property are rendered in the control.

HTML.DropDownListFor uses the first lambda to determine the form field for the HTML component’s Id and Name – which is consistent. But it does not store the data that is rendered in the browser. The actual contents of the dropdown list (and what’s selected) are determined by a special MVC object called SelectList.

So to display a dropdown list from a model which contains a list of usernames and user ids, and the user id to display is held in a property called UserId, you’d need to use the Razor snippet below.

@Html.DropDownListFor(m => m.UserId, new SelectList(Model.UserNames, "Id""Name", Model.UserId))

I think that looks a bit confusing. The hard coding feels like a backwards step from MVC2, and instantiating the SelectList after the lambda is definitely code starting to appear in the view, which we want to avoid.

You could of course move this instantiation across to your view model, but you’re just moving the problem – and you’ve just tightly coupled your ViewModel to the MVC implementation libraries.

I think a better method signature would be:

@Html.DropDownListFor(m => m.UserId, m => m.UserNames, m => m.Id, m => m.Name)

So now I have (what I think) is a nice overload specification for DropDownListFor. In the next post I’ll build up the project infrastructure in Visual Studio and start coding.