Saturday, June 28, 2014

Using MongoDB with ASP.NET MVC (Pluralsight)

I have recently finished watching the Pluralsight course on Using MongoDB with ASP.NET MVC. I have been intending to look more into NoSQL for months now but have not got around to it. This course was the perfect excuse to do so!

The course starts by briefly introducing you to MongoDB and then swiftly shows you how to integrate it into an MVC application. It takes you through CRUD operations using Mongo as the data store then shows you GridFS (the file store for MongoDB) and the new aggregation pipeline model.

I was really impressed with the course (to the extent I decided to blog about it!). In the space of a few hours I went from knowing very little about a technology to being confident about how to utilize it in a project. Wes McClure is a first rate presenter who keeps you engaged through the course, supplying clear explanations and useful information for future proofing your Mongo projects. He also has a very interesting blog which is worth looking at. It's full of good advice and issues he has encountered in the real world.

This was one of my favourite Pluralsight course formats where you are able to code along to the course
and end up with the same end product. Granted you will need to code some of the razor views yourself but the important C# code for interacting with the Mongo driver is all on show.

Wes finishes the course with some great advice: Build something! I already have a couple of projects in mind to use with MongoDB.

Where to go from here... I will start watching Nuri Halperin course Introduction to MongoDB which Wes recommends as this will get you more familiar with the MongoDB server itself. I have also spied Seven Databases in Seven Weeks which looks like a great read to getting familiar with a wide variety of NoSQL databases. But most importantly, I will be developing something.

If you want a practical introduction to MongoDB from a Web Development perspective, this is the course for you.

The days of polygot persistence are upon us.

Monday, June 2, 2014

Looking at the Microsoft Store's Authentication

A few days ago I called the Microsoft Store about an order I had placed online. After discussing what I wanted to change, the operator explained that before she could make any updates to my account she needed to check my email address (up until this point, I had only told her my name and my order number) and that she would be sending a code to that address. After confirming my email address, I quickly signed in to my account, read the code back to her and from that moment on I was verified--it was as simple as that. Let’s break this down from a security perspective.

The traditional route of authentication during a telephone call is to ask a series of questions that only you “should” know the answers to. The problem is that this isn’t always the case and these answers are generally easily discoverable: Google can help with answering what year someone got married in or what their maiden name was; if you’re OK with a little more work, you could examine the public records or even just ask the individual—I doubt most people will have a problem telling you the name of their first pet if brought up unsuspiciously in conversation.


Using a verification code bypasses all of this and places the burden of authentication solely on you having access to the email account that is registered with the Microsoft Store. The assumption is that you know the password to access your email account / that you have access to your email account. Reading the verification code back is evidence of this and satisfies that you are who you claim to be.


This becomes really interesting if the operator has no access to the code and cannot proceed without it as it presents the situation, that as well as providing authentication of you, can also provide authorization for the operator. Without the code, they would be considered unauthorized and would not be able to update an account unless they were supplied the code. This works great in preventing the operator from being coerced into updating the account, as without the code, they really have no way to do this.


I’m impressed with the ease of using a verification code sent by email and the potential it has for offering both authentication and authorization. Of course, if I was unable to access my email account at the time I called, I might have a less favorable opinion; however, an easy alternative would have been to send the code to the mobile phone that was on my account.

Wednesday, May 7, 2014

Test Drive that Fizz Buzz

Fizz Buzz is a game where you count upwards saying the numbers aloud with a slight twist to try and trip you up. When a number is divisible by 3 you say "Fizz", when a number is divisible by 5 you say "Buzz" and if the number is divisible by both 3 and 5 you say "FizzBuzz". The straight forward rules of Fizz Buzz makes it an ideal problem to solve as a TDD kata as it allows you to focus on TDD practices as opposed to the implementation details.

The goal of a TDD kata is to allow you to follow the red, green, refactor pattern over and over. The idea is to first write a failing test (red), write the minimum implementation to make that test pass (green) and then refactor your code as necessary to make it more maintainable / readable.

On with the kata...

Test 1 - Instantiating FizzBuzzer does not throw an exception
Write the failing test:

1
2
3
4
5
[Test]
public void FizzBuzzer_Instantiating_ShouldNotThrowAnException()
{
  Assert.DoesNotThrow(() => new FizzBuzzer());
}
Red - This test will not compile as the FizzBuzzer class does not exist yet.

Write the minimum so the test will pass:

1
2
3
public class FizzBuzzer
{
}
Green - The test now passes.

Refactor - Nothing to refactor.

Test 2 - Value not divisible by three or five returns value
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[Test]
public void Convert_ValueNotDivisibleByThreeOrFive_ShouldReturnValue()
{
  //Arrange
  int valueToConvert = 1;
  string expectedValue = "1";
  FizzBuzzer fb = new FizzBuzzer();

  //Act
  string result = fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - This test will not compile as the FizzBuzzer class currently does not have a Convert method. The test follows the "Triple A" unit test structure. This is generally considered a best practice when writing unit tests to provide them with a consistent structure. The test also utilizes NUnit's Assert-That-Is syntax for its assertions which makes the assertions themselves more human readable - For example the above assertion reads like "Assert that result is equal to expectedValue".

Write the minimum so the test will pass:

1
2
3
4
public string Convert(int valueToConvert)
{
  return valueToConvert.ToString();
}
Green - The test now passes and the minimum functionality has been written. It is tempting to write more than is actually required but resist this otherwise you will find yourself writing additional unit tests after implementing the functionality or gold plating your code with functionality you necessarily do not actually need.

Refactor - Nothing to refactor.

Test 3 - Value divisible by three returns "Fizz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[Test]
public void Convert_ValueDivisibleByThree_ShouldReturnFizz()
{
  //Arrange
  int valueToConvert = 3;
  string expectedValue = "Fizz";

  FizzBuzzer fb = new FizzBuzzer();

  //Act
  string result = fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it will return "3".

Write the minimum so the test will pass:

1
2
3
4
5
6
7
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0)
    return "Fizz";

  return valueToConvert.ToString();
}
Green - The test passes as "Fizz" is returned when valueToConvert is divisible by three - The modulus arithmetic operator is used to check for this.

Refactor - There is some refactoring to be done here. There is some duplication now within the previous two tests: FizzBuzzer fb = new FizzBuzzer(); This can be extracted to a test setup method that is run before each test is executed.

Refactored test code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
private FizzBuzzer _fb;

[SetUp]
public void Setup()
{
  _fb = new FizzBuzzer();
}

[Test]
public void Convert_ValueNotDivisibleByThreeOrFive_ShouldReturnValue()
{
  //Arrange
  int valueToConvert = 1;
  string expectedValue = "1";   

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
A private FizzBuzzer (_fb) variable has been declared with class scope. This is instantiated within the Setup method which is called before each test is executed because of it's [Setup] attribute. After refactoring your code, always re-run your unit tests. This practice will help ensure your refactoring has not broken anything.

The //Act and //Assert steps within each test are also duplicated and could be extracted out into a separate method. However, to help practice the "Triple A" pattern I have chosen to leave them in each of the unit tests.

Test 4 - When value is divisible by five return "Buzz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Test]
public void Convert_ValueDivisibleByFive_ShouldReturnBuzz()
{
  //Arrange
  int valueToConvert = 5;
  string expectedValue = "Buzz";

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it returns "5".

Write the minimum so the test will pass:

1
2
3
4
5
6
7
8
9
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0)
    return "Fizz";
  if (valueToConvert % 5 == 0)
    return "Buzz";

  return valueToConvert.ToString();
}
Green - The test passes

Refactor - Nothing to refactor

Test 5 - When a value is divisible by three and fizz return "FizzBuzz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Test]
public void Convert_ValueDivisibleByThreeAndFive_ShouldReturnFizzBuzz()
{
  //Arrange
  int valueToConvert = 15;
  string expectedValue = "FizzBuzz";

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it returns "Fizz".

Write the minimum so the test will pass:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0 && valueToConvert % 5 == 0)
    return "FizzBuzz";
  if (valueToConvert % 3 == 0)
    return "Fizz";
  if (valueToConvert % 5 == 0)
    return "Buzz";

  return valueToConvert.ToString();
}
Green - The test passes.

Refactor - The Convert method has some duplicate modulus calculations which can be refactored and some improvements can be made to make the method more readable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public string Convert(int valueToConvert)
{
  bool isFizz = valueToConvert % 3 == 0;
  bool isBuzz = valueToConvert % 5 == 0;

  if (isFizz && isBuzz)
    return "FizzBuzz";
  if (isFizz)
    return "Fizz";
  if (isBuzz)
    return "Buzz";

  return valueToConvert.ToString();
}
This refactoring extracts the fizz and buzz modulus calculations into their own boolean variables to represent if valueToConvert is divisible by three or five. These boolean variables are used to return the correct conversion. This refactoring has rippled throughout the whole of the convert method - Running the previously written unit tests will prove that no functionality has been broken.

That completes the Fizz Buzz TDD kata.

Continuing further, you could re-factor the FizzBuzzer implementation to only use a single return statement and use the existing unit tests to confirm you have not broken any functionality. This is an important factor to remember when writing a unit test: The test should not know about any of the implementation details of what it is testing. See my blog post about a ##DDD North## session I attended to read more about this.

The projects full source code can be found here.

Fizz Buzz is an excellent problem to help you get into the TDD mindset. It allows you to focus on the red, green, refactor pattern without becoming too bogged down with implementation details. To help keep things interesting, you can also attempt many different implementations of the FizzBuzzer class when you attempt the kata.

Sunday, March 16, 2014

SSRS - Tip: Passing multiple values in a single parameter within a stored procedure

When modifying a drop down selector in a SSRS report to allow a user to select multiple values I noticed all other reports which provided this functionality had the accompanying SQL query embedded within the report. I thought this was strange as the majority of the other SSRS reports I had looked at used stored procedures.

After a little bit of research I found the following:
"The data source cannot be a stored procedure. Reporting Services does not support passing a multi-value parameter array to a stored procedure." Essentially, SSRS passes the multi-value parameter as a comma separated string to a stored procedure. 
Note: If the SQL query is embedded within the report, this format works perfectly fine: "IN ('Item 1', 'Item 2', 'Item 3')"

All is not lost if you do not want to embed your SQL within the SSRS report. If you read this excellent article written by David Leibowitz Puzzling Situations: Using MultiValue Parameters with Stored Procedures in SSRS, it is possible (and quite straight-forward) to write an SQL function that will convert the comma separated string into a table. The table can then be enumerated using the IN keyword within your stored procedure.

Happy days!

Wednesday, March 12, 2014

Creating local domain with IIS

Recently, I gave a presentation that required webpages to be loaded from multiple domains:



Instead of registering multiple domains and publishing a couple of websites, I was able to achieve this locally through these simple three steps.

1) Add a new Web Site

Open Information Internet Services Manager (the easiest way to do this is to search for "IIS" from the Start menu) and expand your localhost entry in the tree on the left hand side exposing the "Sites" node. Right click on this and select "Add Web Site...".


2) Configuring the new Web Site


The most important thing to notice here is that the "Host name" must match the domain that you want to create locally. With the above configuration, I would expect to access this site by navigating to "www.mygoogle.com" in a browser.

3) Configure the HOSTS file

The last step is to force your computer to resolve requests to your domain to your local IIS instance and not resolve them through a DNS. This is achieved by adding a entry to the HOSTS file that points to your local machine. In Windows XP, Windows Vista, Windows 7 and Windows 8, the hosts file can be found here: c:\windows\system32\drivers\etc\HOSTS.


Any requests for "www.mygoogle.com" will now be resolved to the IP address of 127.0.0.1, which is the loopback address for you machine resulting in your local IIS serving the page:


Sunday, March 2, 2014

MSSQL Maintenance Plans - Tip: Have the task name displayed in your logs

When viewing the history of a Maintenance Plan job, the name of each task can be blank making it tricky to know which row relates to which task.


When creating the Maintenance Plan task, unless a "Task Name" is specified (Properties on the specific task), no name will be displayed within the plans history. 


By adding a "Task Name", your plan history will display the task name at the row level. This helps make the plans history more readable at a glance.




Saturday, February 15, 2014

Roman Numeral Converter and the Strategy Pattern

The Roman numeral converter is a converter that will converter a decimal value (Eg. 4) to its Roman numeral equivalent value (Eg. IV).

This implementation of the converter (of which there are many other alternative implementations) uses a divide and conquer approach. The conversion is broken down into smaller "bite size" parts (ones, tens, hundreds, thousands) which lends itself nicely to using the strategy pattern.

What is the Strategy pattern?
The strategy pattern is a way to encapsulate a family of similar algorithms. Each algorithm is a strategy and the pattern allows one or many strategies to be selected at run-time.

The strategy interface
Each strategy is required to implement an interface so it can be consumed by the client consistently. The IConverter interface is used to achieve this and specifies a single method called Convert.

1
2
3
4
public interface IConverter
{
  string Convert(int number);
}

A strategy implementation
The OnesConverter implements the IConverter interface to convert the ones (1 - 9) to their Roman numeral equivalents. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class OnesConverterStrategy : IConverter
{
  public string Convert(int number)
  {
    int onesToConvert = CalculateNumberOfOnesToConvert(number);

    string conversion = string.Empty;

    int i = 1;

    while (i <= onesToConvert)
    {
      if (i == 4)
        conversion = "IV";
      else if (i == 5)
        conversion = "V";
      else if (i == 9)
        conversion = "IX";
      else
        conversion += "I";
      i++;
    }

    return conversion;
  }

  private int CalculateNumberOfOnesToConvert(int number)
  {
    int numberOfOnes = number % 10;

    return numberOfOnes;
  }
}

Each converter follows a similar pattern where the CalculateNumberOfXXXXToConvert method uses a modulus calculation to determine the number of units (number of tens or number of hundreds etc.) to convert to Roman numerals. This is used within a while loop to generate the conversion.

Roman numeral converter
The RomanNumeralConverter class instantiates a List<IConverter> in the order in which they will be called (thousands > ones). It then enumerates through this list building up the Roman numeral conversion as it progresses and returns the completed conversion to the caller.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class RomanNumeralConverter
{
  private List<IConverter> _converters;

  public RomanNumeralConverter()
  {
    _converters = new List<IConverter>
    {
      new ThousandsConverter(),
      new HundredsConverter(),
      new TensConverter(),
      new OnesConverter()
    };
  }

  public string ConvertToRomanNumerals(int number)
  {
    if (number <= 0 || number > 3000)
    return "Invalid value";

    string result = string.Empty;

    _converters.ForEach(x => result += x.Convert(number));

    return result;
  }
}

The benefits of this approach is that each of the strategy implementation can be tested in isolation and allows the RomanNumeralConverter to be extended by introducing additional converters without effecting the existing converters (as long as the converter initialization order is preserved).

The downside to this implementation is that there is a bit of duplication in each of the converters as essentially the algorithm is the same but only the Roman numerals change. A single converter could be potentially used here which could use a multi-dimensional array to switch which Roman numerals to use based on the place value (ones, tens etc.) of the decimal number currently being converted.

The complete project can be found here with accompanying unit tests.

In a subsequent post, I will extend the RomanNumeralConverter to use a factory to generate an enumerable of IConverter strategies based on the decimal value required to be converted. This will allow us to further utilize the strategy patterns ability to load specific strategies at run-time and introduce the factory pattern.