Changing JSON properties to camel case notation

A quick note on how to change the JSON property names to camel notation. This is achieved by adding the following lines to the WebApiConfig class.

var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.Formatting = Formatting.Indented;

This is how it would look in the class.

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace Carrera
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            settings.Formatting = Formatting.Indented;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Using HtmlHelpers to generate Custom TextArea (Part 2)

This is Part 2 in a (very) mini series on HtmlHelper methods. Here is the link for Part 1, Using HtmlHelpers to generate HTML elements

This article is about creating a HtmlHelper for a TextArea although the same principles apply for other input controls as well. For this example I have created a simple Employee model class.

namespace HtmlHelpersDemo.Models
{
    public class Employee
    {
        public string Title { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Nothing special about the controller. An Employee object is instantiated and passed to the view. Following MVC conventions the Index view from the Home folder is rendered.

using HtmlHelpersDemo.Models;
using System.Web.Mvc;

namespace HtmlHelpersDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Employee());
        }
    }
}

Before looking at the new TextAreaFor HtmlHelper method we will look at how it is called. The method is written as an extension to the Mvc HtmlHelper class (System.Web.Mvc) which allows it to be called the same way the built in TextAreaFor methods are called using @Html..
The first example passes values in a htmlattributes parameter in the form of a class and a data_ref attribute which has an underscore rather than hyphen.

@model HtmlHelpersDemo.Models.Employee
@using HtmlHelpersDemo.Code;
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>

@Html.TextAreaFor(m => m.FirstName, new { @class = "input" , data_ref="123"}, false)

@Html.TextAreaFor(m => m.FirstName,  false)

Here is the code that does all the work. As mentioned this is written as a HtmlHelper extension method so the first parameter is not actually passed in from the calling code. Rather it defines the class the method is associated with and provides us with a local reference to manipulate, in this instance the local name of HtmlHelper is htmlHelper.

using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;

namespace HtmlHelpersDemo.Code
{
    public static class TextAreaExtensions
    {
        public static MvcHtmlString TextAreaFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object htmlAttributes, bool IsReadonly)
        {
            var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
			attributes["class"] = "form-control" + " " + attributes["class"];

            if (IsReadonly)
            {
                attributes.Add("readonly", IsReadonly);
            }

            MvcHtmlString html = default(MvcHtmlString);
            RouteValueDictionary routeValues = new RouteValueDictionary(attributes);
            html = System.Web.Mvc.Html.TextAreaExtensions.TextAreaFor(htmlHelper, expression, routeValues);
			TextAreaFor()
            return html;
        }

        public static MvcHtmlString TextAreaFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool IsReadonly)
        {
            return htmlHelper.TextAreaFor(expression, null, IsReadonly);
        }
    }
}

Lets disect what the method is doing. The first line calls a built in method passing in the htmlAttributes parameter. This method replaces underscore characters with hyphens which is how the data_ref is translated to data-ref when rendered.

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

As all text area controls is this application requires the form-control css class, it is being added to the attributes in this method along with any other css class passed in throught the htmlattributes parameter.

attributes["class"] = "form-control" + 
    (!string.IsNullOrEmpty( attributes["class"] as string) ? " "+ attributes["class"] : "");

If the IsReadOnly parameter is set, the readonly state of the control is assigned to the attribues object.

if (IsReadonly)
{
	attributes.Add("readonly", IsReadonly);
}

The final four rows create a TextArea input control from the attributes and route values if there are any.

MvcHtmlString html = default(MvcHtmlString);
RouteValueDictionary routeValues = new RouteValueDictionary(attributes);
html = System.Web.Mvc.Html.TextAreaExtensions.TextAreaFor(htmlHelper, expression, routeValues);
return html;

There rendered html for the two examples above looks like this.

<textarea class="form-control input" cols="20" data-ref="123" id="FirstName" name="FirstName" rows="2">
</textarea>

<textarea class="form-control" cols="20" id="FirstName" name="FirstName" rows="2">
</textarea>

Using HtmlHelpers to generate HTML elements (Part 1)

When working in a Microsoft MVC application, creating forms containing form elements is made easier due to the number of available HtmlHelper methods for a TextBox, DropDownList, TextArea etc. Although HtmlHelpers are not only available for form controls, there are helpers for links, view rendering, validation and more built in to the MVC libraries.

At some point there will not be a HtmlHelper that does just what is needed and want to share a few examples of customer HtmlHelpers.

Example 1. Label Helper
This example generates html label page elements. Creating the label is as simple as building a string containing the html to be displayed on the page.

using System.Web.Mvc;

namespace HtmlHelpersDemo.Code
{
    public static class Helpers
    {
        public static MvcHtmlString Label(string labelText)
        {
            return new MvcHtmlString(string.Format("<label>{0}</label>", labelText));
        }

        public static MvcHtmlString Label(string labelText, string forAssociatdControl)
        {
            return new MvcHtmlString(string.Format("<label for='{0}'>{1}</label>", forAssociatdControl, labelText));
        }
    }
}

These methods return an instance of type MvcHtmlString class which represents an HTML-encoded string. MvcHtmlString is a member of System.Web.Mvc namespace (in System.Web.Mvc.dll).

Usage
To display a label we add a using statement at the beginning of our view.

@using HtmlHelpersDemo.Code;
@{
    ViewBag.Title = "Home Page";
}

@Helpers.Label("First Name:")

@Helpers.Label("Last Name:", "SomeControl")

When rendered the page contains the labels as expected.
html-helper-label-code

This is quite a simple example but the method could be applied to creating a html table row or even the whole table.

Configuring SpecFlow and NUnit in Visual Studio 2015

How to set up Specflow and NUnit v3 in Visual Studio 2015. I have already added a new Class Library project named SpecFlowTest to an empty solution.


Step 1. Install SpecFlow extension for Visual Studio 2015

Once the SpecFlow extension is installed you will be able to add SpecFlow items to a project from the Installed Templates list of the Add Item dialog box.

  1. In the Tools menu select Extension and Updates…. This will open the Extensions Manager dialog.
  2. In the dialog choose the Online gallery in the left pane.
  3. In the right pane type specflow in the search box.
  4. In the middle pane find Specflow for Visual Studio 2015 in the results list and click the Download button. If you already have it installed a installed-tick tick will be displayed instead of a download button.

specflow-extension-vs2015

The package will be downloaded

specflow-extension-vs2015-download

A dialog will appear with a summary on the installation and prompting confirmation of the install

specflow-extension-vs2015-install

The installation will complete.

specflow-extension-vs2015-installing

Once installed a web page normally opens in Visual Studio with this address, http://www.specflow.org/guidance/first-steps. In some cases a restart of Visual Studio may be required.


Step 2. Installing NuGet packages

As usual NuGet packages can be installed via the window interface
Tools > NuGet Package Manager > Manage NuGet Packages for Solution…
or if you prefer, via the command line
Tools > NuGet Package Manager > Package Manager Console
There are a few ways to add the SpecFlow and NUnit libraries to a project,  either by installing individual packages for each product or by using combined packages.

Option 1. Combined Package

Open NuGet Package Manager and locate the SpecFlow.NUnit package.  This option will install both the SpecFlow and NUnit libraries as well as the NUnit runners for running the tests from TestExplorer in Visual Studio.  In the package description it does say NUnit version 2.6+ will be installed, at the time of this post NUnit version 3.0.0 was installed. In the future this may be a newer version of NUnit.
nuget-vs2015-specflow-nunit
And to install via command…

Install-Package SpecFlow.NUnit

Although NUnit version 3.0.0 is installed it can be upgraded to the latest version.  At this time the current version is 3.4.1.

nuget-vs2015-nunit3-update

And the NUnit update via command
Update-Package NUnit

And with that everything should be good to go.


Option 2. Installing Individual Packages

The packages can be installed separately.  Doing so would allow you to install a different test runner or a different unit testing framework.  Whatever the reason, if that is the case then you can follow these steps.

Install SpecFlow
With NuGet Package Manager open search online for the SpecFlow package.

nuget-vs2015-specflow

And via command

Install-Package SpecFlow

Install NUnit

This will install version is 3.4.1, no need for update.
nuget-vs2015-nunit3-install

And via command

Install-Package NUnit

Install NUnit3TestAdapter

Here I am installing a different test runner to the one installed in the combined package.  The result is the same, tests can be run from within Test Explorer.
nuget-vs2015-nunit3-testadapter

Install-Package NUnit3TestAdapter

If feature files have already been added to the project the below message will prompt for them to be re-generated.

specflow-change-detected

Conclusion

It seems logical to use the SpecFlow.NUnit combined package if NUnit is the unit test framework of choice.  If you will be using MSTest or a different test runner installing separate packages is not that much more work.

Setting up a Visual Studio project for testing with NUnit and SpecFlow

In this article I am going to run through my currently preferred set up for Specflow and NUnit. I have already added a new Class Library project named DemoProject.Tests to an empty solution.


Step 1. Install SpecFlow extension for Visual Studio

Once the SpecFlow extension is installed you will be able to add SpecFlow items to a project from the Installed Templates list of the Add Item dialog box.

  1. In the Tools menu select Extension and Updates…. This will open the Extensions Manager dialog.
  2. In the dialog choose the Online gallery in the left pane.
  3. In the right pane type specflow in the search box.
  4. In the middle pane find Specflow for Visual Studio 2013 in the results list and click the Download button. If you already have it installed a tick will be displayed instead of a download button.

specflow-visualstudio-extension
The extension will be downloaded.
specflow-download
Click Install to complete the installation.
specflow-install

You will be prompted to restart visual studio.


Step 2. Install NUnitTestAdapter

This step is optional.  I like to run NUnit tests from within the Test Explorer in Visual Studio rather than running the tests using the NUnit external application.  At this moment NUnitTestAdapter is not compatible with NUnit 3.0 so in the following steps I will ensure NUnit 2.6.* is installed.

Open Package Manager Console and run the following command.

Install-Package NunitTestAdapter -version 2.0.0 -projectname DemoProject.Tests

Step 3. Install the Specflow

Open Package Manager Console and run the following command.

Install-Package SpecFlow -ProjectName DemoProject.Tests

The relevant SpecFlow assemblies will now installed in the specified project.


Step 4. Install Specflow.NUnit

If you run this command without the specific version parameter this will install Specflow.NUnit 2.0.0 which includes NUnit 3.0.0.  As I intend using NUnitTestAdapter (currently only compatible with NUnit 2.6.4) I do not want NUnit version 3 installed so I have specified the -version 1.1.1 parameter, this will install Specflow.NUnit 1.1.1 which includes NUnit 2.6.0.

Open Package Manager Console and run the following command.

Install-Package SpecFlow.NUnit -version 1.1.1 -ProjectName DemoProject.Tests

Step 5. Update NUnit Version
Open Package Manager Console and run the following command.

Install-Package NUnit -version 2.6.4 -ProjectName DemoProject.Tests

This will have updated the NUnit version from 2.6.0 to 2.6.4.


For additional information see the following links:
http://www.specflow.org/resources/
http://www.specflow.org/getting-started/
http://www.specflow.org/documentation/Install-IDE-Integration/
http://ralucasuditu-softwaretesting.blogspot.co.uk/2015/06/write-your-first-test-with-specflow-and.html