December 7, 2010

Creating a NuGet Package

NuGet is a package manager for .NET that was recently released by Microsoft as a CTP. This library is similar to gems or cpan or similar libraries in other languages. I decided to try my hand at creating a HelloWorld package.

First I needed a package. My original idea was to create something useful enough to contribute to the public feed of NuGet packages. I started by creating the Shelf library, which is a small set of extension methods. Notably, I created the Each<T> method that extends IEnumerable<T>. It takes an Action<T>, invoking the action for every item in the sequence. It's a trivial and small library at the moment, but imagine it is something useful and complicated. The library itself isn’t the point here.

Create the package “manifest” (my term).

<package>
  <metadata>
    <id>shelf</id>
    <version>2010.1203.2330.42313</version>
    <authors>Kwak</authors>
    <description>Shelf is a library of common extension methods</description>
    <language>en-US</language>
  </metadata>
  <files>
    <file src="Shelf\bin\Release\*.dll" target="lib" />
    <file src="Shelf\bin\Release\*.pdb" target="lib" />
  </files>
</package>

The documentation says the files element is optional. It seems I didn’t discover the “convention” they were speaking about in the documentation. I needed it.

I ran the command-line tool nuget.exe passing it the pack command and the package manifest. It spat out the packaged file (BTW, you can use just about any zip tool to browse the contents of the package).

There are couple of different ways to deploy the package. Submitting your package for inclusion in the public feed is one option. You can put the file on any accessible URL. The NuGet source includes a “Server” utility. Until my library grows to a point where it’s not laughably trivial, I opted for just putting it in my file system and pointing the package manager to folder. Phil Haack has a great post explaining the deployment options.

So with my package (shelf.2010.1203.2330.42313.nupkg) located in my local packages folder, anytime I want to make use of the shelf library, I simply go to the package manager console and type

Install-Package shelf
NuGet goes off, makes sure it has the latest package, adds the package folder to my source if it doesn't already exist, downloads (copies) the assembly, and adds the reference to the project.

Here are some of the references, I’ve found useful:


Conclusion: Piece of cake and terribly useful for consumers of your library.

August 9, 2010

Mercurial .hgignore File for .NET Projects

I’m currently using Mercurial, and find myself starting out with this as a base .hgignore file.

glob:bin/*
glob:TestResults/*
glob:obj/*
glob:*.suo
glob:*.user

May 7, 2010

Configuring SpecFlow to Work with MSTest

Add a reference to TechTalk.SpecFlow and then put this in an App.config file of the MSTest project:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
  </configSections>

  <specFlow>
    <unitTestProvider name="MsTest" />
  </specFlow>
</configuration>

May 4, 2010

Visual Studio 2010 Styles

If you haven’t checked out Studio Styles yet, please go do so. An improved version of the old Is Your IDE Hot or Not (the old site seems to have fallen into disrepair). Studio Styles is one of those well-executed, brilliant ideas, that has you saying, “Why didn’t I think of that?”

I spent some time creating a version of my favorite color scheme. It’s called Distant Stormy Shore.

CropperCapture[1] It’s based on the work by Thomas Restrepo on the Distant Shores color scheme.

Please download and give me a “Hot” rating if you like it.

April 30, 2010

Yet Another FizzBuzz

As interesting as I could make it.

private static string FizzBuzz()
    {
      var fizzBuzzMap = 
        Enumerable
          .Range(1, 100)
          .Select(num => MapToFizzBuzz(num));

      return String.Join("\n", fizzBuzzMap.ToArray());
    }

    private static string MapToFizzBuzz(int num)
    {
      if (num % 15 == 0)
        return "FizzBuzz";
      if (num % 5 == 0)
        return "Buzz";
      if (num % 3 == 0)
        return "Fizz";
      return num.ToString();
    }

Before, I lost interest.

March 25, 2010

Dependency Injection and the Controller Factory in ASP.NET MVC

This is a re-post from the older blog. I’m retiring that blog address and this is one of those posts that I refer to when setting up a new project.

Using an IoC is one of those things that can take a time or two to understand where it fits in and how it’s useful. Once you cross the energy barrier, it’s a color in your palette you can’t imagine missing.

Imagine having a QuestionController that takes an interface called DomainRepository. The job of any concrete implementation of the DomainRepository will be to fetch various domain entities from a backing store.

public class QuestionController : Controller
{

  private DomainRepository _repository;

  public QuestionController(
	DomainRepository repository)
  {
    _repository = repository;
  }

  public ActionResult Index()
  {
    ViewData.Model = _repository.AllQuestions;
    return View();
  }

}

This is a perfect place to use an IoC container to provide build a concrete implementation and all of it's dependencies

The gotcha is that ASP.NET MVC, by default, requires its controllers to have default constructors. Luckily, ASP.NET MVC uses a ControllerBuilder to instantiate the controllers using a ControllerFactory. This is an extension point where we can provider our own factory, one that uses the IoC of choice to resolve the controller.

You'll need a class for the new controller factory. This is a minimal implementation that doesn't make use of the MVC 2 requestContext parameter

public class StructureMapControllerFactory : DefaultControllerFactory
{
  protected override IController GetControllerInstance(
	RequestContext requestContext, 
        Type controllerType)
  {
    return 
	ObjectFactory
	.GetInstance(controllerType) as IController;
  }

}

In your bootstrapper, or in the Global.asax.cs, make the ControllerBuilder use the new controller factory

ControllerBuilder.Current
	.SetControllerFactory(
          new StructureMapControllerFactory());

Also, in the bootstrapper, or in the Global.asax, setup your container. This is using StructureMap's 2.6.1 syntax

ObjectFactory.Initialize(factory =>
{
  factory
    .For<DomainRepository>()
    .Use<NoSqlDomainRepository>();
});

These are the minimal steps required to get the ASP.NET MVC web application ready for use with an IoC (e.g., StructureMap).

March 16, 2010

Declarative Style is My Golden Hammer

I was working on a little pet project recently, and I really was tickled when I wrote my unit tests like this:

  public class Given_a_HomeController
  {

    private static HomeController controller;

    [TestClass]
    public class when_asked_for_the_index
    {

      private ActionResult the_result;

      [TestInitialize]
      public void because()
      {
        using_a_new_home_controller();
        after_performing_the_index_action();
      }
      
      public void using_a_new_home_controller()
      {
        controller = new HomeController();
      }

      public void after_performing_the_index_action()
      {
        the_result = controller.Index();
        Assert.IsNotNull(the_result);
      }

      [TestMethod]
      public void it_should_return_a_ViewResult_for_the_Index_view()
      {
        the_result.is_a_ViewResult().for_a_view_named("Index");
      }

    }

If you can read through the test attribute decorators and the public void C# noise, the setup and the tests read like this:

Given a HomeController:
    When asked for the index:
        because:
            using a new HomeController
            after executing the Index action

        it should return a ViewResult for the Index View

It made me smile.

February 6, 2010

Fitnesse Test Styling

In my previous post, I concentrated on setting up Fitnesse. Unfortunately, I did a lot of hand-waving when it came to the test used in the example. I got called out on it, and rightfully so.

Gregor said…

Are you really hard coding the prices and the name of the product into the method names? Do you also have methods named "The_sub_total_shows_3_49" and The_sub_total_shows_8_17"? This means that you cannot change your acceptance test without renaming or adding methods in the fixture. This surely is not the purpose of FitNesse.

The test wasn’t the purpose of the post, and I should probably have Lorem ipsum’d it. Alternatively, I could have explained myself a little better, and improved the test.

My response to the comment is, “Sincerely, thank you for your comments, and yes, yes, true, and sure it is.” The real problem to my point of view is that the product owner, subject-matter expert, customer, stakeholder, or whatever you have probably explained to the programmer (me) something like this:

The customer purchases items. Those items are scanned. The price of the item is put on the bill along with it's description. See figure 1. The subtotal is calculated as the sum of the price of all items on the bill and displayed at the bottom.

I immediately translated this in real time into an implementation. That of a bill, of descriptions showing up on receipts, and prices being displayed and tallied. I broke up the statement into easily re-useable and parameterized chunks. In traditional Fit/Fitnesse tests this probably could have been efficiently captured in a traditional ColumnFixture and look something like:

col-fixture-total-items

The corresponding fixture implementation could then be given as

  public class TotalItemsPurchased : fit.ColumnFixture
  {

    private Bill _bill;

    public TotalItemsPurchased ()
      {
        _bill = new Bill();
      }

    public string Sku
    {
      get
      {
        return _bill.LastItem.Sku;
      }
      set 
      {
        _bill.Scan(value);
      }
    }

    public string Subtotal()
    {
      return _bill.SubTotal.ToString("C");
    }

    public string Description()
    {
      return _bill.LastItem.Description;
    }

    public string Price()
    {
      return _bill.LastItem.Price.ToString("C");
    }
  }

Where Bill is the system under test (or it is for this example anyway). There is nothing wrong with this. It’s a very clean, clear, and concise way to implement these requirements, and to Gregor’s point the implementation code isn’t so weird anymore.

For me though, writing acceptance tests like this becomes too much like programming. I’m moving towards making my acceptance tests read more like end-user documentation. I’d rather the acceptance tests be in the words of the customer. I’m even willing to threaten to publish the acceptance tests as the end-user documentation.

A better example of flow mode using plain-text tables would have been to take the actual words of the customer and make them directly executable.

total-items-end-user

The Fitnesse code for this test looks like:

![ TotalItemsPurchased
The customer purchases items. 
Those items are scanned. 
The price of the item is put on the bill along with it's description. See figure 1. 
The subtotal is calculated as the sum of the price of all items on the bill 
and displayed at the bottom.
]!

 

However, the underlying fixture looks weird again (e.g., The_price_of_the_item_is_put_on_the_bill_along_with_it_s_description_See_figure_1. Honestly I'm ok with that. I can accept the role of the fixture as the bridge between the wiki and the test automation if it means the author of the test can freely communicate the intent of the feature in his/her own words. The automation code itself is free to be separate from the fixture code in this regard.

As far as parameterizing the tests, for the purpose of making the fixture code more re-useable and programmer friendly, that’s ok, if that’s what you’re into, and as my commenter points out Fitnesse gives you more than a few choices (e.g., ScenarioTable, ScriptTable, ActionFixture, DoFixture, et. al.).

In fact, you can parameterize a statement like, “The description of the item is “Bubbly Yummy” and costs “$0.79” in flow-mode and a plain-text table like this:

![" TotalItemsPurchased
  The description of the item is "Bubbly Yummy" and costs "$0.79"
]!

This can be implemented in a fixture like this:

  public class TotalItemsPurchased
  {
    public bool The_description_of_the_item_is_and_costs(string description, string cost)
    {
      // Fire up the API and do some testing
    }
  }

It still looks a little weird, but it avoids hard-coding the values in the function names.

My personal goal with acceptance tests is to get the acceptance tests to feed a TDD cycle. In the standard red-green-refactor cycle is where I’ll worry about the code structure of the test infrastructure and the the application. I want to follow the cycle as depicted in Growing Object-Oriented Software, Guided by Tests:

test-cycle

I don’t want to pressure the writing of the acceptance criteria with implementation concerns. As a result, having fixtures that are mere connectors between the implementation and acceptance criteria is palatable in my book. I’m digging flow-mode style Fitnesse tests because there is a lot of freedom afforded the author of the acceptance test.

January 29, 2010

Setting Up Fitnesse for .net

I promised (myself) that this blog would be more of a notebook; a stream of consciousness  describing my own discoveries. I’m not sure if what I’m going over is old hat for the Fitnesse veteran, or if organizing acceptance tests and unit tests in this way is anything of value to anyone other than myself. Although there are tutorials of setting up Fitnesse for .net already out there, I’m putting down my own personal take on the matter as what I found wasn’t exactly what I was looking for all in one place. It’s what I’m involved with at the moment.

This was all sparked when I attended Maykel Suarez’s presentation on Fitnesse in flow mode. I’ve learned a lot from Mike on testing and software in general since I’ve had the privilege of working with him. I was put off from Fitnesse because of some of the misuse and abuse I’ve seen in the wild. My main beef was that folk were using it as a scripting platform. This became a tangled mess of imperative goo, and the textarea provides a poor IDE in my opinion. After attending Mike’s presentation I realized I could use the wiki to document the intention of the test, and that there was already support from like minded people to make this happen.

Checkout the acceptance test I wrote for a hypothetical POS system. Notice, there’s nothing techie in there. In fact, it even looks like user documentation. A sign, that perhaps this is a good acceptance test.

Test Results for Total Items Purchased

For the Fitnesse guru’s; this particular example could probably have been written more efficiently using a good ol’ fashion ColumnFixture, but I wanted to illustrate the use of plain-text tables and how they can provide a very flexible test structure. You’ll see what the underlying Fitnesse code looks like in a second. I also could have taken the introduction text and put that inside the table to use as the driver for the test.

Getting All the Pieces in Place

  1. Go get the latest build of Fitnesse. Just download the jar file like it says (and if you don’t have Java installed you’ll need that as well).
  2. Go get the latest fitsharp library. This provides the runner and the hooks for Fitnesse to execute .net code.
  3. Create a test project. I use MSTest, but whatever you’re into is cool. I like to name my test project something like GoGoGrocer.Specifications, where GoGoGrocer is the name of the system/application.
  4. Create a folder to hold your acceptance tests. I name mine AcceptanceTests. Go figure.
  5. Dump the fitnesse.jar file you downloaded directly into the AcceptanceTests folder.
  6. Create a little batch file to handle starting up Fitnesse and put these options in it:
    java -jar fitnesse.jar -p 8080 -e 0
    There are a lot of options to start Fitnesse, and a big help was to realize how useful the Quick Reference section was in the User Guide. The options above start the Fitnesse server on port 8080 (-p) and the turn off version history – you know the wiki thing (-e 0).
  7. Create a bin folder under AcceptanceTests and put all the fitsharp files in there. Also change the project’s build settings to output into that folder as well.
  8. Create additional folders under the project for UnitTests and Fixtures. I’ll explain the Fixtures in a second.
  9. Create a file called fitness.config and put that in the bin folder. The contents of the file should be:
    <suiteConfig>
      <ApplicationUnderTest>
        <AddAssembly>
          bin\GoGoGrocer.Specifications.dll
        </AddAssembly>
        <AddNamespace>fitlibrary</AddNamespace>
        <AddNamespace>system</AddNamespace>
        <AddNamespace>
          GoGoGrocer.Specifications.Fixtures
        </AddNamespace>
      </ApplicationUnderTest>
      <fitSharp.Fit.Application.FileExclusions>
        <Add>^\.svn$</Add>
      </fitSharp.Fit.Application.FileExclusions>
    </suiteConfig>
    This adds the test assembly into the runner, and also provides a place to reference the namespaces of your fixtures. This makes it easy for you to reference them in your Fitnesse code. UPDATE: If your tests hang, make sure this file is encoded as UTF-8 (XML...sigh)
  10. One more file to go. Open up the command prompt and run the startFitnesse.bat file. Among other things, this will install your FitnesseRoot and build the initial structure. Edit the content.txt file directly under the newly created FitnesseRoot folder.
    !*> using fitsharp
    !define COMMAND_PATTERN {%m -c bin\fitnesse.config -r fitnesse.fitserver.FitServer,bin\fit.dll %p}
    !define TEST_RUNNER {bin\Runner.exe}
    
    *!
    
    !*> defines
    !define COLLAPSE_SETUP {true}
    !define COLLAPSE_TEARDOWN {true}
    
    *!
    Hint: use the “Show All Files” feature in the Solution Explorer and add all the relevant folders to your project.

Now you’re ready to start using Fitnesse. When you’re all done with setup your project structure should look something like this:

solution-explorer-acctests

Writing a Test in Flow Mode

The following content file defines the “Total Items” test shown above:

!2 Total Items Purchased

The customer purchases items. Those items are scanned. The price of the item is put on the 
bill along with it's description. See figure 1. The subtotal is calculated as the sum of
the price of all items on the bill and displayed at the bottom.

!img-l http://sites.google.com/site/futureturnip/home/images/sub-total-receipt.png

![ TotalItemsPurchased
The cashier scans "Wonder Bread" costing $3.49
The description "Wonder Bread" is displayed on the bill
The bill shows that the "Wonder Bread" costs $3.49
The sub total shows $3.49
The cashier scans "Gallon Milk 2%" costing $3.89
The description "Gallon Milk 2%" is displayed on the bill
The bill shows the cost of "Gallon Milk 2%" is $3.89
The sub total shows $7.38
The cashier scans "Bubbly Yummy" costing $0.79
The description "Bubbly Yummy" is displayed on the bill
The bill shows the cost of "Bubbly Yummy" is $0.79
The sub total shows $8.17
]!

The test is human-readable text, even in it’s wiki markup form. The trick is of course tying it to a Fixture. The fixture is a bridge between the Fitnesse runner and your code. The plain-text table ties itself to the TotalItemsPurchased class on it’s opening declaration. In that class a method is defined for every line in the text; replacing spaces with underscores and generally ignoring special characters like quotes or the percent sign (it did take a little experimentation to find that out). Here’s what fixture code might look like:

namespace GoGoGrocer.Specifications.Fixtures
{
  public class TotalItemsPurchased
  {
    public bool The_cashier_scans_Wonder_Bread_costing_3_49()
    {
      // This method is just the hook.
      // Fire up your API and test the SUT.
    }

    public bool The_description_Wonder_Bread_is_displayed_on_the_bill()
    {
      return true;
    }

The methods return true for a passing test. That’s a little quirky, and there are opportunities to improve the reporting, but that’s the bridge into your test code.

Summary

I still have some little issues with Fitnesse, and I still think the Ruby folk have us beat with Cucumber, but for .net Fitnesse offers a pretty-good solution for acceptance tests.

I also tried to “Export Template…” this, but the resulting template doesn’t install itself into Visual Studio. Haven’t figured that out yet, but I’ll share if I ever do.

January 21, 2010

Functional Patterns for Refactoring in C#

Trying to work on a little filler presentation for my brown-bag sessions at work on a couple of new code smells that can be solved thanks to the small dose of functional programming afforded us by LINQ and C# 3.5 and greater.

I’m working from the refactoring example given in Agile Principles, Patterns, and Practices in C# for the Sieve of Eratosthenes. When this book was published LINQ wasn’t around, and in a 1.x world this is Uncle Bob’s final listing for the problem:

public static int[] GeneratePrimeNumbers(int maxValue)
  {
      if(maxValue < 2)
          return new int[0];
      else
      {
          UncrossIntegersUpTo(maxValue);
          CrossOutMultiples();
          PutUncrossedIntegersIntoResult();
          return result;
      }
  }

This is fine. It reads well. I’ll get into the implementation of some of the methods in a second, but here’s my final implementation of the same method:

public static int[] GeneratePrimeNumbers(int maxValue)
  {
    return 
      Primes
        .TakeWhile(prime => prime <= maxValue)
        .ToArray();
  }

When Generating a Sequence Return IEnumerable<T>

I would like to drop the call to ToArray, but then I would break the interface from the original problem. However, whenever you see a sequence being generated, use IEnumerable<T> unless you need the indexing, and use an iterator if you can get away with it. Take my implementation of Primes for example:

public static IEnumerable<int> Primes
  {
    get
    {
      var remaining = Integers.Where(i => i >= 2);
      while (true)
      {
        int prime = remaining.First();
        yield return prime;
        remaining = remaining.Where(num => num % prime != 0);
      }
    }
  }

There’s no need for any result arrays or other collectors. Just generate the sequence and let the caller tell stop pulling values when they’re ready. This is all about deferred execution and lazy evaluation.

Likewise, my implementation of Integers is:

public static IEnumerable<int> Integers
  {
    get
    {
      int count = 0;
      do
      {
        yield return count++;
      } while (true);
    }
  }

Replace Loops with Filters, and Use Aggregates

Something you ended up doing a lot in 1.x code was writing a function like this (again from Uncle Bob’s original example):

private static int NumberOfUncrossedIntegers()
  {
      int count = 0;
      for (int i = 2; i < crossedOut.Length; i++)
      {
          if (NotCrossed(i))
              count++; // bump count
      }
      return count;
  }
  

Basically, this counts the number of elements in the boolean array crossedOut that are false. In the case of this algorithm, we have to skip the first two. In LINQ this becomes:

private static int NumberOfUncrossedIntegers()
  {
    return crossedOut.Skip(2).Where(x => x == false).Count();
  }
The where statement provides a filter and the count provides the counting. I in-lined the NotCrossed function in the lambda.

Summary

I’m not knocking Uncle Bob’s original implementation. I think it’s groovy. I’m just saying that now that LINQ is around it can let us leverage some pretty powerful syntax to refactor our loops and generators.

January 13, 2010

Oh no! It’s you Again.

So it’s January, and my New Year’s resolution was to suck less than I did the year before. My blogging, and my desire to blog have waned over the last year or couple of years. So, new blog; fresh start; time to rekindle the love of programming and creation of software in general. So in the spirit of my resolution, I’m committing to blogging again.


The old blog had to die. I was paying a nominal fee to keep it alive and entertain the 17 readers I had collected. The content attempted too much at times. I was put off from posting frequently because most of the posts were articles and not log entries. Some of the content was useful (to me at least), but it’s best to make a clean break.


The new blog is a place to store my eclectic bits of techie-software related nuggets. It will be more of a journal. Things I’m working on, as I’m working on them. I’ll try to post the whitepapers somewhere else (but probably not at all).


//TODO: Insert Blog Post Here