.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();
            image.Save(path);
        }
        else
        {
            throw new Exception(string.Format("Bitmap was not created - Enrollment result status: {0}", engineStatus));
        }
    }

    public void Dispose()
    {
        _scanningEngine.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))
    {
        scanner.Enroll();
        scanner.CreateBitmapFile(@"C:\Users\jeremy\Desktop\myFingerprint.bmp");
    }
}
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()
{
    AreaRegistration.RegisterAllAreas();
 
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
}

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.

WebActivatorEx

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.TextBox("UserName")

to

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

.net, C# tip, Clean Code

C# tip – use the yield keyword to clean up your code

I’ve recently needed to convert from one list of objects to another – specifically, I have a ViewModel containing a custom generic List<User> of users, and to display on my view, I needed to convert this to List<SelectListItem>.

This is a very simple operation:

private static IEnumerable<SelectListItem> ConvertListItemsToSelectList<TList>(IEnumerable<User> users, int valueToMarkAsSelected)
{
    var selectList = new List<SelectListItem>();
 
    foreach (var user in users)
    {
        selectList.Add(
            new SelectListItem {
                Value = user.Id.ToString(),
                Text = user.Name,
                Selected = (user.Id == valueToMarkAsSelected) 
        });
    }
 
    return selectList;
}

I’m not sure that I like the explicit declaration of the List<SelectListItem> at the top of the method. Fortunately, the yield keyword makes this unnecessary.

Yield removes the need to have an explicit declaration of an object to hold the state of an enumeration. So instead of declaring the List<SelectListItem> at the top of my method, I can just use the code below.

private static IEnumerable<SelectListItem> ConvertListItemsToSelectList<TList>(IEnumerable<User> users, int valueToMarkAsSelected)
{
    foreach (var user in users)
    {
        yield return new SelectListItem {
            Value = user.Id.ToString(),
            Text = user.Name,
            Selected = (user.Id == valueToMarkAsSelected) 
        };
    }
}

It’s a small change – but the code’s a little cleaner.

You can read more about the yield keyword on MSDN here.