Philly.Net TDD Workshop

October 1, 2008 by slholmes · Comment
Filed under: General 
Last night, I attended Brian Donahue’s excellent Getting Started With Test Driven Development workshop in Ft. Washington PA as part of Philly.Net’s workshop series. Brian originally gave a workshop entitled Building Maintainable, Testable WebForms Applications with the Model-View Presenter Pattern. This was back in July. I think the consensus was that for the July workshop, the presentation was rushed and difficult to follow, so Brian went back and reworked the whole concept and produced a stunning result. He was really able to focus on some of the reasoning behind TDD. The pace was much slower than before but still brisk enough not to get bored. Brian had some great advice on getting started and coping with some of the trappings of TDD. While following along writing code, it became obvious that you need a tool like Resharper in order to boost the efficiency of the manual coding effort. Resharper is almost like magic.

Here’s some notes I took during the workshop. These are my thoughts and not Brian’s words - Brian might or might not agree at all:

Brian recommended the class Nothin’ but .NET Developer Boot Camp http://jpboodhoo.com/training.oo Coming to Philly Nov 17th-21st. $3,000.00

TDD summary: Red. Green. Refactor.

CodeCamp server is on Google code and is an MVC project that’s test driven. Study that for some direction.

Specs - Specifying what you expect your objects to do.

Using NUnit attributes:
[TestFixture] - Defines the context. There should be a different context for each problem you’re trying to solve.
[SetUp] - runs once before each test. Sets up the context for the tests.

And so, the class name + the method name should make a nice sentence.

When_running_the_import <-Class.Method-> Should_parse_file_at_specified_path

The granularity of this is determined by the complexity of the [SetUp]. If the SetUp is getting complex, it’s time to break up the context (TestFixture).

Example:
1. logging in with valid credentials. 2. logging in with invalid credentials. These are different contexts.

An aside (When using SVN, the idea is to do an Update first and then do a commit.)

Dependency Injection involves passing something that is needed to a class as a constructor argument.

As the tests are being written, the code you want is materializing almost as a side effect. As you go, you are being forced to define the public view of your classes and interfaces. You use mocks to pass the tests.
Unit tests are intended to test just small units of stuff, typically using Mocks to avoid needing to set up complicated environments.

Integration tests would test the whole stack, i.e. actually importing a file, parseing extracting stuff, etc.

Assert.AreSame() means the two references point to the same thing (object).

When not to use LINQ to Entities

May 15, 2008 by slholmes · Comment
Filed under: General 
Recently I have been working on a LINQ to Entities (LE) proof of concept project at my day job. This project is my first experience with LE so the pace has been painfully slow. Fortunately, LE with C# is proving so concise and elegant that I’ve fallen in love. My first project consists of a rather simple Entity Framework model (EF), a web page that allows the eu to select some parameters that are used to build a LE query and display a GridView with the results - basically a simple view of some metrics - Plan versus Actual.

The goal was to write an LE query that shows the metric for the current month, the planned metric and the variance as a percentage.

 C# |  copy code |? 
var getStats = from stats in opsMetrics.StatisticsSet
    where stats.FiscalPeriod.FiscalPeriodName == 'MAY_08'
    where stats.District.Region.RegionName == 'South Region'
    group stats.District.Region.RegionName
    into groupedStats
    select new
        {
            PC = groupedStats.Key,
            Actual = groupedStats.Sum(p => p.Actual),
            Plan = groupedStats.Sum(p => p.Plan)
        };
This produces the actual and plan metric for my GridView but I ran into some challenges when I wanted to calculate the percentage difference between the two:

Variance = (Actual/Plan) * 100

Linq to Entities has no percentage extension method. I think it would have confused the daylights out of me anyway. So I decided to create a subquery:

 C# |  copy code |? 
var getPerf = from stats in getStats
select new
    {
        stats.PC,
        stats.Actual,
        stats.Plan,
        From_Plan = (stats.Actual/stats.Plan) * 100
    };

Writing a subquery helps me mentally. I have been writing queries for many years. Nesting queries helps me to formulate unit of work models in my brain. SQL engines usually know how to optimize them and perform in an acceptable way. I like to let the relational calculus do all of the work.

However, there’s a problem in the above snippet. What happens when stats.Plan is zero? The SQL Server database engine reports a divide by zero exception. This can occur naturally when there is no plan. Perhaps there is a new district this year and we did not do the budget for it. We still want to view the district because we want a complete listing of the Region. In this case, we wish to calculate a value of zero for the variance. So, we will fix up our calculation of percentage a little:

Now to be honest this is not exactly what I want. I really and to see the From_Plan column show a percent sign “%” on the grid. So what I really want is a formatted string. If we just add the conversion and then concatenate the “%” sign, the From_Plan calculation is getting way more convoluted than it needs to be. So, I’d like to call a function that does all of the havy lifting:

 C# |  copy code |? 
var getPerf = from stats in getStats
select new
{
    stats.PC,
    stats.Actual,
    stats.Plan,
    From_Plan = safePercentString(stats.Actual, stats.Plan)
};

Then we just implement a simple procedure called safePercentSign.

 C# |  copy code |? 
protected string safePercentString(decimal? inTop, decimal? inBot)
{
    decimal result=0;
    if (inBot != 0) result = (decimal)(inTop / inBot)*100;
    return (result==0) ? "-" : result.ToString("0,0.0") + " %";
}
 
protected string safePercentString(int? inTop, int? inBot)
{
    return safePercentString((decimal?) inTop,(decimal?) inBot);
}

The above will build and not produce an error but at run time, (in my case during the GridView.DataBind()), LINQ to Entities complains that safePercentString is an unknown thingermajigger (I forget what the actual exception is). Obviously, LE is unhappy with what we may consider an “external function call”. External in that my intent is that LINQ to Entities would just automagically call my procedure.

As it happens, LINQ to Entities fails to issue the query simply because it is unable to produce any SQL that would actually result in what I intended. Honestly, when you are this deep into LINQ you forget all about there even being any SQL involved because it’s all objects.

Objects! That’s the solution. We don’t want LINQ to Entities to calculate and convert the percentage at all. We want C# to do that. So the solution is simple. We convert the query to a LINQ to Objects query:

 C# |  copy code |? 
var getPerf = from stats in getStats.AsEnumerable()
select new
{
    stats.PC,
    stats.Actual,
    stats.Plan,
    From_Plan = safePercentString(stats.Actual, stats.Plan)
};

The .AsEnumerable() extension method causes LINQ to Entities the enumerate the results into something LINQ to Objects can work with. LINQ to Objects has no problem calling my C# procedure.

Separate the Linq to Entities unit of work of retrieving the records you need to produce the prep to render unit of work using Linq to Objects. I’ve used this practice on a number of other occasions since and it dramatically boosts my productivity.