Tuesday, 27 March 2012

No test runner icons when using NUnit with CodeRush test runner

Recently, I experienced a problem trying to get the CodeRush test runner to run on my machine, here's the full story.

I was working on an MVC project that had no test project attached, so I added a "Class Library" project to the solution, added NUnit to the project via NuGet and started writing some tests. Unfortunatley, after writing the tests I couldn't get any of them to run. If I selected 'Run Tests' from the project menu Visual Studio told me it couldn't find any tests, and the test tube icons that CodeRush adds to unit tests were not apperaing next to my tests.

The Solution

After faffing around for quite some time I realised you need to install NUnit first before the test runner will work. So I headed over to www.nunit.org and installed NUnit 1.5. After NUnit has been installed you can check that it's set-up and ready to run alongside CodeRush by selecting the 'DevExpress' menu in Visual Studio then choosing the 'Options' option then choosing the 'Unit Testing' node and the 'Test Runner' option. You should then see something similar to this -


You can (just about) see from the screenshot above that the version of CodeRush I'm running only lists versions of NUnit up to 1.5, so I chose to install the 1.5 version rather than the newer 1.6 version. I presume if I updated CodeRush to the latest build it would recognise version 1.6.

Having installed NUnit all I needed to do was remove the reference to NUnit 1.6 from my test project and add a reference to the 1.5 version to match the installed version of Nunit on the machine. Once I'd done this everything clicked into place and the icons appeared!


Before solving the problem, I Googled for a solution for quite some time, and couldn't find anybody who'd had a similar experience, but it's possible that I'm the only person dim enough not to realise that you need to install the test framework of your choice to get the the test runner to work. I guess if I'd installed NUnit via the traditional 'msi' route rather than using NuGet (which I presume only installs the NUnit dll) then I'd have never encountered the problem.

Wednesday, 29 February 2012

Object Initializers (or Initialisers) in .Net

This post contains nothing new, it's about a feature that was introduced in 2007, but I wanted to write a short post about .Net initializers with examples in C# in VB.Net, and what's below is the result of that urge. Please read on if you're interested .....

Before the advent of in-line initializers in .Net 3.0, you'd have to do something like this if you wanted to assign values to properties on an object -

class SuperHero {

 public string Name {get;set;}
 public string SuperPowers {get;set;}
 public string CostumeDescription {get;set;}
}

SuperHero superhero = new SuperHero();
superhero.Name = "Spiderman";
superhero.SuperPowers = "Spider powers!";
superhero.CostumeDescription = "Red and blue, some web patterns";
The above example is in C#, here's what you'd need to do in VB.Net -
Class SuperHero
 Public Property Name As String
 Public Property SuperPowers As String
 Public Property CostumeDescription As String
End Class

Dim superhero As New SuperHero()
superhero.Name = "Spiderman"
superhero.SuperPowers = "Spider powers!"
superhero.CostumeDescription = "Red and blue, some web patterns"
The code above can be shortened if we add a constructor to our object, as the C# sample below demonstrates -
class SuperHero {

 public SuperHero() {}

 public SuperHero(string name,string superpowers,string costumedescription) {
  this.Name = name;
  this.SuperPowers = superpowers;
  this.CostumeDescription = costumedescription;
    }

 public string Name {get;set;}
 public string SuperPowers {get;set;}
 public string CostumeDescription {get;set;}
}

SuperHero superheroconstructor = new SuperHero("Spiderman",
                                               "Spider powers!",
                                               "Red and blue, some web patterns");
We can do the same in VB -
Class SuperHero

 Public Sub New()
 End Sub

 Public Sub New(name As String, superpowers As String, costumedescription As String)
  Me.Name = name
  Me.SuperPowers = superpowers
  Me.CostumeDescription = costumedescription
 End Sub

 Public Property Name As String
 Public Property SuperPowers As String
 Public Property CostumeDescription As String

End Class

Dim superheroconstructor As New SuperHero("Spiderman", "Spider powers!", "Red and blue, some web patterns")
Everything changed in .Net 3.0 though, it provides us with the ability to assign a property's values in-line. Which means we can do the same as we did above, but with much less code and without having to define a constructor. An example of how to do this is given in the C# code below -
SuperHero superheroinline = new SuperHero() {Name = "Spiderman",
          SuperPowers = "Spider powers!",
          CostumeDescription = "Red and blue, some web patterns"};
So, after declaring our object we can assign it's properties in-line by assigning values to property names inside the curly brackets. This can be done in VB.Net as well, where the syntax is slightly different -
Dim superheroinline As New SuperHero() With { _
 .Name = "Spiderman", _
 .SuperPowers = "Spider powers!", _
 .CostumeDescription = "Red and blue, some web patterns" _
}
Further Reading

http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

Wednesday, 28 September 2011

View Templates in MVC 3

Somebody asked me a question today regarding display templates in MVC, the questioner had a model that looked like this -

public class Team
{
     public int TeamId { get; set; }
     [Required]
     public string Name { get; set; }
     public string City { get; set; }
     public DateTime Founded { get; set; }
}

and they wanted to set up a custom display template for the 'City' property of the 'Team' object. Ignoring the fact that this was a bit of an odd request and the questioners model data seemed to have been stolen from Steve Sanderson's MVC Scaffolding posts I asked to look at his project structure, this is what I saw -




In many ways, this looks good, a 'DisplayTmeplates' folder has been created in the 'Teams' view folder and a template has been added to the folder. If we take a look at the code that displays the 'City' display name it also looks good -

@Html.DisplayFor(m => m.City)

N.B. It's always worth double checking that the rendering code for the data you want to add to the template is using a method that will hook in to the templates, if you have code similar to this the templates will always be ignored -

Name
@Model.Name

So, what has gone wrong? The problem lies in the name of the template file. When rendering a display template, MVC will render the default template unless it finds a template that overrides the default template in either the 'shared/dispalytemplates' folder or the 'dispalytemplates' folder of the current controller. The key thing to remember though is that MVC attempts to find the template based on the type of the data being rendered not on the name of the property. So if we wanted to get the template to show for the example above we'd need to add a template file to one of the following locations -

  • Views\Shared\DisplayTemplates\String.cshtml
  • Views\Teams\DisplayTemplates\String.cshtml

The downside of this approach is it will render this template for all strings in the first instance and for all properties of type string on the 'Team' model class in the second instance. This could cause problems.

If you did want to get the city template to apply only to the city property there are a couple of options -

Specifiy the template in the 'DisplayFor' call -

@Html.DisplayFor(m => m.City,"City")

Specifiy a UI hint for the property in the model -

[UIHint("City")]
public string City { get; set; }

Finally here's an example of what the template file might have conatained -

@model System.String
@ViewData.ModelMetadata.GetDisplayName() -  
          @Model (This is special text inclued in the template)

Which would render -




If you need further information regarding the 'ModelMetdata' calls that are made in the view code you can find it here in Brad Wilson's excellent set of blog posts exploring the templating system in MVC.

Saturday, 27 August 2011

Buliding dynamic regular expressions in JavaScript

Let's say we have the following string in some JavaScript code -

var adText = "Car bumper for sale (everybody reading this has a big bum)";

and we want to remove the word 'bum' (as it might cause offence to sensitive readers) but we don't want to get rid of the 'bum' bit of bumper. Then we can do that with a regular expression -

var re =  new RegExp(/\bbum\b/,"g");
var cleanText = adText.replace(re,"(bad word removed)");

By using the '\b' word boundary anchor we ensure that we only match the full word 'bum', we also add the "g" flag to ensure all instances of the word "bum" are removed.

So, everything is working as it should, but what if we wanted to make the bad word we're searching for dynamic? Something a bit like this -

var badWord = "bum";
var re =  new RegExp("\b" + badWord + "\b","g");
var cleanText = adText.replace(re,"(bad word removed)");

So, we've changed the regular expression literal to a string (by removing the '/' characters and replacing them with '"') and added our bad word variable into the relevant part of the string, everything is good yes?

No! And this is what I always forget when doing something like this, as the regular expression we're building up is now a string so we need to escape '\' characters by adding another '\' character, like this -

var badWord = "bum";
var re =  new RegExp("\\b" + badWord + "\\b","g");
var cleanText = adText.replace(re,"(bad word removed)");

You can see a working example of everything that was described above by going to this jsfiddle link.

Saturday, 28 May 2011

An attempt to explain a generic extension method

Let's say we have a method as below -

public static bool should_be<T>(this T item, Func<T, bool> evaluationWith)
{
    return evaluationWith(item);
}

What is this doing? I'll attempt to explain. Firstly it’s worth noting that the method is an extension method which means it extends an already existing class. The method is also a generic method which means it can extend any class, so we could call the method like this on an integer -  


int i; 
i = 3; 
i.should_be(args); 

or like this on a string -


string str; 
str = "blah blah blah"; 
str.should_be(args); 

The ‘this T item’ text within the signature of the function means that within the function the variable ‘item’ refers to the class being acted upon, so in our first example ‘item’ would refer to the integer 3 and in the second example item it would refer to the string “blah blah blah”. It’s important to remember that even though the ‘item’ parameter is included in the arguments list of the function it is not passed to the function when it is called (hence each of our examples only pass one argument to the should_be function). The function derives the value of the ‘item’ parameter from the object it is being called upon.


The ‘Func<T, bool> evaluationWith’  text within the signature means that the ‘should_be’ function expects another function to be passed as the only argument to the ‘should_be’ function. This can take a while to get your head around, I find it easier to comprehend if I consider the following two function signatures -


public static void should_be<T>(this T item, Func<T, bool> evalueationWith)
public static void should_be<T>(this T item, int evalueationWith)

The second signature looks straightforward and all that has been changed from the first signature is that we are passing in a type of ‘int’ rather than a type of ‘Func<T, bool>’. In .Net the type ‘Func<T, bool>’ refers to a function which takes an argument of type T and returns a Boolean. The ‘should_be’ function defines type T as being the same type as the class that is being extended, so in our first example where we call the should_be function on the integer 3 the ‘should_be’ function expects a function to be passed as an argument that takes a single integer argument and returns a Boolean. The function below would fit the bill perfectly -

bool EqualToThree(int tint) { 
return tint == 3; 
} 

We can now extend our first example to include our newly defined function and get a functional piece of code -


int i; 
i = 3; 
i.should_be(EqualToThree); 

Here’s what’s happening in the guts of the ‘should_be’ function -


  • The function equates the variable ‘item’ to the value of the current class, in this case that means that the item variable equals 3
  • The function calls the function passed into itself (‘evaluationWith’) using the item variable as the argument to the function, so the function is effectively calling the following code - ‘isIntegerEqualToThree(3)’, the value true is returned.

For the sake of completeness here’s some code that would get our second string example working -

static bool EqualToBlahBlahBlah(string tstring)
{
    return tstring == "blah blah blah";
}

string str;
str = "blah blah blah";
Console.WriteLine(str.should_be(EqualToBlahBlahBlah)); 

Generic Method Definition

Generic methods need to be defined in a certain way in order for them to work, here’s the code contained in the class that defines the ‘should_be’ function -


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomExtensions
{
    public static class CustomExtensions
    {

        public static bool should_be<T>(this T item, Func<T, bool> evaluationWith)
        {
            return evaluationWith(item);
        }

    }
}

Note that the method is defined within a public static class. Finally here’s the code that calls the extension method as part of a simple console application -


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionGenerics
{
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {

            int i;
            i = 3;
            Console.WriteLine(i.should_be(EqualToThree));

            string str;
            str = "blah blah blah";
            Console.WriteLine(str.should_be(EqualToBlahBlahBlah)); 

            Console.ReadLine();

        }

        static bool EqualToThree(int tint)
        {
            return tint == 3;
        }

        static bool EqualToBlahBlahBlah(string tstring)
        {
            return tstring == "blah blah blah";
        } 

    }
}

You can download the full project code here.

Sunday, 15 May 2011

What's the deal with JSON? (A beginner's guide to JSON)

JavaScript Objects

You can initialise an object in JavaScript by doing this -

var person = {"name":"Kenny"}

Similarly you can make an array of objects by doing this -

var people = [{"name":"Kenny"},{"name":"Steve"}]

JSON

JSON (which is an acronym for JavaScript Object Notation) uses the JavaScript language features explained above to pass data from place to place. Let's imagine we have a very simple page that serves up the details of some Flumps.


Here's what we'd see in the browser window.


Getting at the data

A number of JavaScript libraries make it very easy to access to JSON Data, but for the purpose of this article we're going to do things the (fairly) hard way. Here's the code we'll use to get the JSON data -

window.onload = init;

var request;

function init() {
 request = getXHR();
 getData(request,'jsonarray.htm',handleRequest);
}

 function getXHR () {
 var request = null;
 if (window.XMLHttpRequest) {
  try {
   request = new XMLHttpRequest();
  } catch(e) {
   request = null;
  }
 // Now try the ActiveX (IE) version
 } else if (window.ActiveXObject) {
  try {
   request = new ActiveXObject("Msxml2.XMLHTTP");
   // Try the older ActiveX object for older versions of IE
  } catch(e) {
   try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e) {
    request = null;
   }
  }
 }
 return request;
};
 
function getData(request,url,handler) { 

 if (request != null) {
  // Kill the previous request
  request.abort();
 }

 // Tack on a dummy parameter to override browser caching
 url += "?dummy=" + new Date().getTime();

 try {
  request.onreadystatechange = handler;
  request.open("GET",url,true); // always asynchronous (true)
  request.send(null);
 }
 catch(e) {
  alert("Ajax error communicating with the server.\n" + "Details: " + e);
 }
}

function handleRequest() {;
 if (request.readyState == 4 && request.status == 200) {
  var jsonData = request.responseText;
  var displayText = '';
  var arr = eval(jsonData);
                var displayText = '';
  for (i=0;i<=arr.length;i++) {
   displayText += 'Name: ' + arr[i].name + 
                           ' - Description: ' +  arr[i].description + '\n';
  }
                alert(displayText); 
 }
}
The snippet begins with some boilerplate code that hooks up the window on load event to the 'init' function. The 'init' function then creates an XMLHttpRequest object via the 'getXHR' function. The browser uses the XMLHttpRequest object to send AJAX http requests. Different browsers use different implementations of the XMLHttpRequest object so the code in the 'getXHR' function needs to deal with a number of different scenarios. Once the code has created the XMLHttpRequest object it uses it to send a 'GET' request to the page that holds the JSON data. Most of this code is quite straightforward, this line -
request.onreadystatechange = handler;
assigns a callback function to the XMLHttpRequest object that will be called once the XMLHttpRequest object has received a response. The code assigns the 'handleRequest' function which is defined at the bottom of the code block. The 'handleRequest' function firstly checks the response we have received is the right kind of response, if it is, then it assigns the data received to a variable and uses the JavaScript 'eval' function to convert the JSON data into an array. We can then loop round the array and alert our Flump data. (The code in this section was heavily 'influenced' by 'Head First JavaScript')
The dangers of eval

In the code above we use the 'eval' function to convert the JSON string into a JavaScript object. This presents a security risk, as what ever is passed back to our page will be unquestionably converted to JavaScript and run in our page. For instance if for some reason the following string was returned -
alert('All flumps stink!');
Then we wouldn't get the result we wanted at all. To get around this we could use a JSON parser like the one written by Douglas Crockford. The parser will parse the response we recieve and prevent any malicous JavaScript being executed in the browser. To use the parser download and include the 'json2.js' file in your page -
<script src="script/json2.js"></script>
In our example we would then change the 'handleRequest' function to this -
function handleRequest() {;
 if (request.readyState == 4 && request.status == 200) {
  var jsonData = request.responseText;
  var displayText = '';
  var arr = JSON.parse(jsonData);
  var displayText = '';
  for (i=0;i<=arr.length;i++) {
   displayText += 'Name: ' + arr[i].name + 
                           ' - Description: ' +  arr[i].description + '\n';
  }
  alert(displayText); 
 }
}
N.B. Most modern JavaScript libraries will handle the JSON parsing for you as part of the function that retrieves the JSON content, and some modern browsers provide the 'JSON.parse' function as standard. I've included the full example here only for the sake of completeness.

Sunday, 1 May 2011

Blog moves to Blogger

As of today I've moved the blog from a Subtext solution hosted on discountasp.net to the blogger platform.

Reasons for moving

I like Subtext, but I was paying to host the site on discountasp.net, and discountasp only provide you with one app pool when you sign up with them. This meant it was becoming increasingly difficult to juggle the websites I'm hosting and it seemed like a logical step to move the blog away to make things a bit less complicated.

Blogger

Also, I've been really impressed with Blogger. I initially thought that I'd have to spend some time setting up something like Wordpress but Blogger has been easy to set up and has required no extra hosting etc. Here's a few issues I ran into and how I resolved them.

Showing highlighted code snippets - Blogger gives you full control over the CSS and scripts that you load into your blog so as long as the scripts you require are on a third-party server you can link to them easily. SyntaxHighlighter one of the more popular blog syntax highlighters provide hosted versions of their scripts to help with this.

Linking to images/scripts not hosted on a third party server - I found two ways to do this, it's possibe to use dropbox to host web files and I've also used a free web site from http://www.000webhost.com/ to host a number of image files.

Post Import/Export - Shamefully I've only posted to my blog 22 times in over two years(!) so I transferred the posts manually, by scraping the HTML out of Subtext and straight into Blogger.