About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Closing an anonymous method to a known delegate type
Combining two disparate collections
Nothin’ but .NET – Reaching out
Wow, the difference a single line can make!!
Triggering events on UI components (WinForms)
More new conventions for how I organize my tests!!
Slight addition to jpboodhoo.bdd
Test examples with MBUnit and jpboodhoo.bdd
How I’m Currently Writing My BDD Style Tests – Part 2
How I’m Currently Writing My BDD Style Tests – Part 1
Excel Formatting with Visitors, Specifications, and Composites
Slightly Different Way To Write Unit Tests
BDD Extension Methods
Small bit of code cleanup
Updates to improve readability of tests using mocks
Thoughts On Readability
BDD, AAA Style Testing and Rhino Mocks
Slightly Different Way To Assert That Exceptions Are Thrown
Good to see my thoughts "varified" by someone else!!
Got var?
Austin - Nothin But .Net - 6 Spots Left
Calgary .Net User Group Generics Presentation Material
ReSharper 4.0 Nightly Builds
Automatic Properties - In case you didn't know
Presenter First - Who starts the presenter
Explicit Strongly Typed Selective Proxies - Part 2
Nothin But C# v3.5 with the Igloo Coder - Edmonton, AB (March 31st - April 4th)
Explicit Strongly Typed Selective Proxies
Nothin But .Net - Austin, TX (April 7th - 11th)
WPF UI Automation Testing With MbUnit
IMapper
BDD Specification Base Class
Nothin But .Net Store (Google Code) Breaking Change
MappingEnumerable
Setting The Record Straight - My Thoughts On The MVP Variants (for web applications)
code.google.com/p/jpboodhoo!!!
ReSharper Templates
Huge Code Drop Coming!!!!!!!
Code And Slides For Austin .Net User Group
Nothin But * Courses Coming Your Way
Leveraging the EventHandler delegate more effectively
DateTime Formatting with single custom format specifiers
Nothin But .Net - New York , NY ( October 22nd - 26th, 2007 )
Nothin But .Net - London, England (September 10th - 14th)
Refactoring to reveal intent
Amendment to DNRTV Episode Part 3
DNRTv Series - Demystifying Design Patterns (Source code and information)
Raising events (from a mock) using Rhino Mocks
Multithreading Question - One Solution
Edmonton Presentation - Source Code
Victoria Code Camp Source And Slides
Visual C# 2005 Keyboard Shortcut Poster
And the timer sucks because....
What a waste of timer
Source Code For January 10th Presentation
Sharpen You Sword!!
TDD Live
Take Advantage of the ?? operator
Naming variables using the variable type name (useless tip #1)
Refactoring Ahoy!!
Screencast - Applied Test Driven Development For Web Applications (Part 3)
Quick and Dirty Timing
Why Locking On This May Not Be The Best Idea
Applied Test Driven Development For Web Applications Part 1 Video - Reposted
NMock2 Download
Applied Test Driven Development For Web Applications - Feature Request
One Refactoring Missed
Applied Test Driven Development For Web Applications - Part 1 (Video)
Another Good Question
Applied Test Driven Development For Web Applications Update
The Dark Side Of Declaritive Databinding
Coding to interfaces
Handling Dynamic Rules - A Precursor
Validation In The Domain Layer - Take Two
The often forgotten, but extremely powerful IHttpModule and IHttpHandler interfaces
Applied Test Driven Development For Web Applications - Part 1
Enhancing Images With The Decorator Pattern
Automating Your Builds With NAnt - Part 7
Validation In The Domain Layer - Take One
Source Code For Build Better Collections With Generics Article
TDD By Example - Money
Automating Your Builds With NAnt - Part 6
Dealing with drop down lists with the MVP pattern
Questions about source code
Answers To Some Good Questions
Automating Your Builds With NAnt - Part 4
Automating Your Builds With NAnt - Part 3
Recommended Reading
Generic Range
Anonymous Methods As Event Handlers
Webcast Links
Time Is Counting Down To Register For Nothin' But .Net 2.0!!
I'm Published!!
Fun With Linq and C# 3.0

Archive

Blogroll

 Agile Developer Venkat's Blog
 Ayende @ Blog
 B#
 Barry Gervin's Software Architecture Perspectives
 Boy Meets World
 Brad Abrams
 Canadian Developers
 Christopher Steen
 Claritude Software News
 Clemens Vasters: Enterprise Development and Alien Abductions
 Coding Horror
 Coding in an Igloo
 Dare Obasanjo aka Carnage4Life
 Darrell Norton's Blog [MVP]
 David Hayden [MVP C#]
 Don Box's Spoutlet
 Eric Gunnerson's C# Compendium
 EZWeb guy: Jeffrey Palermo [C# MVP]
 Fear and Loathing
 Generalities & Details: Adventures in the High-tech Underbelly
 Greg Young [MVP]
 Greg's Cool [Insert Clever Name] of the Day
 IanG on Tap
 Ingo Rammer's Weblog
 ISerializable - Roy Osherove's Blog
 James Kovacs' Weblog
 Jason Haley
 Jean-Luc David
 Jeremy D. Miller -- The Shade Tree Developer
 JetBrains .NET Tools Blog
 Jimmy Nilsson's weblog
 John Bristowe's Weblog
 John Papa [MVP C#]
 Jon Skeet's Coding Blog
 JonGalloway.ToString()
 Jump the Fence or Walk Around
 Lambda the Ultimate - Programming Languages Weblog
 Larkware News
 Lutz Roeder
 Marquee de Sells: Chris's insight outlet
 Martin Fowler's Bliki
 Mike Nichols - SonOfNun Technology
 MSDN Magazine - .NET Matters
 MSDN Magazine - All Articles
 OdeToCode Blogs
 Onion Blog
 Planet TW
 Raymond Lewallen [MVP]
 Rockford Lhotka
 RodMan's Corner
 Roger Johansson's blog
 Sahil Malik - blah.winsmarts.com
 Sam Gentile's Blog
 Scott Bellware [MVP]
 Scott Hanselman's Computer Zen
 ScottGu's Blog
 secretGeek
 Service Station, by Aaron Skonnard
 Signum sine tinnitu--by Guy Kawasaki
 Stephen Toub
 Steve Eichert's Blog
 Steven Rockarts
 The Blog Ride
 The Coding Hillbilly
 The Daily WTF
 TheServerSide.net: News
 Tim Gifford
 Vance Morrison's Weblog
 you've been HAACKED

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

 Tuesday, July 28, 2009
Tuesday, July 28, 2009 2:00:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

If you are using extension methods as a way to achieve more language oriented programming, there are lots of times you will want to be able to run extension methods against an anonymous method, but you will first have to close it to a well known delegate type before it is allowed. Here is a useful method if you want the starting point to be an anonymous method created on the fly:

    public class CreateDelegate

    {

       public static DelegateType of<DelegateType>(DelegateType body) {

           return body;

       }

    }

Develop With Passion!

Comments [4] | | # 
 Monday, July 27, 2009
Monday, July 27, 2009 1:40:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

During class last week someone had written a piece of code right near the end of the last evening and I committed to showing them a potential refactoring that could be used. Here is the piece of code in question:

 

            var info_list = new List<ResolverConfigurationInfo>(parser());

            var resolver_items = info_list.Select(x => factory(x)).ToList();

 

            var index = 0;

            parser().each(item =>

            {

                resolvers.Add(item.AbstractType, resolver_items[index]);

                index++;

            });

The code is not really complicated. The messiness comes from the fact that an index needs to be maintained so that it can be used to lookup into another equally sized collection that is not the target of the iteration. There are obviously lots of ways to solve this, but I thought "why not just flatten the two collections into a single collection which eliminates the need for the index. Here is the resulting code that was produced:

 

            var info_list = new List<ResolverConfigurationInfo>(parser());

            var resolver_items = info_list.Select(x => factory(x)).ToList();

            info_list.union(resolver_items).each(item => resolvers.Add(item.first_value.AbstractType, item.second_value));

The union method is a new extension method that will take 2 disparate collections of the same size and combine them into a singular collection of Tuple<T,U> types. I created a simple Tuple class as nothing more than as an immutable parameter object. Here is the resulting code for it (very simple):

 

    public class Tuple<FirstType, SecondType>

    {

        public FirstType first_value { get; private set; }

        public SecondType second_value { get; private set; }

 

        public Tuple(FirstType first, SecondType second_type)

        {

            this.first_value = first;

            this.second_value = second_type;

        }

    }

Finally the code that pulls it all together is here in the extension method that does the heavy lifting:

 

        static public IEnumerable<Tuple<FirstType, SecondType>> union<FirstType, SecondType>(this IEnumerable<FirstType> first_set,

                                                                                             IEnumerable<SecondType> second_set)

        {

            Check.not_null(first_set,second_set);

            var first_list = first_set.ToList();

            var second_list = second_set.ToList();

            Check.ensure(first_list.Count == second_list.Count);

 

            for (var index = 0; index < first_list.Count; index++) yield return new Tuple<FirstType, SecondType>(first_list[index], second_list[index]);

        }

This method hides the details of the indexer into a utility method that can be used anywhere where 2 sets of disparate items of the same length need to be combined into a singular set.

Thoughts?

Develop With Passion!!

Comments [14] | | # 
 Tuesday, March 24, 2009
Tuesday, March 24, 2009 7:40:00 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Training )

There are some big, big changes coming this year that will revolve around how Nothin' but .Net promotes the cause of education. Registration for courses started a couple of weeks ago and I am excited about the potential that this year brings for people who are going to be registering.

After a couple of tweets in the twittersphere, and a great recommendation by Scott; I realized that there were a couple of things that I could do this year to promote the cause of education and make the training a little more accessible. This post outlines the high level plans that are going to be implemented as soon as possible.

In no particular order the items are:

NBDN Scholarship Program
There are lots of people out there who are desperately wanting to get involved with some form of high quality training. Unfortunately, there are also a lot of people who just do not have the resources/support to undertake the financial weight of the course. To that end, this year for each class there is going to be a scholarship issued to one person who will have their complete course tuition wavered. This does not include airfare and accommodations, just the ticket price for a seat in the class. One of the things we are deciding right now is how to go about deciding the format for how this process should work. How do we pick from a potential pool of people who may want to attend the course. Based on the contest I ran last year, it may not be that difficult as in spite of all of the freebies that were being given out, there were very few actual "submissions". If you have any suggestions on how I should structure the "submission" process it would be greatly appreciated. Right now I am leaning in the direction of having people submit stories that describe why they should be awarded the scholarship.

NBDN Course Primer
In the cities where I can coordinate this (and get the timing right), there is going to be a free 1 day primer course that will be open to the public so that they can come and discuss, code, and get a feel for what the scope of the course will entail. My plan for the primer course is to spend the day working through concepts that I feel are prerequisite knowledge, make developers more productive in general, as well as to dive into some code, patterns, and concepts that people should be familiar with (especially if they want to take the course at a later time). Like the course, there will be limited seating (16-20 max), and people will be expected to come with open minds ready to challenge, learn, and have fun. One bonus (in the cities where there is participation) will be the opportunity to work and share discussions with past students (from the local area) who can speak openly and honestly about their experience with the course. In the primer course day people will get exposure to the following :

  • Build automation with rake/powershell
  • Context/Specification style testing
  • Back to advanced basics with core .Net
  • Fundamental Design Principles

Although it is termed as a primer, the goal of the day is to have people leave with their head stuffed full of new ideas and approaches they may not already be familiar with. The reason for the size of the class is to enable as much rich communication as possible, which is very difficult to do in large class sizes. I expect these primers to generate a lot of questions!!

DNRTv
After a great discussion with Carl, we have decided to set some time aside in May to record 2 full days worth of training material. Again, the goal with these videos is to serve as primers for people to get exposed to many concepts that can be instrumental in making them more productive developers. These videos will be extremely code intensive, and should leave people with a greater awareness of tools and techniques they may not already be familiar with. The scope and material that will be covered in these two days is yet to be determined, though my hope is that these videos will give people a great deep introduction to a host of topics.

As you can see, there are lots of plans that are in store this year and I am excited about what the Lord has in store for myself and all of the people I hope to interact with!!

Develop With Passion!!

Comments [7] | | # 
 Monday, March 16, 2009
Monday, March 16, 2009 7:05:00 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I have not changed my build script for my current project for a little while. As the project started to get bigger I started to notice a significant slowdown in building from my build script. I stopped to take a look at my script this morning and smacked my head when I saw what was going on. It read like the following:

$result = MSBuild.exe "$base_dir\solution.sln" /t:Rebuild /p:Configuration=Debug

A quick change to the following and it was all good:

$result = MSBuild.exe "$base_dir\solution.sln" /t:Clean /t:Build /p:Configuration=Debug

Micro optimization is where its at!!

Develop With Passion!!

Comments [4] | | # 
 Tuesday, March 03, 2009
Tuesday, March 03, 2009 3:37:00 PM (Mountain Standard Time, UTC-07:00) ( .Net 3.0 | C Sharp | Programming )

I am currently working on a large winforms application (most likely the last winforms app before I make the transition to WPF). I am writing the application in a top down fashion, which means I drive out the tests for the presenters, and then move down through the corresponding layers to get a good vertical slice of functionality. When it comes to the development of the user interface I am using a command based UI to allow me to easily drive the testing of the screens easily from a unit test. One thing that I often need to do, is cause a UI component to trigger one of its own events to see if the command in question will be triggered. In order to allow for a bit of “guidance” I wrote a class that allows me to quickly trigger events on UI components. The following code snippet shows a usage:

EventTrigger.trigger_event<Events.ControlEvents>(x => x.OnKeyPress(new KeyPressEventArgs('A')), target);

I am making use of an expression tree to determine which event I want the target control to raise. This is easily done because most (almost all) UI components in both the .Net framework and 3rd party Winforms libraries follow a convention of having a method named “OnEventName” which is usually a protected method that the control itself can call when it wants to raise its event. The EventTrigger class lives in my test utilities and for my current application I have a set of Events classes which correspond to some of the third party, and raw .net, control I want to raise events on, here is a trimmed down section of one of the events class:

public class Events

{

    public interface ControlEvents : IEventTarget

    {

        void OnEnter(EventArgs args);

        void OnKeyPress(KeyPressEventArgs args);

    }

 

    public interface FormEvents : ControlEvents

    {

        void OnActivated(EventArgs e);

        void OnDeactivate(EventArgs e);

    }

}

Again, this class lives in my test utility folder and it contains interfaces specific to control types that I want to raise events on. For each control interface, I will place the events (as needed) that I need to be able to trigger from my unit tests. There are multiple ways to get the correct method signature on these interface methods, I can use the Object Browser, Reflector, or ReSharper can generate them!! The point is, the interface contains a public method that is the identical signature for a corresponding protected method on the target control. This is really to help get intellisense about the event I want to raise along with the arguments to the method itself. This works with all component frameworks as their EventArgs classes are always made public as to be able to be consumed by the components that will be hosting them.

Let’s get to the interesting part of this. I mentioned earlier that I am an expression tree to ultimately raise the event. Let's take a look at the trigger_event method signature to get a little understanding of what it is doing:

static public void trigger_event<Target>(Expression<Action<Target>> expression_representing_event_to_raise, object target) where Target : IEventTarget

Notice I am making use of the IEventTarget interface to basically simply constrain the incoming expression to be one based on one of the interfaces that lives in the “Events” class. The first argument “Expression<Action<Target>> is an expression representing the code. The target argument is the actual control to raise the event on. Here is the entire body of the trigger_event method:

static public void trigger_event<Target>(Expression<Action<Target>> expression_representing_event_to_raise, object target) where Target : IEventTarget

{

    var method_call_expression = expression_representing_event_to_raise.Body.downcast_to<MethodCallExpression>();

    var method_args = get_parameters_from(method_call_expression.Arguments);

    var method_name = method_call_expression.Method.Name;

    var method = target.GetType().GetMethod(method_name, binding_flags);

 

    Debug.Assert(target != null,"The target to raise the event on cannot be null");

    Debug.Assert(method != null,"There is no method called {0}, on a {1}".format_using(method_name,target.GetType().proper_name()));

 

    method.Invoke(target, method_args.ToArray());

}

This is test utility code, so I am able to make a lot of assumptions about how I am going to be consuming and using it. For starters I know that the ExpressionTree coming is is going to represent a MethodCallExpression. This post is only a small intro into the amazing concept of expression trees, if they are not something you are comfortable with, there is no time like the present to start playing around with them.

With a MethodCallExpression I have access to the MethodInfo object that contains information about the target method to call (this allows me to reflectively match upto the protected method on the target I want to raise the event on:

var method_name = method_call_expression.Method.Name;

var method = target.GetType().GetMethod(method_name, binding_flags);

Once I have the actual method to invoke, it still needs to be invoked with the correct arguments:

method.Invoke(target, method_args.ToArray());

The act of getting the arguments is the interesting part to this code (and a little gentle introduction to the world of ExpressionTrees for those of you who are not using them yet). The following line:

var method_args = get_parameters_from(method_call_expression.Arguments);

method_call_expression.Arguments is actually a collection of Expressions also. If you look back at the line of code that is using this the original trigger method, we’ll decompose it so that you can get a better idea of the expression tree created to represent the call to the event:

EventTrigger.trigger_event<Events.ControlEvents>(x => x.OnKeyPress(new KeyPressEventArgs('A')), target);

  • MethodCallExpression [x.OnKeyPress(
    • NewExpression[new KeyPressEventArgs(
      • ConstantExpression(‘A’)
    • )
  • )

Expression tree are “tree based structures. This simple line of code actually constructs an ExpressionTree that consists of a:

  • MethodCallExpression
    • NewExpression
      • ConstantExpression

Here is the complete code for the get_parameters_from method:

static IEnumerable<object> get_parameters_from(IEnumerable<Expression> parameter_expressions)

{

    foreach (var expression in parameter_expressions)

    {

        if (can_handle(expression)) yield return get_value_from_evaluating(expression);

        else cannot_handle(expression);

    }

}

This method iterates over each Expression in the incoming set and attempts to expand it to an actual object value. The can_handle method simply makes use of an existing dictionary that has been populated at startup with handlers that know how to evaluate the appropriate Expression:

static EventTrigger()

{

    expression_handlers = new Dictionary<ExpressionType, Func<Expression, object>>();

    expression_handlers[ExpressionType.New] = instantiate_value;

    expression_handlers[ExpressionType.MemberAccess] = get_value_from_member_access;

    expression_handlers[ExpressionType.Constant] = get_constant_value;

}

 

The get_value_from_evaluating(expression) method is very simple, it just look into the dictionary using the NodeType of the current expression, and invokes the expression handler against the expression so that it can be evaluated:

static object get_value_from_evaluating(Expression expression)

{

    return expression_handlers[expression.NodeType](expression);

}

Lets start by looking at the simplest one of them all, the method that evaluates a ConstantExpression:

static public object get_constant_value(Expression expression)

{

    return expression.downcast_to<ConstantExpression>().Value;

}

This method explicitly casts the incoming Expression to a ConstantExpression and then returns the expressions value. In our current example, that value will be the char ‘A’.

We’ll finish up by looking at the most involved one:

static object instantiate_value(Expression expression)

{

    var new_expression = expression.downcast_to<NewExpression>();

    var args = new_expression.Arguments.Select(constructor_argument_expression => get_value_from_evaluating(constructor_argument_expression));

    return new_expression.Constructor.Invoke(args.ToArray());

}

 

In the second line we are actually evaluating each of the constructor arguments expressions one at a time and having them also evaluated by the get_value_from_evaluating method. Because of the nested nature of expression trees, depending on the type of Expression that was passed in, this handles recursive traversal of the expression.

Once all of the arguments to the constructor have been evaluated, we can then invoke the expressions Constructor (which is a ConstructorInfo) to create the item. In our example here, it will cause the creation of a new KeyPressEventsArgs with the character of ‘A’ (the character was evaluated using the ConstantExpression we discussed earlier).

When it comes to testing a new control I can just create a new nested interface in my Events class, add public versions of the protected methods that I want to invoke (along with the correct arguments) and then I’m off to the races!!

Develop With Passion

Comments [1] | | # 
 Monday, February 16, 2009
Monday, February 16, 2009 8:00:00 AM (Mountain Standard Time, UTC-07:00) ( BDD | C Sharp )

As the current project I am on is getting fairly large now, I just recently switched around the way I organize my tests. Here is a sample concern pulled from a main class in my application (smart client based):

public class ApplicationControllerSpecs

{

    public abstract class concern : observations_for_a_sut_with_a_contract<IApplicationController, ApplicationController>

    {

        protected IApplicationShellView shell_presenter;

    }

 

    [Concern(typeof (ApplicationController))]

    public class when_starting_up : concern

    {

        context c = () =>

        {

            application_shell = the_dependency<IApplicationShellPresenter>();

            start_all_modules = the_dependency<IStartAllModules>();

            event_aggregator = the_dependency<IEventAggregator>();

        };

 

        because b = () =>

            sut.start();

 

        it should_start_the_application_shell = () =>

              application_shell.received(x => x.start());

 

        it should_start_all_of_the_application_modules = () =>

             start_all_modules.received(x => x.run());

 

        it should_register_itself_as_a_listener_with_the_event_aggregator = () =>

            event_aggregator.received(x => x.register_listener(sut));

 

        static IApplicationShellPresenter application_shell;

        static IStartAllModules start_all_modules;

        static IEventAggregator event_aggregator;

    }

 

}

Notice how at the top I am now creating a container class which is named {SUT}specs:

public class ApplicationControllerSpecs

All of the concerns for the ApplicationController will be housed inside this class. From an organizational perspective I can now have a superclass for all of my concerns for a particular SUT named concern:

public abstract class concern : observations_for_a_sut_with_a_contract<IApplicationController, ApplicationController>

{

    protected IApplicationShellView shell_presenter;

}

Before, I would place my concerns directly at the root of the file (not nested inside a container class), this meant that when I went to derive a concern from a base concern, I would have to filter through a big ReSharper list of all of the base test classes in the solution that started with the word concern. Because I was following a convention of “concern_for_[sut]”, I would see more than I wanted. Now when I am inside of a container class and am writing a concern that I want to derive from its parent concern,typing con followed by CTRL-SPACE will only give me a very small set of options. I also don’t need to come up with a fancy name for the initial concern superclass. I can just call it concern. Each *Specs file in my current application follows this convention, and each one has an initial superclass named concern. You don’t need the superclass, I just find it a convenient place to put fields etc that can often crowd up the test, common results etc.

Develop With Passion!!

Comments [9] | | # 
 Wednesday, February 04, 2009
Wednesday, February 04, 2009 4:00:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

If you recall from the last post on this topic one of the ways you can record an observation is by simply doing this:

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                connection.was_told_to(x => x.Dispose());

            }

In addition to be able to define observations using traditional attributes. You can now also define observations by using blocks (like the rest of the code uses). So the following observation is identical to the one above:

            it should_dispose_the_appropriate_items = () =>

                connection.was_told_to(x => x.Dispose());

Because all of this is backed by MBUnit. You can start integrating this into your existing MbUnit test suites with no change required. MBUnit GUI, and Console pick them up with no problem. TestDriven.Net can even run them. You can mix and match traditional attribute based observations and block style observations in the same test:

it should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db = () =>

    result.should_not_be_null();

 

[Observation]

public void should_dispose_the_appropriate_items()

{

    connection.was_told_to(x => x.Dispose());

}

The only issue with TD.Net right now, is that you can’t pick a single “it” block to run in a fixture. If you put the cursor on an “it” block and tell TD.Net to run test, it will run all of the “it” blocks in that fixture. If you are using a traditional attribute based Observation block this is not a problem.

If people are interested in how I rolled out this feature, please respond with comments and I will get another post out!!

Develop With Passion!!

Comments [12] | | # 
 Tuesday, January 27, 2009
Tuesday, January 27, 2009 6:08:00 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

The other day I placed a library up on assembla that I use as a place to store my current set of conventions on writing unit tests. My current flavour of testing focuses on the use of BDD to emphasize context and behaviour of a particular SUT (System under test) that I am exercising.

This post is not about detailing my current thinking on BDD, more to demonstrate some ways that you can use the very small framework in conjunction with MBUnit to remove a lot of cruft from your tests. To that end, the following are some sample tests written to demonstrate different aspects of the library:

1) Adding two numbers (without a because block):

 

    public class when_adding_2_numbers_together : observations_for_a_static_sut

    {

        [Observation]

        public void should_result_in_the_sum_of_the_2_numbers()

        {

            (2 + 2).should_be_equal_to(4);

        }

    }

Notice that the class simply inherits from a class named  observations_for_a_static_sut. This is the base class you will use when you are either testing a static class, or (as in this case) you are simply writing a quick inline test.

2) Adding two numbers with a because block (the because block is meant to focus your eyes to the actual behaviour you are exercising:

    public class when_adding_2_numbers_together : observations_for_a_static_sut

    {

        static int result;

 

        because b = () =>

        {

            result = 2 + 2;

        };

 

        [Observation]

        public void should_result_in_the_sum_of_the_2_numbers()

        {

            result.should_be_equal_to(4);

        }

    }

The behaviour being exercises is placed inside of a anonymous method block assigned to a delegate type (because). It is also important to note that the field is static.

Let’s look at a slightly more involved test that has some dependencies, a factory method for the system under test, etc.  Here is the start:

 

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

            static IQuery query;

            static IDatabaseConnectionFactory connection_factory;

            static IDatabaseConnection connection;

            static IDbCommand command;

            static IDataReader reader;

 

            context c = () =>

            {

                connection_factory = an<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                connection.was_told_to(x => x.Dispose());

            }

 

            public override DatabaseGateway create_sut()

            {

                return new DatabaseGateway(connection_factory);

            }

        }

Let’s start by taking a look at the context block:

            context c = () =>

            {

                connection_factory = an<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

In this block I define all of the dependencies that are going to come into play during the test. The “an” method, is a generic method that lives on the base class, which basically creates a mock of the contract in question. It carries on to setup return values for method calls that will be leveraged during the course of the SUT doing its work. Unfortunately, it is hard to identify which mocks are direct dependencies of the sut and which are collaborators. It is only when you look at the factory method for the system under test:

            public override DatabaseGateway create_sut()

            {

                return new DatabaseGateway(connection_factory);

            }

Here it is evident that the direct dependency of the DatabaseGateway is the connection_factory (IDatabaseConnectionFactory). The because block highlights the behaviour being tested:

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

The force_traversal method is a utility method that forces the traversal of an enumerable. It is necessary as the implementation of the method under test uses deferred execution by nature of leveraging the yield keyword and returning an IEnumerable. Here is the implementation of the class under test:

        public class DatabaseGateway

        {

            IDatabaseConnectionFactory connection_factory;

 

            public DatabaseGateway(IDatabaseConnectionFactory connection_factory)

            {

                this.connection_factory = connection_factory;

            }

 

            public IEnumerable<DataRow> get_rows_matching(IQuery query)

            {

                var table = new DataTable();

                using (var connection = connection_factory.create())

                using (var command = connection.create_to_run(query))

                using (var reader = command.ExecuteReader())

                {

                    table.Load(reader);

                }

                foreach (DataRow row in table.Rows) yield return row;

            }

        }

Let’s now show the exact same test written with the minimum amount of plumbing code that is necessary:

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

 

            context c = () =>

            {

                the_dependency<IDatabaseConnectionFactory>().Stub(x => x.create()).Return(the_dependency<IDatabaseConnection>());

                the_dependency<IDatabaseConnection>().Stub(x => x.create_to_run(the_dependency<IQuery>())).Return(the_dependency<IDbCommand>());

                the_dependency<IDbCommand>().Stub(x => x.ExecuteReader()).Return(the_dependency<IDataReader>());

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(the_dependency<IQuery>());

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                the_dependency<IDatabaseConnection>().was_told_to(x => x.Dispose());

            }

        }

The factory method has been removed along with the fields to reference the dependencies that come into play. For readability, I think this approach loses out, so this last way is the way I would finish up with:

        [Concern(typeof (DatabaseGateway))]

        public class when_retrieving_a_set_of_rows_based_on_a_query : observations_for_a_sut_without_a_contract<DatabaseGateway>

        {

            static IEnumerable<DataRow> result;

            static IQuery query;

            static IDatabaseConnectionFactory connection_factory;

            static IDatabaseConnection connection;

            static IDbCommand command;

            static IDataReader reader;

 

            context c = () =>

            {

                connection_factory = the_dependency<IDatabaseConnectionFactory>();

                query = an<IQuery>();

                connection = an<IDatabaseConnection>();

                command = an<IDbCommand>();

                reader = an<IDataReader>();

 

                connection_factory.Stub(x => x.create()).Return(connection);

                connection.Stub(x => x.create_to_run(query)).Return(command);

                command.Stub(x => x.ExecuteReader()).Return(reader);

            };

 

            because b = () =>

            {

                result = sut.get_rows_matching(query);

                result.force_traversal();

            };

 

            [Observation]

            public void should_leverage_db_infrastructure_to_return_a_set_of_rows_from_the_db()

            {

                result.should_not_be_null();

            }

 

            [Observation]

            public void should_dispose_the_appropriate_items()

            {

                connection.was_told_to(x => x.Dispose());

            }

        }

This tests reintroduces the fields to store the mocks. It still removes the factory method, and it uses the following two different methods:

  • the_dependency<T>
  • an<T>

to differentiate between a constructor depedency and a mock that happens to come into play while collaborating with that dependency.

There are lots of other things you can do, and I will post more examples as requests come in!!

 

Develop With Passion!!

Comments [7] | | # 
 Monday, December 22, 2008
Monday, December 22, 2008 2:29:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

We left off in part 1 with an example of a test written using my current style and I finished off outlining the skeleton for one of the base classes that shields the actual Concern classes from a lot of noisy test related nomenclature.

In this post I am going to break down the responsibilities of the “an_observations_basic_set_of_behaviours” class. For a quick reminder, here is the skeleton outline of the class:

        [Observations]

        public abstract class an_observations_set_of_basic_behaviours

        {

            static protected IDictionary<Type, object> dependencies;

            static Exception exception_thrown_while_the_sut_performed_its_work;

            static protected Action behaviour_of_the_sut;

 

            [SetUp]

            public void setup() {}

 

            void prepare_to_make_an_observation() {}

 

            [TearDown]

            public void tear_down() {}

 

            after_all_observations a = () => dependencies.Clear();

 

            ICommand build_command_chain<DelegateType>() {}

 

            void run_action<DelegateType>() {}

 

            protected virtual void initialize_the_sut() {}

 

            static public void doing(Action action) {}

 

            static protected Exception exception_thrown_by_the_sut

            {

                get { }

            }

 

            static Exception get_exception_throw_by(Action action) {}

 

            static protected object an(Type type) {}

 

            static protected InterfaceType an<InterfaceType>() where InterfaceType : class {}

        }

    }

Let’s start off by discussing the fields:

static protected IDictionary<Type, object> dependencies;

 

  • This field is hopefully pretty self explanatory. It is a dictionary that will contain any direct dependencies of the SUT. In most of my apps I tend to favour Constructor based DI so, this dictionary basically contains the set of objects (mocks and/or reals) that the sut will depend on. How this gets populated will be discussed later.

static Exception exception_thrown_while_the_sut_performed_its_work;

  • This field will be used to store a reference to the exception that the sut threw while it performed its work. Is used in conjunction with the doing() method (more on that later).

static protected Action behaviour_of_the_sut;

  • I am going to revisit this field when we discuss the doing() method

That takes care of the first set of fields, lets move on to a method that should look very familiar to MbUnit/NUnit people:

        [SetUp]

        public void setup()

        {

            exception_thrown_while_the_sut_performed_its_work = null;

            dependencies = new Dictionary<Type, object>();

            prepare_to_make_an_observation();

        }

This is a traditional MbUnit setup method. Because it is decorated with the SetUp attribute, all of the code in this method will get run once before each observation (test). Essentially this method is used to reset stateful fields, this is not that interesting. The guts of setup happen in the following method:

        void prepare_to_make_an_observationjjj()

        {

            run_action<context>();

            initialize_the_sut();

            run_action<after_the_sut_has_been_initialized>();

            run_action<because>();

        }

In this base class the initialize_the_sut method has an empty implementation. The prepare_to_make_an_observation method leverages a hook method (initialize_the_sut) that can be leveraged (it will be by an_observation_for_an_instance_sut). In the base class, it is a virtual method with no implementation. As you can see, this method is responsibility for performing the following actions before an observation can be made:

  • Establishing the context (run_action<context>())
  • Initializing the SUT
  • Invoking the behaviour under test (run_action<because>())

Again this is a small little method that basically serves as a driver for prepping the way to be able to make observations. By the time we actually enter an observation in our actual fixtures, the SUT has already performed its work!!

Now I am sure you are wondering what the deal is with the run_action method? Here is the signature for the run_action method:

void run_action<DelegateType>()

This method is a generic method that accepts a delegate type as its generic argument. Again this is a convention that is understood by the naming of the generic parameter. You can’t place constraints on a generic method that constrain the Generic argument to be assignable from a delegate (of course, you can do this with a guard clause). Here are the different delegate signatures that I defined for use in the test-harnesses:

public delegate void context();

public delegate void after_the_sut_has_been_initialized();

public delegate void because();

public delegate void after_each_observation();

You may be wondering why I did not just use the plain old action delegate as opposed to creating discrete delegate types. This is so the driver class (this one we are examining) has a clearer way of differentiation between the different delegates. Without the named delegate types, I would have to resort to following a convention for the name I assigned to a field for an Action delegate (messy, messy).

Here is the full implementation of the run_action method:

        void run_action<DelegateType>()

        {

            build_command_chain<DelegateType>().run();

        }

 

Once again, this method is pretty simple as it is really delegating its responsibility to whatever gets created by the build_command_chain method. So lets dive into the full body of this method, as this is really where the majority of the work is being done:

        ICommand build_command_chain<DelegateType>()

        {

            var actions = new Stack<ICommand>();

            var current_class = GetType();

 

            while (current_class.is_a_concern_type())

            {

                actions.Push(new DelegateFieldInvocation(typeof (DelegateType), this, current_class));

                current_class = current_class.BaseType;

            }

 

            return actions.as_command_chain();

        }

So what is going on here. Take a look at this test one more time as it will give you a good visual as to what is going on:

    [Concern(typeof (MappingStep<,,>))]

    public class when_an_expression_mapping_step_is_told_to_run :

        concern_for_mapping_step

 

    {

        static SomeSourceObject item;

        static SomeDestinationObject destination;

        static string name;

 

        context c = () =>

        {

            item = new SomeSourceObject();

            name = "JP";

            destination = new SomeDestinationObject();

 

            source_evaluator.Stub(x => x.evaluate_against(item)).Return(name);

        };

 

        because b = () => sut.map(item, destination);

 

        [Observation]

        public void should_run_the_target_evaluator_passing_it_the_information_retrieved_from_evaluating_the_source()

        {

            target_action.was_told_to(x => x.act_against(destination, name));

        }

    }

I chose not to also put in this Concerns base class, the only important thing to remember about the “concern_for_mapping_step” is that it also has its own context block :

         context c = () =>

        {

            target_action = the_dependency<ITargetAction<SomeDestinationObject, string>>();

            source_evaluator = the_dependency<ISourceEvaluator<SomeSourceObject, string>>();

        };

 

It is important to remember that the “an_observations_basic_set_of_behaviours” class is the test driver. Here is the inheritance hierarchy for this current test fixture:

  • an_observations_basic_set_of_behaviours
    • observations_for_an_instance_sut
      • obsevations_for_a_sut_with_a_contract
        • concern_for_mapping_step
          • when_an_expression_mapping_step_is_told_to_run

At any point in the chain (starting from the top, working down) each level could have its own context to run. The run_action method is responsible for walking the inheritance hierarchy of a particular concern and building a chain of “commands” for a particular delegate type. Once the command chain has been build, the chain can be executed in the right order (from top to bottom) to ensure that any prior context in a base class has been established before a subclass runs. If you are already thinking, could he not have done the same thing with abstract/virtual methods. Yes. When I initially started down that route, I kept getting stung by forgetting to call back into the base method. By now having to worry about calling the base method prior to doing your own work, you as a developer can just focus on the context that is applicable to a particular test. You can do this, as the driver class is responsible for ensuring blocks run in the order they are supposed to run. Without the driver class, all the fields that have lambdas assigned to them would be useless as they are just sitting there waiting to be invoked.

At the end of the while loop in the build_command_chain method there will be a stack (I chose stack as it is a LIFO structure, which is perfect for walking a class hierarchy, as when the last item is added – the base class, I can just start popping items off and they will be in the right order, ending with the ultimate test class itself). The stack itself is being used to store a set of ICommand implementations. Here is the ICommand interface:

    public interface ICommand

    {

        void run();

    }

This is a pretty stock interface that I have used for years. The uses are endless!! How does the loop know when to end? What is with the following method?:

current_class.is_a_concern_type()

The field current_class is of type Type. The is_a_concern_type method is a local extension method that has the following implementation:

    static public bool is_a_concern_type(this Type type)

    {

        return typeof (an_observations_set_of_basic_behaviours)

            .IsAssignableFrom(type);

    }

This method just adds a bit of readability (from the point of usage, which is a huge bonus of extension methods) and ensures that we wont worry about putting anything that is not either a derivative of an_observations_set_of_basic_behaviours or the an_observations_set_of_basic_behaviours type itself on the stack (it will always be the top item on the stack at the end of the traversal).

So lets explore the line that does the grunt work:

actions.Push(new DelegateFieldInvocation(typeof (DelegateType), this, current_class));

Keep in mind that the actions field is a stack of ICommand. It stands to reason that the DelegateFieldInvocation class is an ICommand implementation. Which it is. The DelegateFieldInvocation class takes in its constuctor a delegate type to scour for, an instance to act against (always this), and finally the particular type to reflect against (this will change as we continue to walk up the inheritance hierarchy). Here is the implementation of the DelegateFieldInvocation:

    public class DelegateFieldInvocation : ICommand

    {

        const BindingFlags probing_flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;

        Type delegate_type;

        readonly object instance;

        IEnumerable<FieldInfo> fields;

 

        public DelegateFieldInvocation(Type delegate_type, object instance, Type current_type)

        {

            fields = current_type.GetFields(probing_flags);

            this.delegate_type = delegate_type;

            this.instance = instance;

        }

 

        public void run()

        {

            all_fields_of_the_target_delegate_type().each(x => x.GetValue(instance).downcast_to<Delegate>().DynamicInvoke());

        }

 

        IEnumerable<FieldInfo> all_fields_of_the_target_delegate_type()

        {

            return fields.Where(x => x.FieldType.Equals(delegate_type));

        }

    }

All this command does in its run implementation is scour all of the fields in the “current_type” and filters them to look for only fields of the certain delegate type being searched for. Once the particular delegate type is found, we get the value of the field using the instance:

x.GetValue(instance).downcast_to<Delegate>()

downcast_to is just a utility extension method to do casting. At this point we have an actual reference to the delegate. With that, because we know (again by convention) that all of the delegate types we are working with are void with no arguments, they can just be invoked by using the DynamicInvoke method that lives on the delegate class. Again, the beauty of the command pattern allows this command to be queued up with all the information that it needs, and then it can simply perform it when it is told to run.

Of course, the build_command_chain ends with this line:

return actions.as_command_chain();

All that this method does is return a Composite of commands that when told to run, will run each of the commands that it is composed with (we’ll dive into that at a later date). So back up in the run_action method:

build_command_chain<DelegateType>().run();

It should now be clear to see that the run() method is invoked on the Composite, that will cause all of the commands to run in sequence. In the case of run_action<context> it will cause a Composite command to be built that is composed of commands to run “context” delegates from the Grandparent down to the actual Concern itself.

For clarification, look again at how the run_action method is used:

        void prepare_to_make_an_observation()

        {

            run_action<context>();

            initialize_the_sut();

            run_action<after_the_sut_has_been_initialized>();

            run_action<because>();

        }

The other calls to run action simply walk down the hierarchy invoking the appropriate delegate fields that may or may not be present in the actual test classes. The because block is the behaviour we are invoking of our system under test. In the case of the test we first examined:

because b = () => sut.map(item, destination);

For the design pattern aware, you will have already realized that the prepare_to_make_an_observation method (along with the use of delegate fields that can be defined at any level of the hierarchy) is just a specialization of the template method pattern, the main difference being that subclasses do not provide their behaviour by overriding abstract methods, rather they just simply have to define fields of a certain delegate type, that contain the code that will be invoked dynamically by the base class using reflection!!

That is enough for now, we’ll carry on the drilldown in the next part!!

Develop With Passion!!

Comments [4] | | # 
 Thursday, December 18, 2008
Thursday, December 18, 2008 3:08:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

In the ongoing goal of “Competing against yourself daily” I have changed many things about my coding style over this past year. One of the areas that has been most affected by all of this is how I organize and write tests for the systems I am building.

Here is an example of a test that I wrote for something called a MappingStep:

public abstract class concern_for_mapping_step : observations_for_a_sut_with_a_contract<IMappingStep<SomeSourceObject, SomeDestinationObject>, MappingStep<SomeSourceObject, SomeDestinationObject, string>> { static protected ITargetAction<SomeDestinationObject, string> target_action; static protected ISourceEvaluator<SomeSourceObject, string> source_evaluator; context c = () => { target_action = the_dependency<ITargetAction<SomeDestinationObject, string>>(); source_evaluator = the_dependency<ISourceEvaluator<SomeSourceObject, string>>(); }; } [Concern(typeof (MappingStep<,,>))] public class when_an_expression_mapping_step_is_told_to_run : concern_for_mapping_step { static SomeSourceObject item; static SomeDestinationObject destination; static string name; context c = () => { item = new SomeSourceObject(); name = "JP"; destination = new SomeDestinationObject(); source_evaluator.Stub(x => x.evaluate_against(item)).Return(name); }; because b = () => sut.map(item, destination); [Observation] public void should_run_the_target_evaluator_passing_it_the_information_retrieved_from_evaluating_the_source() { target_action.was_told_to(x => x.act_against(destination, name)); } }

First thing to notice is a convention I have started using when it comes to writing tests. I create a base class named concern_for_[name_of_system_under_test]. You will also see that all of the fields in the test classes are static and not instance. The 2 fields in the base concern_for_mapping_step class are there to hold references to dependencies of the system under test. I don’t need to have them there as they are accessible using a helper method on the base test class (more about the base test class hierarchy in a minute), I just like to have them as I find it a bit more readable than calling methods to access the dependencies of the system under test ex:

  • I prefer referring to a field named: target_action as opposed to repeatedly having to call a method such as:
    • Mock<ITargetAction<SomeDestinationObject,string>> / the_dependency<ITargetAction<SomeDestinationObject,string>> (of course, in this example, the generic signatures emphasize the issue even more!!!)

Second thing to notice is the use of a field named c which is of a delegate type named context. Here is the definition for the context delegate type:

public delegate void context();

Nothing all that special about it. This field will get used back up in the base test class to “establish the context for the test to run” much like a traditional setup method would / constructor if you are using xUnit.

If we focus our attention now on the “when_an_expression_mapping_step_is_told_to_run’ class, you will see that it inherits from the base concern class. The base concern class will be used to hide fields/extra noise that would otherwise pollute the test. You will see that this test also has its own context block. Context blocks are applied recursively from the top of the hierarchy down, this ensures that any contexts in base classes will always run first. In the past I would use overriden methods to accomplish this, but then you had to deal with making sure to call the base “establish_context” method, and if you forgot you could have tests fail because of a silly omission. By adhering to a convention of placing scaffolding in a context block, the “framework” takes care of ensuring that contexts are run in the correct order.

The following block:

because b = () => sut.map(item, destination);

focuses our attention to what behaviour of the system under test we are testing (in the particular context). You will notice that I use the name of the class to embody both action and context. Of course, in this particular test I am focusing on a happy day scenario. An example of testing in another context could be a test fixture named:

  • when_a_mapping_step_is_told_to_map_from_an_invalid_source

This name implies context. In the first test I am just testing the behaviour of mapping. In the second test (which is a different context), I am testing how the sut behaves when it is provided invalid data. One of the things that is hard to see from this example is that one context (test fixture) could have several observations (assertions). In this current example there is only 1 observation being made.

Notice that the because block, like the context block is a field of a simple delegate type (another void delegate type). This means that the code does not execute as it is just an anonymous method of certain delegate type being assigned to a field of a matching delegate type.

Finally observations are made. Notice the use of the Observation attribute. Inside an observation (Test) I will make logical assertions against either the system under test, the dependencies, or the outputs of the method under test. It is best to try to stick to one logical assertion (keeping in mind that 2 actual assertions can be part of 1 logical assertion) per observation. This is why you will often see a single Context (TestFixture) with multiple Observations.

One of the things that you may have missed is the fact that the System Under Test is never instantiated. This is also taken care of in a base class. I have the ability to override the creation of the system under test, but for most tests, letting the SUT be created for me saves a couple of lines of code, and allows me to not have to change things as more dependencies get added.

So how does all of this work? Currently all of this is coded to run against MBUnit 2.5. I have a project called jpboodhoo.commons.bdd (part of jpboodhoo.commons) where I place all of the plumbing code to make all of this work. Here is a snapshot of the project:

image

This is one of those utility type projects that got harvested over time as I saw patterns start to emerge. Under the concern folder there are 4 main classes:

image

In my projects I derive from either one of the following 3:

  • observations_for_a_static_sut
  • observations_for_a_sut_with_a_contract
  • observations_for_a_sut_without_a_contract

Those 3 base classes cover the range of classes I may want to write tests against. I am hoping that the naming of the classes is pretty self explanatory. Here are the definitions for each of the above 3 classes:

public abstract class observations_for_a_static_sut : an_observations_set_of_basic_behaviours { }

This one is the most basic, it simply inherits from “an_observations_set_of_basic_behaviours”. I derive from this class when I am testing static classes. The other 2 are equally as simple with a little twist:

public abstract class observations_for_a_sut_with_a_contract<Contract, ClassUnderTest> : observations_for_an_instance_sut<Contract, ClassUnderTest> where ClassUnderTest : Contract { }

I derive from this class when I want to write tests against a class, but code the tests against an interface of the class, and not the class itself. Here the term interface/contract applies to either a C# interface, or a class that the ClassUnderTest inherits from (usually an abstract class). The final base class (that I can choose to derive from) is very similar:

public abstract class observations_for_a_sut_without_a_contract<SystemUnderTest> : observations_for_an_instance_sut<SystemUnderTest, SystemUnderTest> { }

Notice how this class derives from the same class as the previous class, except that it uses the same type for providing the generic arguments to the “observations_for_an_instance_sut”

Again, the 3 classes that I have just covered are there to introduce a convention for people (right now just me) to follow when they are writing their own tests classes. The naming of the 3 makes it pretty simple( I think) to figure out which one you would start with.

With those 3 covered it really leaves the 2 “big ones” that hide a lot of plumbing and MBUnit specific details. Let’s start by taking a look at the skeleton for the “an_observations_set_of_basic_behaviours”:

[Observations] public abstract class an_observations_set_of_basic_behaviours { static protected IDictionary<Type, object> dependencies; static Exception exception_thrown_while_sut_performed_its_work; static protected Action behaviour_of_the_sut; [SetUp] public void setup() { } [TearDown] public void tear_down() { } void do_setup() { } after_each_observation a = () => dependencies.Clear(); ICommand build_command_chain<DelegateType>() { } void run_action<DelegateType>() { } protected virtual void initialize_system_under_test() { } static public void doing(Action action) { } static protected Exception exception_thrown_by_the_sut { } static Exception get_exception_throw_by(Action action_that_should_be_taken_by_the_sut) { } static protected object an(Type type) { } static protected InterfaceType an<InterfaceType>() where InterfaceType : class { } }

This is just the interface (we’ll dive into implementation of each method in time!!). Let’s break it down step by step. First thing you should see is the use of the Observations attribute on the class itself. This is basically just an alternative to the TestFixtureAttribute (thanks go to Albert Weinert for suggesting this). Here is the code:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ObservationsAttribute : TestFixturePatternAttribute { public ObservationsAttribute(string description) : base(description) { } public ObservationsAttribute() { } public override IRun GetRun() { var run = new SequenceRun(); run.Runs.Add(new OptionalMethodRun(typeof (SetUpAttribute), false)); run.Runs.Add(new MethodRun(typeof (ObservationAttribute), true, true)); run.Runs.Add(new OptionalMethodRun(typeof (TearDownAttribute), false)); return run; } }

The main thing you should get out of this is that the GetRun method tells MbUnit to look for methods that are decorated with the ObservationAttribute, and to treat them as tests. The ObservationAttribute is really simple:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class ObservationAttribute : TestPatternAttribute { }

You have already seen this attribute used on the test earlier. The thing that should be immediately apparent about the “an_observations_basic_set_of_behaviours” class is that it is there to shield the rest of the test code from the details of whatever xUnit framework you are targeting (in this case, MBUnit).

Tomorrow I’ll continue by breaking down the responsibilities of this class in a piece meal fashion.

Develop With Passion!!

Comments [5] | | # 
 Wednesday, December 10, 2008
Wednesday, December 10, 2008 4:44:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

The title is definitely a mouthful!!

A project a year ago (yep, I’m quite behind on the technical blogging front) required the need for Excel generation and formatting. Unlike other Excel generation tasks I had done in the past, this particular task called for generation of tabbed workbooks, with graphs, fancy formatting etc. Much more involved than the trivial stuff I had typically done with excel in the past.

Applying formatting to elements in a tree is a perfect job for the Visitor pattern!! Of course, different types of formatting need to be applied to different cells, some cells need multiple types of formatting applied to them. Composite pattern can come to the rescue here. How can we filter out different types of formatting to certain cells / range of cells? The Specification pattern can come in handy here.

The project resulted in the creation of a fairly flexible excel formatting engine (that has been run against 3rd party excel frameworks SpreadSheetGear, and OfficeWriter).

Here is the interface for a cell visitor:

public interface ICellVisitor { void visit(IRange cell); }

And here is the implementation for the composite visitor:

public class CompositeCellVisitor : ICellVisitor { private IList<ICellVisitor> all_visitors; public CompositeCellVisitor() { all_visitors = new List<ICellVisitor>(); } public void add(ICellVisitor visitor) { all_visitors.Add(visitor); } public void add_all(IEnumerable<ICellVisitor> visitors) { foreach (var visitor in visitors) add(visitor); } public void visit(IRange cell) { foreach (var visitor in all_visitors) visitor.visit(cell); } }

As you can see, a composite basically implements the same interface as the things it is being composed of and it simply (for the most part) does its job by delegating to each of its leaf items to do their jobs. In this case, each visitor is told to visit a cell. This means that when an iterator for a spreadsheet (which essentially makes sure to walk over each cell in the spreadsheet) walks to a certain cell, it can then tell the CompositeVisitor to visit the cell. Because the composite is composed of all the possible visitors that can visit a cell, you only need to pass through the spreadsheet once to apply all formatting.

Here are the names of some of the formatting that can be done:

  • ApplyAllCellBorders
  • AutoFitCellWidth
  • BoldFont
  • ChangeFontSize
  • CustomFormat
  • FormatBackColor

Here is the implementation of one of the visitors:

public class FormatBackColor : ICellVisitor { private Color color; public FormatBackColor(Color color) { this.color = color; } public void visit(IRange cell) { cell.Interior.Color = color; } }

As you see, the visitor is only responsible for a single discrete action. It has no knowledge as to whether or not it should actually apply itself against a cell, it just goes ahead and applies itself. This would obviously cause problems as there needs to be a way to allow a Visitor to visit/not visit a cell, without necessarily giving the visit the extra responsibility of making that determination. To accomodate this I separated responsibilities (matching/visiting) by “favouring composition” here is a class that was created to solve this problem in an SRP fashion:

public class ConstrainedCellVisitor : ICellVisitor { private ICellVisitor cell_visitor; private ISpecification<IRange> constraint; public ConstrainedCellVisitor(ICellVisitor cell_visitor, ISpecification<IRange> constraint) { this.cell_visitor = cell_visitor; this.constraint = constraint; } public void visit(IRange cell) { if (constraint.is_satisfied_by(cell)) cell_visitor.visit(cell); } }

The ConstrainedCellVisitor is composed of a raw visitor (that will perform an action against the cell) as well as the specification that will determine whether the cell in questions meets the criteria to be visited with the actual concrete formatting visitor.

The specification interface is something I am sure you have seen me use before (lots of usages, different contexts):

public interface ISpecification<T> { bool is_satisfied_by(T item); }
 
 

All that is needed to finish it off is a very simple configuration api to configure visitors with specifications. Here is one example of a line that builds a visitor and a specification:

yield return new ConstrainedCellVisitor( new ChangeFontSize(8), Cell.occurs_between_columns(3, 8) .and(Cell.occurs_after_row(5)) .or(Cell.is_named("P3")));
 
 

With this model, the ability to add new formatting needs was as simple as adding a new visitor that was only concerned with a specific formatting. This allowed for the incremental growth of formatting visitors as the report demanded it.

This is just one example of where using the power of composition and a couple of “seemingly” simple patterns, can yield results that are extremely extensible results. IMHO the Command and Visitor patterns are 2 of the most powerful and highly underused design patterns a developer has in their toolkit (of course, like with any design pattern, you need to use them wisely).

Comments [2] | | # 
 Tuesday, November 25, 2008
Tuesday, November 25, 2008 7:15:00 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I was in the middle of the last Nothin But .Net class (more on that in a later post) and I started playing around with a slightly different way to write unit tests (inspired by the look of MSpec). It was cool to build it/demo it/ and use it in front of the class. Here is some sample code written using the new style:

[Concern(typeof (ShoppingCart))] public class when_a_bag_of_ruffles_chips_is_added_to : a_shopping_cart_with_a_can_of_pepsi_in_it { static IShoppingCartItem an_item_for_a_bag_of_ruffles; static IProduct a_bag_of_ruffles; context c = () => { an_item_for_a_bag_of_ruffles = an<IShoppingCartItem>(); a_bag_of_ruffles = an<IProduct>(); when_the(shopping_cart_item_factory).is_told_to(x => x.create_a_shopping_cart_item_from(a_bag_of_ruffles)) .Return(an_item_for_a_bag_of_ruffles); }; because b = () => sut.add(a_bag_of_ruffles); [Observation] public void an_item_for_the_bag_of_ruffles_should_be_stored_in_the_cart() { shopping_cart_items.should_contain(an_item_for_a_bag_of_ruffles); } [Observation] public void should_have_items_for_both_the_can_of_pepsi_and_the_bag_of_ruffles() { shopping_cart_items.should_contain(an_item_for_a_can_of_pepsi, an_item_for_a_bag_of_ruffles); } }

The use of the lambdas for the context (setup) and because(action of the system under test) causes them to not jump to the eyes as quickly as the concern and the observations (as they attributes help draw your eyes to them faster. Lots of tests were written in class. The context block can be shared with other contexts that occur up the hierarchy. Outside of the mechanics of how setup and teardown are now handled, it is still very much a NUnit/MbUnit flavoured test with a heavy BDD spin on it. One of the nice things that I have started taking advantage of is having the system under test automatically created for me (in a base class, with the option to override). I have also put in a lot of effort to shield myself from the noise of mock object frameworks and testing specific nomenclature (notice the an method).

I am going to be releasing some more stuff on this in the next couple of days. I just wanted to give a sneak peek. You will notice that I have opted to not bother trying to come up with meaningful names for the context and because fields. I name the fixture/concern to be descriptive as to the context of the sut I am testing, and the names of the observations fill out the rest of the meaty details.

Thoughts?

Develop With Passion!!

Comments [15] | | # 
 Wednesday, October 29, 2008
Wednesday, October 29, 2008 4:00:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

In response to a comment from the  last post, here is the interface of the BDDExtensions that were driven out from the last NBDN course:

public static class BDDExtensions { public static void force_traversal<T>(this IEnumerable<T> items) public static void should_be_null(this object item) public static void should_contain<T>(this IEnumerable<T> items, T item) public static void should_be_greater_than<T>(this T item, T other) where T : IComparable<T> public static void should_not_be_equal_to<T>(this T item, T other) public static void should_be_equal_ignoring_case(this string item, string other) public static void should_only_contain<T>(this IEnumerable<T> items, params T[] items_to_find) public static void should_only_contain_in_order<T>(this IEnumerable<T> items, params T[] items_to_find) public static void should_be_true(this bool item) public static void should_be_false(this bool item) public static void should_be_equal_to<T>(this T actual, T expected) public static ExceptionType should_throw_an<ExceptionType>(this Action work_to_perform) public static void should_not_throw_any_exceptions(this Action work_to_perform) public static void should_be_an_instance_of<Type>(this object item) public static void should_not_be_null(this object item} }

This is the main base set of extensions. I usually have a whole family of application specific extensions that come into play for doing application specific assertions.

Develop with Passion!!

Comments [1] | | # 
Wednesday, October 29, 2008 2:36:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

Thanks to a suggestion from Albert Weinert I have added 2 new test attributes to the spec helpers layer of my codebase (this is the folder that contains all of the test related utilities).

For a long time I have been aliasing the TestAttribute and changing it to observation. Instead with a suggestion from Albert, I have now added 2 new attribute classes to the spec helpers layer (Albert sent me the code, I just renamed the TestPatternAttribute class):

[AttributeUsage(AttributeTargets.Method,AllowMultiple = false)] public class ObservationAttribute : TestPatternAttribute {}

[AttributeUsage(AttributeTargets.Class,AllowMultiple = false)] public class Observations : TestFixturePatternAttribute { public Observations(string description) : base(description) { } public Observations() { } public override IRun GetRun() { var run = new SequenceRun(); run.Runs.Add(new OptionalMethodRun(typeof(SetUpAttribute),false)); run.Runs.Add(new MethodRun(typeof(ObservationAttribute),true,true)); run.Runs.Add(new OptionalMethodRun(typeof(TearDownAttribute),false)); return run; } }

This is much cleaner than aliasing (as well as adhering to DRY). I chose to keep this in my codebase vs rolling it into MbUnit as it gives people the freedom to name the attributes the way they feel. Because all of my test fixtures inherit from a base fixture, this change only required changing the attribute on my base test fixture as well as a quick search/replace to eliminate the:

using Observation = MbUnit.Framework.TestAttribute;

Thanks Albert.

Develop With Passion

Comments [1] | | # 
 Tuesday, October 28, 2008
Tuesday, October 28, 2008 10:43:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

In my ongoing quest to simplify the use of mock objects and to make the test code that I write remove the need for testing specific nomenclature. I made a small update to the BDDExtensions that I use when working with Rhino Mocks. Here is the class in question:

public static class RhinoMocksExtensions { public static VoidMethodCallOccurance<T> was_told_to<T>(this
T mock, Action<T> item) { return new VoidMethodCallOccurance<T>(mock, item); } public static IMethodOptions<R> when_told_to<T, R>(this T mock
, Function<T, R> func) where T : class { return mock.Stub(func); } }

The above 2 extension methods are the only ones I need to use when working with my mock objects. As you can see, they are just non-testing-nomenclature specific wrappers around existing rhino mocks methods.The was_told_to extension method is a method that I use to verify that a void method call message was sent to a mock object. You can see that the method returns a VoidMethodCallOccurance class that looks like this:

public class VoidMethodCallOccurance<T> { public Action<T> action; private T mock; public VoidMethodCallOccurance(T mock, Action<T> action) { this.mock = mock; this.action = action; mock.AssertWasCalled(action); } public void times(int number_of_times_the_method_
should_have_been_called) { mock.AssertWasCalled(action, y => y.Repeat.Times(number_of
_times_the_method_should_have_been_called)); } public void only_once() { times(1); } public void twice() { times(2); } }

This class allows you to specify the number of times a method was called on mock object. Which allows you to do this:

[Observation] public void should_tell_the_log_4_net_initialization_command_
to_run() { initialization_command.was_told_to(x => x.run())
.only_once(); }

as opposed to this:

[Observation] public void should_tell_the_log_4_net_initialization_command_
to_run() { initialization_command.AssertWasCalled(x => x.run()
,y => y.Repeat.Times(1)); }
 
It is a small change, but one that, IMHO, adds a lot to the
readability of the test.
 
Develop With Passion!!
Comments [3] | | # 
 Tuesday, August 26, 2008
Tuesday, August 26, 2008 10:47:36 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I am currently going through my existing application and refactoring for a bit more readability (with a focus on natural language). Could I get your feedback onthe readability of the following piece of code which demonstrates a chain of responsibility:

Run.the<wire_up_global_error_handling>() .then<initialize_the_container_for_the_user_interface>() .then<initialize_the_user_interface_registry>() .then<initialize_the_ui_images_registry>() .then<initialize_the_main_menus>() .execute();

Underscores in code seem to have permeated a lot of my thinking. And I am currenlty playing around with lowercase method naming with underscores to separate significant words. How would you feel if you were presented with this code to read? Be brutally honest!!

 

Develop With Passion!!

Comments [2] | | # 
 Friday, June 13, 2008
Friday, June 13, 2008 5:47:58 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

Having downloaded and started to use Rhino Mocks 3.5 beta pretty much as soon as Oren released. I am very happy with the AAA style (Arrange, Act, Assert) and the readability and brevity it has brought to my tests. The current project I am on has a huge set of tests. Here is an example of using Rhino Mocks, in conjunction with some BDD style naming:

[Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_to_be_created : behaves_like_unit_of_work_with_scope_storage_in_play { protected override void because() { sut.Create(); } [Observation] public void Should_access_scoped_storage_to_determine_if_a_unit_of_work_is_already_active() { scoped_storage.was_told_to(item => item.DoesNotContain<IUnitOfWork>()); } } [Concern(typeof (UnitOfWorkFactory))] public class When_creating_a_unit_of_work_and_the_scoped_storage_does_not_contain_an_active_unit_of_work : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); scoped_storage.setup_result(item => item.DoesNotContain<IUnitOfWork>()).Return(true); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); } protected override void because() { sut.Create(); } [Observation] public void Should_store_the_newly_created_unit_of_work_in_scoped_storage() { scoped_storage.was_told_to(item => item.Store(Arg<IUnitOfWork>.Matches(uow => uow != null))); } } [Concern(typeof (UnitOfWorkFactory))] public class When_a_new_unit_of_work_is_requested_and_one_already_exists_in_scoped_storage : behaves_like_unit_of_work_with_scope_storage_in_play { private ISession session; private IUnitOfWork new_unit_of_work; private IUnitOfWork active_unit_of_work; protected override void establish_context() { base.establish_context(); session = Dependency<ISession>(); active_unit_of_work = Dependency<IUnitOfWork>(); nhibernate_session_factory.setup_result(item => item.OpenSession()).Return(session); scoped_storage.setup_result(item => item.Contains<IUnitOfWork>()).Return(true); scoped_storage.setup_result(item => item.Retrieve<IUnitOfWork>()).Return(active_unit_of_work); } protected override void because() { new_unit_of_work = sut.Create(); } [Observation] public void Should_return_a_non_disposing_unit_of_work_proxy() { new_unit_of_work.should_be_an_instance_of<NonDisposableUnitOfWork>(); } }
 

I am no longer using the automocking container so you are probably wondering what the Dependency method call is all about. It is simply a method defined on a base ContextSpecification class whose definition is as follows:

 

[Context] public abstract class ContextSpecification { [SetUp] public void setup() { unit_test_container.Initialize(); establish_context(); because(); } [TearDown] public void teardown() { after_each_specification(); unit_test_container.tear_down_and_unregister_from_dependency_registry(); } protected abstract void because(); protected abstract void establish_context(); protected virtual void after_each_specification() { } protected InterfaceType Dependency<InterfaceType>() { return MockRepository.GenerateMock<InterfaceType>(); } protected InterfaceType Stub<InterfaceType>() { return MockRepository.GenerateStub<InterfaceType>(); } }

And I have some extension methods that wrap the RhinoMocks "assertions" with more language oriented assertions: Instead of AssertWasCalled you get was_told_to, and so on.

 

Develop With Passion!!

Comments [11] | | # 
 Sunday, May 11, 2008
Sunday, May 11, 2008 4:18:21 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

For the longest time (the last 4 months!!) I have been using the following style of code to determine whether exceptions are thrown in my codebases:

typeof (InterfaceResolutionException).ShouldBeThrownBy(() => DependencyRegistry.GetMeAn<IDbConnection>());

As you can see, all that I am doing here is leveraging an extension method that hangs of the type class:

public static void ShouldBeThrownBy(this Type exceptionType,Action workToDo) { GetExceptionFromPerforming(workToDo).ShouldBeAnInstanceOf(exceptionType); }

This extension method lives in a library of extension methods that I use when doing Behavior Driven Development and trying to leverage natural language as close as possible vs the traditional Assert this/that.

I just switched it up a bit to change it to make it completely foolproof, as with the original extension method you could have easily done this:

typeof (SqlConnection).ShouldBeThrownBy(() => DependencyRegistry.GetMeAn<IDbConnection>());

This code would compile and run, but SqlConnection is not an exception type. What I want to be able to do, to address this issue is flip things around like this: 

(() => DependencyRegistry.GetMeAn<IDbConnection>()).ShouldThrowA<InterfaceResolutionException>();

Notice how I am trying to use 2 different concepts here:

  • Extension methods having off of a lambda expression
  • Generics to ensure that the type provided to the ShouldThrowA method is an derivative of Exception

The only real problem with this is that you can't have an extension method that hangs off a lambda. What I can do is the following to get started:

public static void ShouldThrowA<ExceptionType>(this Action workToDo) where ExceptionType : Exception { GetExceptionFromPerforming(workToDo).ShouldBeAnInstanceOf<ExceptionType>(); } public static Exception GetExceptionFromPerforming(Action work) { try { work(); } catch(Exception e) { return e; } return null; }

The first thing that I did is to create an extension method that belongs to any Action delegate instance. Notice the use of the generic constraint to ensure that the generic type parameter provided to the method is an actual derivative of Exception, which ensures that using this method is only applicable to exception throwing behaviors for a specific exception type. The second method GetExceptionFromPerforming (you will notice that I commonly use a style of naming that makes the method name coupled with its parameters the full name of the method, read the line as GetExceptionFromPerforming(work) vs GetExceptionFromPerformingWork(work), just a little bit of redundancy I don't care for) returns the exception caught while trying to execute the Action.

The ShouldBeAnInstanceOf method is another extension method that gets associated with any object, it just makes use of an existing assertion in the MbUnit library.

All of the building blocks are in place there is only one problem. I can't do this:

(() => DependencyRegistry.GetMeAn<IDbConnection>()) .ShouldThrowA<InterfaceResolutionException>();

So with just the following new class added to the my BDD Extensions Class:

 

public static class The { public static Action Action(Action workToDo) { return workToDo; } }

Looks a little weird, to have a method that looks like all it is doing is returning what it was called with, but in this case it is actually allowing us to allow assignment of the lambda to a known type which ultimately allows us to have extension methods that are bound to that known type (in this case the Action delegate). With all of these places in place this is how I now do assertions for exceptions thrown in a piece of SUT code:

The.Action(() => DependencyRegistry.GetMeAn<IDbConnection>())
                    .ShouldThrowA<InterfaceResolutionException>(); 

 

In this code the SUT is the DependencyRegistry which is actually a Static Gateway to container functionality.

Develop With Passion!!

Comments [3] | | # 
 Wednesday, April 23, 2008
Wednesday, April 23, 2008 4:11:54 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

Looks like Ilya Ryzhenkov of JetBrains shares my same thoughts with regards to using implicitly typed local variables!!

It is an interesting read that you may want to check out here.

Develop With Passion!!

Comments [0] | | # 
Tuesday, April 22, 2008 11:02:56 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I had a couple of interesting discussions at the recent MVP summit around my preference to using the var keyword in my recent set of codebases.

I argued that people who are already in the habit of expressively naming their variables are going to be much more open to dropping the extra "noise" of specifying the type on both sides of the variable declaration.

Having been exposed to dynamic languages (Ruby) has definitely altered my perspective with regards to considering this:

IList<Customer> listOfCustomers = new List<Customer>()

Much more noisy than this:

var listOfCustomers = new List<Customer>()

As I strive toward more readable, intent revealing code, I find myself looking at the intent behind the usage of the variable coupled with a meaningful name, vs the actual type. In reality, I find the the argument to not use var is a moot point in a static environment that provides you with all the information you need once you hit the "."

How do you var?

Develop With Passion!!

Comments [6] | | # 
 Wednesday, March 05, 2008
Wednesday, March 05, 2008 6:49:38 PM (Mountain Standard Time, UTC-07:00) ( Agile | C Sharp | Training )

This is just a message to those people who are interested in attending next months Nothin But .Net session in Austin, TX. There are only 6 spots left. Tell your friends, tell your co-workers. This session promises to be an absolute blast. The attendance roster is varied and will provide for lots of interesting conversation and pair programming opportunities.

You can register for the course here:

http://www.acteva.com/booking.cfm?bevaID=150826

Develop With Passion!!

Comments [1] | | # 
 Tuesday, March 04, 2008
Tuesday, March 04, 2008 3:23:51 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Presentations )

Last week I had the honor of presenting at the Calgary .Net User group on the topic of Generics in .Net. In retrospect, I think the fact that I was leveraging vs2008, and C# 3.5 potentially clouded focus on raw generics.

Nonetheless, there was lots of good discussion, and a lot of concepts were able to get demonstrated. Among the nuggets that were started:

  • Generic Ranges
  • Specification based querying
  • Strongly typed dto mappers
  • Generic dto mappers
  • Type safe query objects

All code was created on the fly during the presentation, and 3 blesses attendees were able to walk away with a copy of ReSharper.

As a side note, my speaking schedule is starting to fill up for the year, if you think your user group would be interested in having me out to do a presentation; please do not hesitate to contact me at: jp@jpboodhoo.com.

The code for the presentation is available here. None of the 3rd party libraries are present in the download, if you actually want to run the code you will have to go and download the tools specified in the following folders:

  • build\tools
  • thirdparty\tools

To extract the rar file you can use WinRar or 7Zip (I am sure there are lots of others).

Develop With Passion!!

Comments [4] | | # 
 Friday, February 22, 2008
Friday, February 22, 2008 3:11:53 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Tools )

Ever since the nightly builds for ReSharper 4.0 went live, being the REA (Resharper early adopter) that I am, I downloaded it and have been using it on my C# 3.5 projects. I am happy to report that even though it is in the pre EAP phase, it is extremely solid and a joy to work with.

The support for the new language features such as extension methods, automatic properties ... is great. So far I have had only one exception dialog pop up. For those of you who have braved prior EAP's for ReSharper (remember ReSharper 2.0 EAP!!!) you have probably already developed a thick skin for the exception dialogs that typically pop up during EAP. So far this is not the case.

In all honesty, those of us who love ReSharper would be more than willing to put up with multiple exception dialogs as, let's face it, studio without ReSharper == "I won't use it".

So what are you waiting for, head over and download the latest nightly build. Keep in mind that results may vary between use as well as different nightly builds!!

Develop with Passion!!

Comments [1] | | # 
 Wednesday, February 20, 2008
Wednesday, February 20, 2008 8:25:28 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

The following snippet of code (C# 3.5) is allowable, and gives you the benefit of unnecessary extra verbosity with the benefits of encapsulation. Of course, if you need to implement logic in your property, then you don't want to think about automatic properties:

public T Item { get; private set; }

Comments [2] | | # 
 Wednesday, February 13, 2008
Wednesday, February 13, 2008 11:57:32 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

Had a question recently with regards to presenter first development in a smart client application.

“How do you tell the presenter to run?”

In presenter first style, the presenter will be the first point of contact from the ApplicationController. It will be the presenters responsibility to tell its associated view to render, etc. In my current smart client application I am making heavy use of commands that can be attached to arbitrary elements : buttons, linkbutton, menu items, to initiate the running of a command. Here is a small piece of code that should give away how I am hooking up commands to presenters in the application:

public class RunPresenterCommand<Presenter> : ICommand where Presenter : IPresenter { private IApplicationController controller; public RunPresenterCommand(IApplicationController controller) { this.controller = controller; } public void Execute() { controller.Run<Presenter>(); } }

Notice that all this command does when told to execute is to dispatch a call to the application controller, telling it to run the associated presenter. This keeps the responsibility of starting up the presenter in the place that it should be, the ApplicationController.

Hope that answers the question.

Comments [2] | | # 
 Wednesday, January 30, 2008
Wednesday, January 30, 2008 7:27:34 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

This is a very short post to demonstrate the concept that I mentioned in parting during the last post.

“And of course I could eliminate the method call tracker altogether if I made use of lambda expressions and parsed the expression tree to see what method was called”

Someone fired an email asking how to do this so I thought I would quickly implement to show them the result. You can now also set filters on the interceptor by use of a lambda expression. So instead of this (and you can still do this):

IInterceptorConstraint<IAnInterface>constraint = sut.AddInterceptor<SomeInterceptor>(); constraint.InterceptOn.OneMethod();

or this: 

IInterceptorConstraint<IAnInterface> constraint = sut.AddInterceptor<SomeInterceptor>(); constraint.InterceptOnMethods(constraint.InterceptOn.ValueReturningMethodWithAnArgument(1));

You can now use a lambda expression which negates the need to store a reference to the constraint to apply constraints:

sut.AddInterceptor<SomeInterceptor>() .InterceptCallTo(x => x.OneMethod()) .InterceptCallTo(x => x.SecondMethod());

The InterceptCallTo method accepts an ExpressionTree of type Action<T> where T is the target to be proxied. The code to parse this expression tree into a method call is very simple. The InterceptorConstraint class just forwards the call onto its MethodCallTracker:

public IInterceptorConstraint<Target> InterceptCallTo(Expression<Action<Target>> expression) { callTracker.AddCallInferredFrom(expression); return this; }

Notice that the method returns the InterceptorConstraint itself, which is what allows for the very limited fluent interface. As far as parsing the expression to store the method to be intercepted on, it is all done by the MethodCallTracker itself: 

public void AddCallInferredFrom(Expression<Action<T>> expression) { MethodCallExpression methodCallExpression = expression.Body as MethodCallExpression; if (methodCallExpression != null) AddCallFor(methodCallExpression.Method.Name); }

That’s it, that’s all. The AddCallFor method is now called from both here and the original Interception tracker to store the list of methods that should be intercepted on.

Develop with Passion!!

Comments [0] | | # 
Wednesday, January 30, 2008 4:31:58 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Training )

Another awesome course is entering the lineup for the March timeframe also. Unlike Wendy’s kick butt WPF course which is occuring in New York in the month of March, this course will be a Canuck affair, to be held in the winter wonderland of Edmonton!!

Donald Belcham (aka. Igloo Coder) will be the instructor for the course, and he has a crazy week lined up for the people interested in stepping up for the challenge.

You can register for the course here. Sign up quick, as seating is limited. Here is a description of the course:

Overview

Nothin’ But C# v3.5 is a 5 day boot camp styled course that provides in depth training in the new language features in version 3.5 of the .Net Framework.  Attendees will work with the new features in this version of the Framework to gain an understanding of their operation at a very deep level and aid them in the pragmatic implementation of these tools in their daily development.

While learning to use the new features of .Net v3.5, the students will also be introduced to foundational object oriented programming techniques.  They will learn both how to implement these techniques as well as understanding the benefits that they offer.

By the end of the course you will have knowledge of the new features at a very detailed level.  You will understand the concepts behind their existence, the limitations that they have and how you can use them to write better code in real applications.  None of the concepts will be taught using wizards, drag and drop or templates.  Attendees will be learning how to implement these language features combined with OO best practices and using techniques such as TDD.

Attendees should have a good understanding of programming in .Net and OO practices.  This is not an introductory course for learning to program with .Net.

Core Concepts Overview

  • New language features in .Net 3.5
  • Extension Methods – helping to make fluent interfaces
  •  Lambda Expressions – from refreshers on delegates all the way to the lean lambda
  •  Linq – for SQL, XML, Objects, etc.
  • New User Interface Controls
  •  ASP.NET MVC
  • Object Oriented Foundations

Detailed Topic Coverage Breakdown

·          New Language Features

o    Simple Properties

o    Anonymous Constructors

o    Anonymous Types

o    DateTime2

o    TimeZoneInfo

o    HashSet<T>

o    Active Directory Integration

o    Diagnostics

o    Cross Framework compatibility

·          Extension Methods

o    Using with primitive types

o    Using with complex types

o    Using with enumerations

o    Using to build fluent interfaces

o    How they are interpreted by the compiler

o    Dangers and code smells

·          Lambda Expressions

o    Refresher on Delegates

o    Refresher on Anonymous Delegates

o    Refresher on Predicates

o    Learn the syntax

o    Replacing Anonymous Delegates with Lambdas

o    How are they interpreted by the compiler

·          Linq

o    Linq fundamentals

o    How is Linq interpreted by the compiler

o    Linq to SQL

o    Linq to XML

o    Linq to Objects

o    Linq to Dataset

o    Linq and performance

·          UI Components

o    ListView control

o    DataPager control

·          ASP.NET MVC

o    MVC fundamentals

o    Writing Views

o    Routing

o    Plugging in Inversion of Control containers

o    Testability

·          Object Oriented Foundations

o    Single Responsibility Principle

o    Separation of Concerns

o    Design by Contract

o    Dependency Injection and Inversion of Control

o    Design Patterns

 

Target Audience

This is an intermediate level course that will prepare developers to work with the release of the .Net 3.5 framework.  Attendees should have a working knowledge of .Net and knowledge of the following

  •         Core working knowledge of either Visual Basic or C#
  •         Base grasp of Object Oriented Design principles
  •         High level understanding of SQL Server and XML

Intended Outcomes

Once attendees have completed this course they should have a strong, practical understanding of the following:

 

  • New base language features in the .Net 3.5 framework
  • Lambda expressions
  • Linq for SQL, XML and Objects
  • Extension methods
  • ASP.NET MVC
  • Design by contract
  • Practical application of basic patterns
  • Test Driven Development

 

About The Coordinator

Donald Belcham is a software developer with a strong focus on .NET development platforms.  He has been building application with .NET since the release of version 1.1 of the framework.  More recently Donald has become very active in the developer community as the President of the Edmonton .NET User Group.  The combination of that role and a passion for bettering the skills of any software developer, Donald has become a regular speaker at User Groups, Code Camps and conferences across North America.  He advocates and speaks on the creation of a solid set of foundational object oriented skills and understandings that can then be used with any of the many appropriate tools.  These activities and beliefs have garnered Donald a Microsoft MVP award in C#.

Donald can be reached at donald.belcham@igloocoder.com and via phone at 780.974.5860.  He welcomes open and frank conversations on different development techniques at his website www.igloocoder.com

Once again, you can register for the course here. If you have any questions do not hesitate to contact me at jp@jpboodhoo.com

 

Comments [0] | | # 
Wednesday, January 30, 2008 2:19:04 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

Had the question the other day:

“How could I dynamically create a proxy around an object (interface based proxies are not a problem) and then selectively apply interceptors at a method by method level if necessary”.

Let’s clear up a bit of terminology so that everyone is on the same page with regards to the problem at hand:

Proxy – An object that implements the same interface as a target object and intercepts methods calls to the target to perform some sort of pre and or post method invocation.

Interceptor – An object that can be plugged into a proxy to perform a pre/post method invocation step. Common example that most people are familiar with is a LoggingInterceptor.

Attacking the problem test first drove me down a fairly interesting path that I was pleased with for a first cut. I’ll explain the details in a minute, but examples speak a lot louder than words. I created a couple of dummy interfaces and a simple object to demonstrate the proxying/interception capabilities. It should also be noted that I am making use of Castle DynamicProxy as I feel it is an much easier barrier of entry for people who want to take advantage of creating dynamic proxies vs dropping down to the wire and leveraging Reflection.Emit classes directly (though that is something that I strongly recommend playing with a couple of times, just so you have an understanding for it). Here are the interceptors that will be used in this example:

public class SomeInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { Console.Out.WriteLine("Interception occured on method {0} with {1}",invocation.Method.Name,this.GetType().Name); invocation.Proceed(); } }

public class SomeOtherInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { Console.Out.WriteLine("Interception occured on method {0} with {1}",invocation.Method.Name,this.GetType().Name); invocation.Proceed(); } }

As you can see. Both of these interceptors are ridiculously simple. They both implement the IInterceptor interface that comes from Castle.Core, the interface itself only has one method called Intercept which is the method that will get invoked by the proxy when a method call is intercepted. Both of these classes lived in a test fixture class file, so I was not concerned with the evident duplication. Here are the interface and implementation for the item that is going to be proxies:

public interface IAnInterface { void OneMethod(); void SecondMethod(); int FirstValueReturningMethod(); int ValueReturningMethodWithAnArgument(int number); } public class SomeImplementation : IAnInterface { public void OneMethod() { Console.Out.WriteLine("Real work is being done in OneMethod"); } public void SecondMethod() { Console.Out.WriteLine("Real work is being done in SecondMethod"); } public int FirstValueReturningMethod() { Console.Out.WriteLine("Real work is being done in FirstValueReturningMethod"); return 1; } public int ValueReturningMethodWithAnArgument(int number) { Console.Out.WriteLine("Real work is being done in ValueReturningMethodWithAnArgument"); return 1 + number; } }

Again, substitute this interface and implementation with any interface/implementation pair that you would want to create a proxy for in your own application. With all of those, I’ll show you some usages of the final product before explaining the solution:

Scenario 1 : Intercept on all method invocations with a SomeInterceptor

[Test] public void Should_proxy_all_methods_with_some_interceptor() { IAnInterface anImplementationOfTheInterfaceToProxy = new SomeImplementation(); sut = new ProxyBuilder<IAnInterface>(); sut.AddInterceptor<SomeInterceptor>(); IAnInterface proxy = sut.CreateProxyFor(anImplementationOfTheInterfaceToProxy); proxy.OneMethod(); proxy.SecondMethod(); }

Which results in the following console output:

Interception occured on method OneMethod with SomeInterceptor
Real work is being done in OneMethod
Interception occured on method SecondMethod with SomeInterceptor
Real work is being done in SecondMethod

Notice that the interceptor was leveraged on both method calls prior to the call on the underlying item being made.

Scenario 2 : Intercept on all method invocations with multiple interceptors

[Test] public void Should_proxy_all_methods_with_multiple_interceptors() { IAnInterface anImplementationOfTheInterfaceToProxy = new SomeImplementation(); sut = new ProxyBuilder<IAnInterface>(); sut.AddInterceptor<SomeInterceptor>(); sut.AddInterceptor<SomeOtherInterceptor>(); IAnInterface proxy = sut.CreateProxyFor(anImplementationOfTheInterfaceToProxy); proxy.OneMethod(); proxy.SecondMethod(); }

Which produces the following console output:

Interception occured on method OneMethod with SomeInterceptor
Interception occured on method OneMethod with SomeOtherInterceptor
Real work is being done in OneMethod
Interception occured on method SecondMethod with SomeInterceptor
Interception occured on method SecondMethod with SomeOtherInterceptor
Real work is being done in SecondMethod 

In this scenario both of the individual interceptors were invoked on any method call to the proxied item. Ok, so that was easy, lets try the next one:

Scenario 3 : Intercept on specific method invocations with a Single interceptor:

 

[Test] public void Should_proxy_only_targeted_methods_with_a_single_interceptor() { sut = new ProxyBuilder<IAnInterface>(); anImplementation = new SomeImplementation(); IInterceptorConstraint<IAnInterface> constraint = sut.AddInterceptor<SomeInterceptor>(); constraint.InterceptOn.OneMethod(); IAnInterface proxy = sut.CreateProxyFor(anImplementation); proxy.OneMethod(); proxy.SecondMethod(); }

Which produces the following output:

Interception occured on method OneMethod with SomeInterceptor
Real work is being done in OneMethod
Real work is being done in SecondMethod 

Notice in the test above the use of the constraint that is returned from the Add method. Notice the call to the constraint.InterceptOn.OneMethod(). That is actually setting a filter to only enable the interceptor when that method is invoked on the proxy. For those familiar with Natural Mocks syntax (Rhino Mocks / TypeMock) this should look similar. It also has the nice benefit of not requiring the use of strings to specify which methods to filter on. Which means that it is also refactoring friendly. Notice that even though 2 method calls are made on the proxy, the interceptor only kicks in for the method that the constraint was configured for!!

Scenario 4 : Intercept on specific method invocations with differing interceptors:

[Test] public void Should_proxy_only_targeted_methods_with_differing_interceptors() { sut = new ProxyBuilder<IAnInterface>(); anImplementation = new SomeImplementation(); IInterceptorConstraint<IAnInterface> constraint1 = sut.AddInterceptor<SomeInterceptor>(); constraint1.InterceptOn.OneMethod(); IInterceptorConstraint<IAnInterface> constraint2 = sut.AddInterceptor<SomeOtherInterceptor>(); constraint2.InterceptOn.SecondMethod(); IAnInterface proxy = sut.CreateProxyFor(anImplementation); proxy.OneMethod(); proxy.SecondMethod(); }

Which results in the following console output:

Interception occured on method OneMethod with SomeInterceptor
Real work is being done in OneMethod
Interception occured on method SecondMethod with SomeOtherInterceptor
Real work is being done in SecondMethod 

Notice how in this example the interceptors are firing selectively for the methods that they were configured for.

Finally you can configure multiple method constraints at a time using the following syntax:

constraint.InterceptOnMethods( constraint.InterceptOn.FirstValueReturningMethod(), constraint.InterceptOn.ValueReturningMethodWithAnArgument(0));

Again, the syntax for this was heavily inspired by prolonged usage of Rhino Mocks. So let’s inspect the players that come together to make this all work:

 

public class ProxyBuilder<T> : IProxyBuilder<T> { private IProxyFactory proxyFactory; private IInterceptorConstraintSet constraintSet; public ProxyBuilder():this(new ProxyFactory(),new InterceptorConstraintSet()) { } public ProxyBuilder(IProxyFactory proxyFactory, IInterceptorConstraintSet constraintSet) { this.proxyFactory = proxyFactory; this.constraintSet = constraintSet; } public IInterceptorConstraint<T> AddInterceptor<Interceptor>() where Interceptor : IInterceptor,new() { constraintSet.AddConstraintFor<Interceptor,T>(); return constraintSet.GetConstraintFor<Interceptor,T>(); } public T CreateProxyFor<T>(T instance) { return proxyFactory.CreateProxyUsing<T>(instance, constraintSet); } }

This is entry point to the api used to create proxies and associate interceptors with them. Driving out the design in a test first manner really helped me push off responsibilities to the last possible moment. Which leaves the ProxyBuilder class fairly simple. It leverages both a ProxyFactory and an InterceptorContraintSet. The InterceptorConstraintSet is just a strongly typed collection of constraints with a little bit of smarts to it:

public class InterceptorConstraintSet : IInterceptorConstraintSet { private IDictionary<Type, object> constraints; private IInterceptorConstraintFactory constraintFactory; public InterceptorConstraintSet():this(new Dictionary<Type,object>(),new InterceptorConstraintFactory(new ProxyFactory())) { } public InterceptorConstraintSet(IDictionary<Type, object> constraints, IInterceptorConstraintFactory constraintFactory) { this.constraints = constraints; this.constraintFactory = constraintFactory; } public void AddConstraintFor<Interceptor, Target>() where Interceptor : IInterceptor, new() { if (constraints.ContainsKey(typeof(Interceptor))) return; constraints.Add(typeof (Interceptor), constraintFactory.CreateFor<Interceptor, Target>()); } public IInterceptorConstraint<Target> GetConstraintFor<Interceptor, Target>() where Interceptor : IInterceptor, new() { return (IInterceptorConstraint<Target>) constraints[typeof (Interceptor)]; } public IInterceptor[] AllInterceptors<Target>() { return SetOfAllInterceptorsFor<Target>().AsList().ToArray(); } private IEnumerable<IInterceptor> SetOfAllInterceptorsFor<Target>() { foreach (IInterceptorConstraint<Target> constraint in constraints.Values) { yield return constraint.BuildInterceptor(); } } }

The SetOfAllInterceptorsFor<Target> method is interesting as this is where the work to create the interceptors for a proxy is delegated to the constraint. The InterceptorConstraint and its accompanying collaborators is what allows for the natural syntax:

 

public class InterceptorConstraint<Target,Interceptor> : IInterceptorConstraint<Target> where Interceptor : IInterceptor,new() { private readonly IMethodCallTracker<Target> callTracker; public InterceptorConstraint(IMethodCallTracker<Target> callTracker) { this.callTracker = callTracker; } public Target InterceptOn { get { return callTracker.Target; } } public void InterceptOnMethods(params object[] makeMethodCallsUsingInterceptOnProperty) { } public void InterceptOnMethods(params Action[] makeMethodCallsToInterceptOnPropertyInsideOfActionDelegate) { foreach (Action action in makeMethodCallsToInterceptOnPropertyInsideOfActionDelegate) { action(); } } public IInterceptor BuildInterceptor() { if (callTracker.CallsWereMade) return new SelectiveInterceptor(new Interceptor(), callTracker.AllMethods()); return new Interceptor(); } }

The work of doing the interceptor filtering is done in the BuildInterceptor method. The InterceptorConstraint makes use of a MethodCallTracker which keeps track of whether calls were made to filter on selective methods. If the client is requesting a filtered interceptor the InterceptorConstraint returns an instance of a SelectiveInterceptor. SelectiveInterceptor is a proxy for an Interceptor (I know that is a mouthful!!):

public class SelectiveInterceptor : IInterceptor { private IInterceptor interceptor; private IDictionary<string,string> methodsToInterceptOn; public SelectiveInterceptor(IInterceptor interceptor, IDictionary<string, string> methodsToInterceptOn) { this.interceptor = interceptor; this.methodsToInterceptOn = methodsToInterceptOn; } public void Intercept(IInvocation invocation) { if (methodsToInterceptOn.ContainsKey(invocation.Method.Name)) { interceptor.Intercept(invocation); return; } invocation.Proceed(); } }

Selective interceptor decides whether or not to forward the call onto the associated interceptor, if the method is not in the dictionary of methods to intercept on, it bypasses the interceptor and directly forwards the call onto the item to proxy.

Notice the user of : new Interceptor();

This creates a new instance of whatever the interceptor type was that was specified by the AddInterceptor<Interceptor> method call back on ProxyBuilder. This works because of the generic constraint that ensured that the IInterceptor implementation also had a public no-arg constructor.

Last but not least, you are probably curious as to how the natural syntax is enabled? Take a look at the MethodCallTrackerFactory class:

public class MethodCallTrackerFactory : IMethodCallTrackerFactory { private ProxyGenerator proxyGenerator; public MethodCallTrackerFactory(ProxyGenerator proxyGenerator) { this.proxyGenerator = proxyGenerator; } public IMethodCallTracker<T> CreateFor<T>() { MethodCallTracker<T> methodCallTracker = new MethodCallTracker<T>(); T target = proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(methodCallTracker); methodCallTracker.Target = target; return methodCallTracker; } }

The ProxyGenerator class is supplied by Castle.DynamicProxy. I am using it to create a proxy around an interface without an actual underlying target:

T target = proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(methodCallTracker);

Notice how after the MethodCallTracker is instantiated, it is passed in as an argument to the CreateInterfaceProxyWithoutTarget method? This method takes either a single or variable array of IInterceptor implementations. That’s right. The MethodCallTracker is itself as IInterceptor implementation. It intercepts calls on its Target property so that it can store the calls to be used in the Interception filtering process:

public class MethodCallTracker<T> : IMethodCallTracker<T> { public T Target{get;set;} private IDictionary<string, string> methodNames; public MethodCallTracker() : this(new Dictionary<string, string>()) { } public MethodCallTracker(IDictionary<string, string> methodNames) { this.methodNames = methodNames; } public void Intercept(IInvocation invocation) { SetReturnValueFor(invocation); if (methodNames.ContainsKey(invocation.Method.Name)) return; methodNames.Add(invocation.Method.Name, invocation.Method.Name); } private void SetReturnValueFor(IInvocation invocation) { Type returnType = invocation.Method.ReturnType; if (returnType == typeof(void)) return; invocation.ReturnValue = (returnType.IsValueType ? Activator.CreateInstance(returnType) : null); } public bool CallsWereMade { get { return methodNames.Count > 0; } } public IDictionary<string, string> AllMethods() { return methodNames.Copy(); } }

And finally, the glue that ties it all together. ProxyFactory, this class actually creates proxies instances leveraging the Castle ProxyGenerator as well as the completed InterceptorConstraintSet:

 

public class ProxyFactory : IProxyFactory { private ProxyGenerator proxyGenerator; private IMethodCallTrackerFactory methodCallTrackerFactory; public ProxyFactory():this(new ProxyGenerator(),new MethodCallTrackerFactory(new ProxyGenerator())) { } public ProxyFactory(ProxyGenerator proxyGenerator, IMethodCallTrackerFactory methodCallTrackerFactory) { this.proxyGenerator = proxyGenerator; this.methodCallTrackerFactory = methodCallTrackerFactory; } public IMethodCallTracker<T> CreateMethodCallTracker<T>() { return methodCallTrackerFactory.CreateFor<T>(); } public T CreateProxyUsing<T>(T instance, IInterceptorConstraintSet constraints) { return proxyGenerator.CreateInterfaceProxyWithTarget<T>(instance, constraints.AllInterceptors<T>()); } }

People ask me why I love TDD? It’s because you can start with a blank slate, drive out the components one at a time in isolation from another, isolating/deferring responsibilities as you go, and finally you can plug all of the pieces together. In all of the code samples above I added in the poor mans dependency injection so that people could see the concretes being injected into the dependent. In the actual source code, an IOC container is being used. As when driving out the solution the interfaces were used to defer responsiblity to another object that did not exist yet. Taking this code, it would not be hard to add the pre/post/both filter also so that you could choose when specifically to apply an interceptor!! And of course I could eliminate the method call tracker altogether if I made use of lambda expressions and parsed the expression tree to see what method was called. I’ll leave that for another day!!

Develop With Passion!!

Comments [3] | | # 
 Tuesday, January 29, 2008
Tuesday, January 29, 2008 5:40:24 PM (Mountain Standard Time, UTC-07:00) ( Agile | C Sharp | Training )

After lots of requests, Nothin But .Net is finally coming to Austin,Texas!! I am sure that seats are going to sell out fast, so hurry and register here if you want a spot in what will surely be an amazing week of crazy coding!!

Overview

Nothin But .Net is a five day (intense) boot camp style course that will focus on applying .Net development best practices in the context of developing a working N-Tiered application. Registrants will learn about how to practically apply.Net as they apply it to the task of building a complete application from the UI layer all the way down to the mapping layer.

 

WARNING!!!!

If you are expecting to come to this course to learn about how to have VS.Net automatically generate an “application” for you, then this course is NOT for you.

This course is all about taking control of the .Net framework and having it work the way you want. This course will place a heavy emphasis on getting back to the basics and making .Net do things the way you want it to, in a predictable and testable way.

During the course of the week, there will be absolutely no code that gets compiled from within Visual Studio. Studio itself will be relegated to a glorified code editor. I will teach you development techniques and tools that will dramatically increase your day to day productivity as a software developer.

This course will focus on a code centric view of application development vs. the typical databinding/designer magic covered by many typical .Net courses. You will walk away with a deep understanding of fundamental aspects of .Net and how these pieces can be used to develop and deliver enterprise scale applications.

Core Concepts Overview

*        Expand the capabilities of developing with VS.Net - Enter ReSharper (a productivity add-in for Visual Studio .Net)

*        There’s more to development than code generators

*        Automated Builds       

*        Generics ( they’re not just for collections )

*        Object Relational Mapping in .Net

*        Creating layered architectures

*        Driving out functionality and design through testing

*        Taking Control Of Databinding

*        Test Driven Development & Mock Objects

*        Core Design Patterns Applied

 

Detailed Topic Coverage Breakdown

·          Language Enhancements

o    Generics

o    Anonymous Delegates

o    Iterators

o    Linq

·          Collections

o    Taking advantage of the collection interfaces

o    Making use of the IDictionary<T> and IList<T> interfaces.

o    Overcoming the limitations of the IList<T> interface

o    Sorting, searching, and manipulating collections using generic delegates

o    Overcoming limitations of searching with generic delegates

o    Creating custom comparers

·          Events

o    Delegates in depth

o    Creating classes that expose events

o    Safely publishing events

o    Multithreading with delegates

·          ADO .Net

o    Creating a Custom Object Relational mapping layer

o    Effective uses of TransactionScope to test the mapping layer

o    Eliminating the need for stored procedures

o    Effective techniques for querying data

·          ASP.Net

o    Master Pages

o    Passing Data Between Pages

o    Taking Control Of Databinding

o    Validation Techniques

o    Leveraging Front Controller Architecture styles for cleaner separation of concerns.

o    Saying goodbye to WebForms

o    MVC vs MVP vs SC

·          OO Practices & Principles

o    Dependency Inversion

o    Single Responsibility

o    Open Closed

o    Hollywood

o    Tell Don’t Ask

o    Encapsulation

o    Polymorphism

·          Patterns

o    Layered Architecture

o    Data Transfer Object

o    Supervising Controller

o    Passive View

o    Notification

o    Static Gateway

o    Unit Of Work

o    Mapper

o    Gateway

o    Domain Model

o    Null Object

o    Proxy

o    Adapter

o    Abstract Factory

o    Event Aggreagor

o    Service Layer

o    Façade

o    Visitor

o    Decorator

o    Composite

o    Front Controller

o    Notification

·          Testing

o    Using Automated Testing Frameworks

o    Dependency Based/Interaction Based

o    TDD as a design tool

o    Applied Test Driven Development

o    Avoiding over specification problems with Interaction Based Testing

o    Test Partitioning

o    Different types of testing (Integration,Acceptance,Unit)


Recommended Prerequisites

This is an intermediate to expert level course. In order to walk away with the most benefit from the course the following list outlines key prerequisites and the level of knowledge that people would be best served entering the course with:

 

*        Knowledge of the C# syntax (Strong)

*        Knowledge of the .Net event/delegate architecture (Moderate/Strong)

*        OO programming concepts (Moderate/Strong)

*        Domain Driven Design (Cursory)

*        Refactoring (Cursory)

*        Design Patterns (Cursory)

*        Automated Testing Frameworks (Cursory/Moderate)

*        Test Driven Development (Cursory)

*        Utilizing Events and Delegates in .Net (Moderate/Strong)

*        Manipulation of core ADO.Net objects (Moderate/Strong)

*        Build Automation (Cursory)

 

**********Please be aware that the length of course days (based on prior iterations of the course) can fluctuate dramatically based on the level of student interaction. It is best to come ready expecting the course days to be no less than 10 hours.************

 

Intended Outcomes

Upon completion of this course students should be equipped with a practical, applied understanding of the following concepts:

 

*        Interface Based Programming

*        Design By Contract

*        Test Driven Development

*        Layered architecture

*        Object Oriented Programming

*        Design Patterns

*        Unit Testing

*        Interaction vs. State Based Testing

*        Dependency Injection

*        Object Relational Mapping

*        Domain Driven Design

*        Build Automation

People are required to bring their own laptops capable of running:

  • Windows XP w/SP2 & IIS 5.0
  • SQL Server 2005 Developer Edition
  • Visual Studio 2008 Professional Edition
  • TortoiseSVN
  • ReSharper 3.x / 4.0

WARNING……………This is a very intense week. Your mind will not have very much in the way of downtime. Days in past courses have gone anywhere from 10 – 20 hours in length!!

One side goal of the course is to leave people feeling a lot more empowered and energized to do their jobs!! Develop with passion is not just my tagline, it is something that I personally believe in!!

If you are interested then sign up here.

Comments [2] | | # 
 Thursday, January 17, 2008
Thursday, January 17, 2008 3:25:11 PM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I’ll blog about the details of what I’m working on at a later date (if I can disclose). Needless to say. Make sure you use the TestFixture attribute as follows:

[TestFixture(ApartmentState = ApartmentState.STA)]

public class When_the_tree_item_is_expanded

{

}

This ensures that all of the tests in the fixture will run in a Single Threaded Apartment. And no putting the STAThread attribute on top of the test method won’t do it!!

 

Develop with passion!!

Comments [6] | | # 
 Wednesday, December 19, 2007
Wednesday, December 19, 2007 10:26:48 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

Got some feedback on my MappingEnumerable post. People wanted to see me leveraging some of the new language features (specifically linq).

I can leverage linq to change the extension method to eliminate the need for the MappingEnumerable (which was brought in to mitigate the absence of extension methods) and replace it with the following code: 

public static IEnumerable<Output> MapAllUsing<Input,Output>(this IEnumerable<Input> items,IMapper<Input,Output> mapper) { return from item in items select mapper.MapFrom(item); }

K. Scott Allen had the suggestion to use property initializers:  

IEnumerable<Department> departments = departmentRepository.GetAllDepartments(); return from d in departments select new DepartmentDisplayItemDTO() { ID = d.ID, Name = d.Name };

Which you can definitely do if you so wish, that specific dto is completely immutable so the above would not work, but could be changed to accommodate.

It is important to note that the IMapper<Input,Output> interface is an interface that can be implemented to perform all sorts of mapping. Some examples of how I have used this in the past are:

  • Mapping from DB to Domain
  • Mapping from Domain to DTO
  • Mapping from Errors to ScreenElements
  • Mapping from DTO to Presentation Model
  • ….

You are only limited by your imagination. And because each mapper has a single MapFrom method, it is very easy to test specific implementations of the interface, you can even create a non generic IMapper interface that you can use for completely reflective scenarios (picture externally defined OO mapping).

K. Scott Allen also mentions DTO Tax, and I don’t think his point is specific to just DTO’s but the cost of mapping in general. Focusing on 1 mapping at a time, refactoring out the duplication and moving on; is a way that you can grow and add all sorts of mapping in a very organic way to your applications.

Develop With Passion!!

Comments [3] | | # 
Wednesday, December 19, 2007 1:44:14 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

With a newfound interest in leveraging the AutoMockingContainer (credit to James for convincing me of this approach) here is the code for my base class used to write BDD style interaction based tests:

public abstract class Specification { private MockRepository mockery; private AutoMockingContainer container; protected MockRepository Mocks { get { return mockery; } } protected AutoMockingContainer Container { get { return container; } } [SetUp] public void BaseSetup() { mockery = new MockRepository(); container = new AutoMockingContainer(mockery); container.Initialize(); Before_each_spec(); } [TearDown] public void TearDown() { After_Each_Spec(); } protected virtual void After_Each_Spec() { } public IDisposable PlayBackOnly { get { using (Record) { } return PlayBack; } } public void BackToRecord(object mockObject) { Mocks.BackToRecord(mockObject); } public IDisposable Record { get { return Mocks.Record(); } } public IDisposable PlayBack { get { return Mocks.Playback(); } } public abstract void Before_each_spec(); public Item CreateSUT<Item>() { return container.Create<Item>(); } public Interface CreateStrictMockOf<Interface>() { return mockery.CreateMock<Interface>(); } public IEnumerable<T> CreateMockEnumerable<T>() { return CreateMock<IEnumerable<T>>(); } public T Mock<T>() where T : class { return container.Get<T>(); } public void ProvideAnImplementationOf<Interface, Implementation>() { container.AddComponent(typeof (Implementation).FullName, typeof (Interface), typeof (Implementation)); } public void ProvideAnImplementationOf<Interface>(object instance) { container.Kernel.AddComponentInstance(instance.GetType().FullName, typeof (Interface), instance); } protected Interface CreateMock<Interface>() { return Mocks.DynamicMock<Interface>(); } }

I changed some of my original method names to match up with what Dave was doing (for a bit of consistency).Here is an example of a testfixture that leverages this as the base (this test happens to use an explicit CreateSUT method, vs the one provided by the AutoMockingContainer):

 

[TestFixture] public class When_told_to_visit_all_items : Specification { private IVisitor<int> visitor; private RichList<int> numbers; private IEnumerableActions<int> sut; private IEnumerableActions<int> CreateSUT() { return new EnumerableActions<int>(numbers); } public override void Before_each_spec() { numbers = new RichList<int>(); numbers.Add(1); numbers.Add(2); sut = CreateSUT(); visitor = CreateMock<IVisitor<int>>(); } [Test] public void Should_tell_visitor_to_visit_all_items_in_the_enumerable() { using (Record) { foreach (int i in numbers) { visitor.Visit(i); } } using (PlayBack) { sut.VisitAllItemsUsing(visitor); } } }

Develop With Passion!

Comments [1] | | # 
Wednesday, December 19, 2007 1:22:00 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

I just upgraded the project to a VS2008 project and am now starting to demonstrate (and will continue to do so in the new year) how to integrate some of the new language features.

This means that if you don’t have .Net 3.5 installed on your machine you will not longer be able to run the NAnt build. Furthermore, if you do not have VS2008 on your machine you will not be able to open the solution.

Sorry!!

 

Develop with Passion!!

Comments [6] | | # 
Wednesday, December 19, 2007 11:03:44 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

In my infrastructure layer of my projects I regularly include the following interface:

public interface IMapper<Input, Output> { Output MapFrom(Input input); }

This interface should be fairly self-explanatory, it takes in an item of type Input and spits out an item of type Output. For those who care about details (and I do) it is also good to note that this interface matches the signature for a Converter generic delegate.

One of the (many) places that I use implementations of this interface is in the service layer to marshal data back up to the higher level layers as DTOS. Here is an example of a simple Mapper:

public class DepartmentDisplayItemDTOMapper : IDepartmentDisplayItemDTOMapper { public DepartmentDisplayItemDO MapFrom(IDepartment department) { return new DepartmentDisplayItemDO
(department.Name, department.Id); } }

One of the ways that I would have leveraged this in the past would have been to inject the service layer component with the appropriate mapper and then map items that were returned from the repository in place.

Here is another alternative that takes advantage of a type I am calling a MappingEnumerable<T>. Take a look at the code for the class:

public class MappingEnumerable<Input, Output> : IMappingEnumerable<Input, Output> { private IMapper<Input, Output> mapper; private IEnumerable<Input> inputItems; public MappingEnumerable(IMapper<Input, Output> mapper, IEnumerable<Input> inputItems) { this.mapper = mapper; this.inputItems = inputItems; } IEnumerator<Output> IEnumerable<Output>.GetEnumerator() { return MapAllFrom(inputItems).GetEnumerator(); } public IEnumerator GetEnumerator() { return ((IEnumerable<Output>) this).GetEnumerator(); } private IEnumerable<Output> MapAllFrom(IEnumerable<Input> input) { foreach (Input item in input) { yield return mapper.MapFrom(item); } } }

Using this class from the service layer is as simple as:

 

public IEnumerable<DepartmentDisplayItemDO> GetAllSubdepartmentsOf(long departmentId) { IDepartment parentDepartment = departmentRepository.FindBy(departmentId); IEnumerable<IDepartment> subdepartments = departmentRepository.AllSubDepartmentsOf(parentDepartment); return new MappingEnumerable<IDepartment, DepartmentDisplayItemDO> (subdepartments, departmentDisplayItemDTOMapper); }

Notice that the MappingEnumerable decorates the existing enumerable with mapping behaviour. Because the MappingEnumerable is itself an implementation of an IEnumerable<T> interface, the mapping of each item will not start until the iteration of the enumerable happens.

Taking this class and applying it in the 3.5 world (I prefer using components vs free floating extension methods) can result in the following:

IDepartment parentDepartment = departmentRepository.FindBy(departmentId); IEnumerable<IDepartment> subdepartments = departmentRepository.AllSubDepartmentsOf(parentDepartment); return subdepartments.MapAllUsing(departmentDisplayItemDTOMapper);

Where MapAllUsing is an extension method on IEnumerable which lives in my infrastructure layer. The simplified implementation of MapAllUsing just delegates the work to the MappingEnumerable class: 

public static IEnumerable<Output> MapAllUsing<T,Output>(this IEnumerable<T> itemsToMap,IMapper<T,Output> mapper) { return new MappingEnumerable<T, Output>
(mapper,itemsToMap); }

One more short example to show how I leverage this pattern in my apps take a look at this method on a DatabaseGateway interface:

IEnumerable<DataRow> GetASetOfRowsUsingA(IQuery query);

A simple method to return an enumerable of DataRows. You can now leverage this to do things like:

public IEnumerable<DomainObject> GetAllUsing(IQuery query) { return gateway.GetASetOfRowsUsingA(query).MapAllUsing(dbMapper); }

Where the mapper in this case knows how to hydrate datarows into domain objects of the specific (DomainObject) type the mapper is defined for.

One of the things I tell people in class (and work) is that IEnumerable is the ultimate Separated Interface and this post just scratches the surface of the things you can do by just getting creative with the IEnumerable interface.

Develop With Passion!!

Comments [2] | | # 
 Wednesday, November 28, 2007
Wednesday, November 28, 2007 11:59:42 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Agile | C Sharp | Programming )

Having received a bunch of emails in the past couple of weeks from people who have been asking me questions with regards to Passive View/Supervising controller patterns for web applications. I needed to let people know that for the last couple of months I have been developing web apps in a completely MVC style which eliminates the need for patterns like Passive View/ Supervising Controller.

For the people who are using the MVP pattern in their (web) applications I personally would now lean to the Supervising Controller style as it eliminates a lot of necessary chattiness between the view and the presenter. It also lends itself to much more simple unit tests.

Having gotten back into the Smart Client realm, I am once again reminded of the importance of patterns like Supervising Controller and presentation model as becoming essential to ensuring correct separation of responsibilities.

For my web applications, however, all I use now is a:

  • Front Controller
  • Commands
  • View Templates (ASPX style!!)

Here is an example of what I mean, for the nothinbutdotnetstore.web.app project that is currently hosted on google code, here is the Command that processes getting a list of the main departments in the store for viewing:

 

using NothinButDotNetStore.Infrastructure; using NothinButDotNetStore.Infrastructure.Container.Common; using NothinButDotNetStore.Tasks; using NothinButDotNetStore.Web.FrontController; namespace NothinButDotNetStore.Web.DepartmentBrowser { public class ViewMainDepartments : ICommand { private ICatalog catalog; private IRequestContext requestContext; private IViewEngine viewEngine; public ViewMainDepartments(IHttpContext context) : this(context, DependencyResolver.GetImplementationOf<IRequestContextFactory>().CreateFrom(context), DependencyResolver.GetImplementationOf<IViewEngine>(), DependencyResolver.GetImplementationOf<ICatalog>()) { } public ViewMainDepartments(IHttpContext context, IRequestContext requestContext, IViewEngine viewEngine, ICatalog catalog) { this.catalog = catalog; this.viewEngine = viewEngine; this.requestContext = requestContext; } public void Execute() { requestContext.AddToStateBag(ViewBagItem.Departments, catalog.GetMainDepartments()); viewEngine.Display(Views.ViewDepartments); } } }
 
Here is the complete ASPX (View Template) that gets rendered for that command executing:
 
 
<%@ MasterType VirtualPath="~/Store.master" %> <%@ Page Language="C#" AutoEventWireup="true" Inherits="System.Web.UI.Page" MasterPageFile="~/Store.master" %> <%@ Import namespace="NothinButDotNetStore.Web.FrontController"%> <%@ Import namespace="NothinButDotNetStore.Web"%> <%@ Import namespace="NothinButDotNetStore.Infrastructure"%> <%@ Import namespace="NothinButDotNetStore.DTO"%> <asp:Content ID="content" runat="server" ContentPlaceHolderID="childContentPlaceHolder"> <p class="ListHead">Select An Isle</p> <table> <% int rowIndex = 0; %> <% foreach (DepartmentDisplayItem dto in ViewBag.GetItem(ViewBagItem.Departments)) { %> <tr class='<%=(rowIndex++ %2 ==0 ? "nonShadedRow" : "shadedRow" ) %>'> <td> <a href='<%= Url.ToBeProcessedBy(CommandNames.ViewSubDepartments) .AddPayloadValue(PayloadKeys.DepartmentId,dto.Id).Build() %>'> <%=dto.DepartmentName %> </a> </td> </tr> <% } %> </table> </asp:Content>

There is no code behind for this aspx page. The logic in the aspx file is there because it is rendering related logic. This aspx page does not talk to a service layer or domain objects or even a data access layer. It reaches into a ViewBag looking for information that it can render, and then it proceeds to do exactly what it should, render the information. What may not be immediately obvious is that this is a plain aspx file with no codebehind file. The page inherits from System.Web.UI.Page.

As far as testability of this style of development, here is a sample test for one behaviour of the ViewMainDepartments command:

[RunInUnitTestContainer] [Test] public void Should_populate_the_context_with_the_departments_to_display() { ICommand sut = CreateSUT<ViewMainDepartments>(); IEnumerable<DepartmentDisplayItem> results = CreateMock<IEnumerable<DepartmentDisplayItem>>(); using (Mocks.Record()) { Expect.Call(mockCatalog.GetMainDepartments()).Return(results); mockRequestContext.AddToStateBag(ViewBagItem.Departments, results); } using (Mocks.Playback()) { sut.Execute(); } }
 
 
 

In the next little while I am going to shed some more light on this approach to web application development. IMHO, the separation of concerns for web applications written in this style is much greater than when trying to stuff in a pattern that (again IMHO) did not fit well for the technology, and was leveraged for the sake of increased testability.

Comments [2] | | # 
Wednesday, November 28, 2007 11:01:52 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Continuous Integration | Patterns | Programming | Tools )

I finally set up a googlecode project to host source code for the various things I have been doing over the last year. The first major significant contribution is of course the code drop that I promised a week ago now!!

The application is the start of what I hope will evolve to be a great learning resource for lots of things related to .Net development. The application does not currently cover any of the “extra” topics that I did not have time to get covered in the course. This is perfect because as request come in from people (including past students) asking how to tackle a certain problem, I will use this application as the demonstration area where I can tackle the problem, and update the code base, and you will be able to update your local copy and carry on.

I am currently in the midst of a large Smart Client application that I am hoping to be able to harvest pieces of code out and do the exact same thing except for the smart client realm. I have much more experience developing in the smart client realm and that is where I feel most comfortable, so I am looking forward to be able to do another code drop (for a different application) in a couple of months.

I am going to write up another post about the Web Application as it is built very differently from traditional .Net based web applications. In following with the theme for my courses, there are currently no 3rd party frameworks (other than log4net) that have come into play. My goal with this web app is to demonstrate to people how far we can push raw .Net. The goal being that expanding their knowledge of how to creatively leverage .Net, they will be better prepared to jump into frameworks that they may currently feel daunted by. As time goes by, I will swap pieces of the application out with components that people are asking to see meaningful samples on:

  • NHibernate
  • Castle
  • Prototype
  • JQuery
  • ..*

As the app stands right now I see it as the beginning of what will shape up to be a pretty mean machine!!

I am going to post a screencast that will show people how to get started working with the web application. For people who are eager to get going right now, here are the quick and simple steps without a lot of explanation (that will come in the next post):

  • Anonymously checkout the trunk from the google code repository using the following svn command line:
    svn checkout http://jpboodhoo.googlecode.com/svn/trunk/ jpboodhoo-read-only
  • Navigate to the checkout folder
  • Go into the build folder
  • Copy local.properties.xml.template and paste it into the same directory, then rename the copied file to local.properties.xml
  • Open up the local.properties.xml file with your favourite text editor.
  • Modify any of the settings in the file that are different on your machine.
  • Open up a command prompt and navigate to the build directory of the code.
  • type: build load.data and hit enter.
  • type: build test.all.woc
  • type: build run
  • The last task should fail (I haven’t automated everything yet)
  • Create a virtual directory called nothinbutdotnetstore that points at the following location (this location is created after you attempt to run the build run task) : ${checkoutfolder)\build\deploy\web\app
  • After successfully creating the virtual directory try the build run task again.
  • If the web browser pops up pointed at a web page (for the app) you are in business. Feel free to click through the first set of pages that are implemented (only 3 pages are currently implemented).

As far as what I have planned to implement in the web app (that is currently not implemented):

  • Build out a more extensive domain model that encompasses some more advanced scenarios of the application (especially around order processing).
  • Unit Of Work for the service layer
  • Implement a lightweight OR/M layer
  • Integrate some UI frameworks like prototype
  • Eliminate Master Pages completely and switch to a much more elegant template view pattern.
  • Introduce a more robust container (as the current one is a simple dictionary wired up in a simple procedural fashion).
  • Introduce the concepts of lifecycles for the items in the container. Right now, everything wired into the container is essentially a singleton.
  • Introduce CSS based layout for the web pages (working with a designer on this one).
  • Bring security concerns into play
  • Demonstrate how to effectively manage sessions
  • ……lots,lots,lots more!!!

Obviously I will be leaning on people checking out the code and playing around with it and submitting requests for things they would like to see.

There are a couple of things that you will immediately notice about the application:

  • Clean front controller implementation with ASPX pages as the template views. There are no code behind pages in this web application. All web requests are handled by command objects that interact with the service layer, push the details into a “ViewBag” and then choose which view to render.
  • Logical layers in the project are separated using simple folders and namespaces (not full blown projects)
  • Build automation is its own project in the solution (props to Jay Flowers for this inspiration)
  • The current container implements (CustomDependencyContainer) is very simple and is handled by a big procedural application startup task.
  • Compile time support for the database layer. A couple of classes ago I introduced the concept of a generic TableColumn<T> type. In England after introducing this concept Scott Cowan leveraged his knowledge of MyGeneration to automatically generate strongly typed table definitions that we could leverage to do mapping (trust me when I say, this is nothing like datasets). Until moving into OR/M concepts deeper this gives a good place to start as the generation of the TableDefinitions is linked to whenever the SQL files change, so you will get compile errors if column types are now mismatched etc…

There are lots of other things I could talk about, but this code really is the start of what I see being a long running conversation between myself and other people wanting to learn. In all honesty for all of the emails I have not paid attention to this year, hosting code through google will allow me to answer peoples questions in a much more meaningful way as I can point them at this site to see the implementation of the code they had questions about.

I am going to be placing all of the code for presentations that I have done for the last year as well as continue to update it with the source code that comes out of new courses that will be coming out in the new year, and the DNRTv episodes.

Once again, the application is currently in its infancy, but as people start sending in the requests I now will have a venue and example to add upon to answer questions in a much more timely fashion!!!

 

Develop With Passion!!!

 

 

Comments [15] | | # 
 Tuesday, November 13, 2007
Tuesday, November 13, 2007 1:55:06 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | C Sharp | General | Tools )

Since I have been asked for these quite a few times, I thought I would oblige and give these out. You can find below the links for both my Resharper Live Templates and File templates.

Enjoy:

Comments [1] | | # 
 Sunday, November 11, 2007
Sunday, November 11, 2007 5:48:00 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Programming | Training )

A lot of people will probably say it is about time!! I am taking the source code that just got driven out from this last week of Nothin But .Net and I am going to make it publicly available from my blog. I am hoping to release it by the end of the week. The reason that I can’t release it yet, is that there are lots of concepts that I wanted to cover in class that I did not have time too, so I am going to spend a bit of time fleshing out the code base to include all of the concepts that were missed (by student request)

Keep in mind that Nothin But .Net is a course about fundamental software development practices with a bit of a .Net slant. Here are some of the things you will be able to see in the code base:

  • How Test Driven Development was used to drive out the functionality of screens in the application in a top down fashion
  • The benefit of using Data Transfer objects not as a marshaling tool, but as a tool to let the needs of the UI not influence unecessary changes to the domain model
  • The benefits of leveraging layered architecture
  • Why you don’t need lots of projects in your enterprise solutions if you are using an automated build (take  a look at the following screenshot to get an idea for the solution structure
  • Clean Front Controller implementation so that you can eliminate the need for messy Passive View/Supervising Controller implementations just for testability of the web form world
  • Good practices around mixing both interaction and state based testing
  • Test partitioning (integration, unit, acceptance)
  • My current project build structure
  • How to avoid the overspecification problem with interaction based testing
  • Rhino Mocks and leveraging the automocking container (thanks James for getting me hooked on this thing)
  • Fluent Interfaces
  • Build Automation
    • NAnt compilation as an effective tool for pruning dead code that studio does not show
    • NAnt as a build tool
    • NAnt as your compiler and test runner
    • Build file partitioning
      • Use of filesets
    • Machine agnostic build files through use of local property files
  • Unit Testing
    • Focusing on one thing at a time
    • Incremental testing
    • Breaking reliance on setup methods
  • MBUnit
    • Decorators used effectively
  • Design Patterns
    • Visitor
    • Factory
    • Data Transfer Object
    • Adapter
    • Proxy
    • Mapper
    • Unit Of Work (lots of people have been bugging me about this for a while)
    • Lazy Loading
    • IOC
    • Gateway (and Static Gateway)
    • Service Layer
    • Identity Map
    • Data Mapper
    • Database Gateway
    • Money
    • Null Object
    • Strategy
    • Composite
    • Command
    • Template View
    • Query Object
    • Specification
    • Domain Model
    • Separated Interface
  • Design Principles
    • Single Responsibility
    • Open Closed principle
    • Dependency Inversion Principle
    • Hollywood principle
    • Tell Don’t Ask

I am sure I am missing lots in the description above, but you get the general idea. The important thing to note, is that all of the code (except for the changes I am making this week) was driven out through the course of the one week bootcamp!!

I am going to spend a couple of days ensuring that it contains as much code as possible for an initial drop, with full end to end functionality in place.

Going forward, this code will serve as a good place for me to be able to demonstrate in a public arena, concepts that people email me and ask me questions about. This way, I won’t have to spend as much time blogging, people can send me a question about something they are having problems with, I can implement the solution in the codebase and they can see how I attacked the problem from a test first perspective.

I envision this as being a very organic application. I am going to use it as a public tool to share whatever knowledge I have with as many people as possible.

When I post the code I will make sure I post a little about the application and why I feel that it will serve as a good tool to both teach and practice.

Comments [11] | | # 
 Tuesday, August 14, 2007
Tuesday, August 14, 2007 9:30:50 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Presentations )

Yesterday I had the wonderful opportunity to present a talk on Generics to the Austin .Net user group. The session was a whirlwind of code and questions. I was honored to be received by such a large group of people. And I would like to thank Jeff and the Austin .Net user group for allowing me to give my first formal talk in the United States!! Seeing as how I am going to be giving several talks in the states this year, it was fitting that the first one would leave me with such a positive feeling.

I made a mistake and did not check in the code that I developed over the course of the presentation, so the code base that you can download is not representative of all of the information  that was covered over the 2 hour session.

Once again, thanks Austin .Net for allowing me to opportunity to come and share an awesome time with you.

Materials:

Comments [7] | | # 
 Monday, July 16, 2007
Monday, July 16, 2007 4:56:36 PM (Mountain Standard Time, UTC-07:00) ( Agile | C Sharp | Training )

This year has been an awesome year for allowing me to venture into the training arena. Although I am not a full time trainer (nor do I ever intend to be), I have greatly enjoyed taking a week out of my schedule once a month this year to deliver top tier Agile development training to students all over the US and Canada. For the remainder of the year I will be blessed with the ability to take the course offerings globally with my first course in England scheduled for September.

My focus this year has been on delivering – Nothin But .Net. An intense 5 day course that stretches people to think outside the box of how they typically program and delve into realms they have potentially not event thought about yet:

  • Behavior Driven Development
  • Applied Object Oriented Programming
  • Incremental Design
  • ……

I have greatly enjoyed delivering this course, but feel that it is time to throw some other course options into the fray. With that in mind, here are “some” of the courses that people will be able to request (on demand) for the 2008 calendar year:

  • Nothin But Agile Project Management***
  • Nothin But Virtual Wizardry***
  • Nothin But Build Automation
  • Nothin But An Introduction To Unit Testing
  • Nothin But Test Driven Development
  • Nothin But Domain Driven Design
  • Nothin But Windows Presentation Foundation
  • Nothin But Windows Communication Foundation
  • Nothin But De-mystifying Design Patterns
  • Nothin But Developing With Open Source Frameworks (NHibernate,Monorail,Windsor ….)

It should be noted that not all of these courses are 5 day bootcamps.

This is just a small sample of the offerings, and if your company is in need of training that is focused around a particular application that you are going to be (or are currently) building, all of the courses are completely dynamic and able to adapt very quickly to the needs of the students. I am about a week away from finishing my full blown web site where information on each of the courses will be explained in detail, and where you will also be able to request course offerings that you would like to see.

I am going to be collaborating with people over the next year to offer up a wide group of trainers who all exhibit the values and skills that I would expect of someone able to teach a Nothin But * course. Know that when you engage in one of these courses that your minds will be pushed to the limit for the entire duration of the course.

Being first and foremost a developer, I am still going to be only committed to teaching a course a month so that I can continue to “sharpen the sword” during the remaining weeks of the month. Leveraging collaborators will allow more people to get exposure to what I feel is pivotal training that can completely change your development career, it will also allow more courses to be offered over the course of the year than what I could offer on my own.

Spread the word, Nothin But * is coming your way!!

 

***I am fairly excited about these courses as there is a huge need for some de-mystifying around these areas.

Comments [7] | | # 
 Wednesday, July 11, 2007
Wednesday, July 11, 2007 7:29:16 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | C Sharp )

If you are now coding in .Net 2.0/3.0/3.5 and are creating types that expose events. Chances are you have started leveraging the EventHandler<T> delegate that frees you from creating custom delegate signatures for events anymore. If not this post is for you. Let’s say that you want to expose an event that another object could consume. Normally you would follow these steps:

  1. Create a type that inherits from EventArgs if the event is going to propagate event specific data. This step is optional as you may not have any custom data to propagate.
  2. Create a delegate signature for the event. If you are not using a custom EventArgs derivative, then you can get away with just leveraging the EventHandler delegate that already exists in the framework.
  3. Create the type that is going to raise the event and have it declare the event using either implicit or explicit event registration.
  4. Create a method on the type that will raise the event.

In .Net 2.0/3.0/3.5 these steps can now become:

  1. Create a type that inherits from EventArgs if the event is going to propagate event specific data. This step is optional as you may not have any custom data to propagate.
  2. Create the type that is going to raise the event and have it declare the event using either the EventHandler delegate type for an event that does not propagate custom data, or leverage the generic EventHandler<T> delegate to declare an event bound to the specific EventArgs derivative you need to use. Again you can use either implicit or explicit event registration.
  3. Create a method on the type that will raise the event.

This can actually become slightly better. Instead of always creating a class that derives from EventArgs if you need to pass custom data; create a parameter object that encapsulates the information you would want to propagate in the event. This class does not need to inherit from EventArgs. Then create the following utility class:

 

public class EventArgs<T> : EventArgs { private T eventData; public EventArgs(T eventData) { this.eventData = eventData; } public T EventData { get { return eventData; } } }

This means that the 3 steps above can now be changed to:

  1. Create a parameter object that encapsulates any information you want to propagate in the event.. This step is optional as you may not have any custom data to propagate.
  2. Create the type that is going to raise the event and have it declare the event using either the EventHandler delegate type for an event that does not propagate custom data, or leverage the generic EventHandler<T> delegate, with the generic EventArgs<T> class to declare an event bound to the specific parameter object you need to use. Again you can use either implicit or explicit event registration.
  3. Create a method on the type that will raise the event.

 

So if I had a parameter object that looked like this:

public class ReportingPeriod { private DateTime start; private DateTime end; public DateTime Start { get { return start; } } public ReportingPeriod(DateTime start, DateTime end) { this.start = start; this.end = end; } }

I would be able to create a type that raises an event to propagate this data as follows (using implicit registration):

public class ReportTrigger { public event EventHandler<EventArgs<ReportingPeriod>> RunReport; }

Or using explicit registration:

public class ReportTrigger { private EventHandler<EventArgs<ReportingPeriod>> subscribers; public event EventHandler<EventArgs<ReportingPeriod>> RunReport { add { subscribers += value; } remove { subscribers -= value; } } }

Develop With Passion!

Comments [8] | | # 
 Tuesday, July 10, 2007
Tuesday, July 10, 2007 6:04:13 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | C Sharp )

I may be the last one in the .Net world to find this one out!! Say you wanted to execute the following string format statement:

 

return string.Format("{0:MMMM} {0:d}-{1:d}, {0:yyy}", start, end);

The result of that format command would be: January 1/1/2007-1/7/2007, 2007. This is obviously not what I was expecting. In order to specify a single character format specifier I have to use the following:

 return string.Format("{0:MMMM} {0:%d}-{1:%d}, {0:yyy}", start, end);

Which results in the following output: January 1–7, 2007 (which is what I wanted).

Notice the use of the % format specifier prior to the single digit day format specifier. That is what I was missing. If you want to know more about how this works check out the documentation here.

Develop with passion!

Comments [1] | | # 
 Monday, June 25, 2007
Monday, June 25, 2007 3:52:19 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | .Net 3.0 | Agile | C Sharp | Patterns | Programming | Training )

That’s right folks. Nothin But .Net is coming to New York.

The course is going to be held at TCCIT Solutions.

 The course runs for the week of October 22nd – 26th, 2007.

Overview

Nothin But .Net is a five day boot camp that will focus on pragmatically applying .Net within the context of developing a working N-Tiered application. Registrants will learn about advanced features of .Net (2.0/3.0) as they are applied to the task of building a complete application from the UI layer all the way down to the mapping layer.

WARNING!!!!

If you are expecting to come to this course to learn about how to have VS.Net automatically generate an “application” for you, then this course is NOT for you.

This course is all about taking control of the .Net framework and having it work the way you want. This course will place a heavy emphasis on getting back to the basics and making .Net do things the way you want it to, in a predictable and testable way.

This course will focus on a code centric view of application development vs. the typical databinding/designer magic covered by many typical .Net courses. You will walk away with a deep understanding of fundamental aspects of .Net and how these pieces can be used to develop and deliver enterprise scale applications.

Core Concepts Overview

  • Expanding the capabilities of developing with VS.Net - Enter ReSharper (a productivity add-in for Visual Studio .Net)
  • There’s more to life than generated code
  • Automation for the developer
  • Generics ( they’re not just for collections )
  • Back to basics - Rules Of Good Object Oriented Design
  • Dependency Injection
  • Object Relational Mapping in .Net
  • Applying the dependency inversion principle
  • Domain Driven Design
  • Passive View/Supervising Controller (Model View Presenter)
  • Creating layered architectures
  • Driving out functionality and design through testing
  • Taking Control Of Databinding
  • Behavior (Test) Driven Development
  • Core design patterns applied
  • Pragmatic Productivity Tools For Developers

Although the list may look rather daunting, the majority of the bullet points will be covered during the evolutionary design and construction of the sample project.

One of the main goals of the course is to show how to effectively use behavior (test) driven development, design patterns and a solid toolset to develop a portion of a non-trivial application.

The course will allow students to pragmatically apply BDD practices as well as teach people how to utilize fundamental OO concepts and techniques that will allow for them to have cleaner, more loosely coupled architectures. It will also be an opportunity for students to see what is involved in creating applications that utilize a Rich Domain Model,and the supporting infrastructure that is required to use "Plain Old Objects".

I have successfully delivered this course several times with great success. I anticipate that people who are interested will find that this is a very unique course offering, not typical of what is being delivered in the mainstream.

Seats are limited. The course costs $3000/US for a full 5 days. The fee covers:

  • 5 (8 - 14 hour days, depending on the audience availability) of bootcamp style instruction
  • Breakfast
  • Hot Lunch
  • Book - Patterns Of Application Architecture
  • Software – ReSharper 3.0 License

If you have any questions please don't hesitate to contact me at jp@jpboodhoo.com.

To Register for the course please use the following link:

Comments [2] | | # 
 Wednesday, June 20, 2007
Wednesday, June 20, 2007 9:58:33 AM (Mountain Standard Time, UTC-07:00) ( Agile | C Sharp | Training )

That’s right folks. Nothin But .Net is coming to England. This is especially sentimental for me as I was born and raised in England, and I have been waiting for an opportunity to go back and show my family the wonders of England.

The course is going to be held at the Hilton London Euston. If you are needing a room for the week, the Hilton has offered up a discounted rate for anyone who books a room before the 10th of August. The room rate is 179GBP a night excluding VAT. This rate includes an English breakfast.

 The course runs for the week of September 10th – 14th, 2007.

Overview

Nothin’ But .Net is a five day boot camp that will focus on pragmatically applying .Net within the context of developing a working N-Tiered application. Registrants will learn about advanced features of .Net (2.0/3.0) as they are applied to the task of building a complete application from the UI layer all the way down to the mapping layer.

WARNING!!!!

If you are expecting to come to this course to learn about how to have VS.Net automatically generate an “application” for you, then this course is NOT for you.

This course is all about taking control of the .Net framework and having it work the way you want. This course will place a heavy emphasis on getting back to the basics and making .Net do things the way you want it to, in a predictable and testable way.

This course will focus on a code centric view of application development vs. the typical databinding/designer magic covered by many typical .Net courses. You will walk away with a deep understanding of fundamental aspects of .Net and how these pieces can be used to develop and deliver enterprise scale applications.

Core Concepts Overview

  • Expanding the capabilities of developing with VS.Net - Enter ReSharper (a productivity add-in for Visual Studio .Net)
  • There’s more to life than generated code
  • Automation for the developer
  • Generics ( they’re not just for collections )
  • Back to basics - Rules Of Good Object Oriented Design
  • Dependency Injection
  • Object Relational Mapping in .Net
  • Applying the dependency inversion principle
  • Domain Driven Design
  • Passive View/Supervising Controller (Model View Presenter)
  • Creating layered architectures
  • Driving out functionality and design through testing
  • Taking Control Of Databinding
  • Behavior (Test) Driven Development
  • Core design patterns applied
  • Pragmatic Productivity Tools For Developers

Although the list may look rather daunting, the majority of the bullet points will be covered during the evolutionary design and construction of the sample project.

One of the main goals of the course is to show how to effectively use behavior (test) driven development, design patterns and a solid toolset to develop a portion of a non-trivial application.

The course will allow students to pragmatically apply BDD practices as well as teach people how to utilize fundamental OO concepts and techniques that will allow for them to have cleaner, more loosely coupled architectures. It will also be an opportunity for students to see what is involved in creating applications that utilize a Rich Domain Model,and the supporting infrastructure that is required to use "Plain Old Objects".

I have successfully delivered this course several times with great success. I anticipate that people who are interested will find that this is a very unique course offering, not typical of what is being delivered in the mainstream.

Seats are limited. The course costs $4000/US for a full 5 days. The fee covers:

  • 5 (8 - 14 hour days, depending on the audience availability) of bootcamp style instruction
  • Breakfast
  • Coffee Break
  • Hot Lunch
  • Supper
  • Book - Patterns Of Application Architecture
  • Software – ReSharper 3.0 License

If you have any questions please don't hesitate to contact me at jp@jpboodhoo.com.

Requirements

  • You will be required to bring your own laptop ( VMWare / VPC images will be deployed to your machine on day 1 of the course)

To Register for the course please use the following link:

Comments [5] | | # 
 Wednesday, June 13, 2007
Wednesday, June 13, 2007 11:19:35 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Patterns )

Bil Simser had a post up the other day about Refactoring Dumb, Dumber, and Dumbest away. I had some small suggestions that I offered up and Bil implemented some of the changes that I had mentioned. Here is the code as it stands right now :

public class SegmentConfigurationFactory { /// <summary> /// Gets the configuration given the values provided. /// </summary> /// <param name="cableSegmentCount">The cable segment count.</param> /// <param name="segmentCount">The segment count.</param> /// <param name="passesCount">The passes count.</param> /// <param name="segmentIndex">Index of the segment.</param> /// <param name="supplyVoltage">The supply voltage.</param> /// <param name="voltageDrop">The voltage drop.</param> /// <param name="segmentPercentage">The segment percentage.</param> /// <returns></returns> public ISegmentConfiguration GetConfigurationGiven( int cableSegmentCount, int segmentCount, int passesCount, int segmentIndex, int supplyVoltage, decimal voltageDrop, decimal segmentPercentage ) { ISegmentConfiguration configuration = new DefaultSegmentConfiguration(1, supplyVoltage, voltageDrop); if (segmentCount > 1) { if (cableSegmentCount == 1) { if (passesCount > 1 && (segmentIndex <= (segmentCount - 2))) { configuration = new MultiPassConfiguration(passesCount, supplyVoltage, voltageDrop, segmentPercentage); } else { configuration = new SinglePassConfiguration(cableSegmentCount, supplyVoltage, voltageDrop, segmentPercentage); } } else { configuration = new MultipleCableCountConfiguration(cableSegmentCount, supplyVoltage, voltageDrop, segmentPercentage, passesCount); } } return configuration; } }

I was then asked how I could potentially take the refactoring further. I had mentioned that there were a lot of “magic numbers” in the code, to which Bil correctly replied that there are, but they were numbers that represented real business rules, and as such were not that “magic”. Armed with the following set of rules that center around the messy if statement: 

  • If there is one pass we use a single pass configuration
  • If there is one segment we use the default configuration
  • If there are multiple cables in a segment then we use the multiple cable count configuration
  • If there are multiple passes or the segment we’re looking at is the 2nd last one we use a multiple pass configuration

I decided to take the refactoring a step further to introduce a bit more readability into the Model. I got into mad refactoring mode and decided to pair back the final implementation. The result of the refactoring is as follows: 

public class SegmentConfigurationFactory : ISegmentConfigurationFactory { public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters) { if (new MultiPassSegmentConfigurationParametersSpecification().IsSatisfiedBy(parameters)) return new MultiPassSegmentConfigurationFactory().CreateUsing(parameters); if (new SinglePassSegmentConfigurationParametersSpecification().IsSatisfiedBy(parameters)) return new SinglePassSegmentConfigurationFactory().CreateUsing(parameters); if (new MultipleCableCountSegmentConfigurationParametersSpecification().IsSatisfiedBy(parameters)) return new MultiCableCountSegmentConfigurationFactory().CreateUsing(parameters); return new DefaultSegmentConfigurationFactory().CreateUsing(parameters); } }

The first step to achieve this refactoring was to introduce a parameter object that encapsulated all of the arguments that use to be called on the method. This:

public ISegmentConfiguration GetConfigurationGiven( int cableSegmentCount, int segmentCount, int passesCount, int segmentIndex, int supplyVoltage, decimal voltageDrop, decimal segmentPercentage )

Became this:

public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters)

I won’t bother showing the parameter object as it is just an object that exposes all of the original parameters as properties.

Now that I had the parameter object, I could leverage it from a new factory interface:

public interface ISegmentConfigurationFactory { ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters); }

If you look back to the original code you will realize that at each branch that is creating a configuration, a potential different set of arguments is being used. By coming up with an interface for the factory, I can now have specific factories that create specific configurations based on the configuration parameters:

    public class DefaultSegmentConfigurationFactory : ISegmentConfigurationFactory
    {
        public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters)
        {
            return new DefaultSegmentConfiguration(1, parameters.SupplyVoltage, parameters.VoltageDrop);
        }
    }

public class MultiPassSegmentConfigurationFactory : ISegmentConfigurationFactory { public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters) { return new MultiPassConfiguration(parameters.PassesCount, parameters.SupplyVoltage, parameters.VoltageDrop, parameters.SegmentPercentage); } }

public class SinglePassSegmentConfigurationFactory : ISegmentConfigurationFactory { public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters) { return new SinglePassConfiguration(parameters.CableSegmentCount, parameters.SupplyVoltage, parameters.VoltageDrop, parameters.SegmentPercentage); } }
 

public class MultiCableCountSegmentConfigurationFactory : ISegmentConfigurationFactory { public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters) { return new MultipleCableCountConfiguration(parameters.CableSegmentCount, parameters.SupplyVoltage, parameters.VoltageDrop, parameters.SegmentPercentage, parameters.PassesCount); } }

Each factory is responsible for creating a specific configuration based on the parameters. This introduces a nice separation of responsibilities, because properties can be added to the SegmentConfigurationParameters without introducing any change to the individual factories and the original SegmentConfigurationFactory itself. It also allows each individual factory to only leverage the properties on the parameter object that it needs to. This allows fine grained tests against the individual factories to ensure that they are only pulling from properties that they should be, and that they are providing the configurations they create with the correct information.

That’s great JP, you’ve introduced discrete factories but we are still left with the if statements and “magic” numbers. Remember that at each branch in the if statement (where a configuration is being created) that configuration matches a certain “Specification”. I just gave it away!! I can introduce discrete specifications that encapsulate the business rules so that each conveys more clearly what “Cable” specification it matches. Once again I can use the parameter object in the new interface:

public interface ISegmentConfigurationParametersSpecification { bool IsSatisfiedBy(SegmentConfigurationParameters parameters); }

If you are not familiar with the specification pattern you can stay tuned to DNRTv as I am going to be drilling down deep into the pattern (way more than I am showing here!!). Here are specifications for the main types of configuration:

public class MultiPassSegmentConfigurationParametersSpecification : ISegmentConfigurationParametersSpecification { public bool IsSatisfiedBy(SegmentConfigurationParameters parameters) { return parameters.SegmentCount > 1 && parameters.CableSegmentCount == 1 && parameters.PassesCount > 1 && (parameters.SegmentIndex <= (parameters.SegmentCount - 2)); } }
 

public class SinglePassSegmentConfigurationParametersSpecification : ISegmentConfigurationParametersSpecification { public bool IsSatisfiedBy(SegmentConfigurationParameters parameters) { return parameters.SegmentCount > 1 && parameters.CableSegmentCount == 1 && parameters.PassesCount == 1; } }

public class MultipleCableCountSegmentConfigurationParametersSpecification : ISegmentConfigurationParametersSpecification { public bool IsSatisfiedBy(SegmentConfigurationParameters parameters) { return parameters.SegmentCount > 1 && parameters.CableSegmentCount > 1; } }

As you can see, each specification is responsible for answering the question “Does this parameter object meet the ‘Specification’ of a certain type of configuration. Again, each class can be tested independently of one another. Notice that there is duplication between the classes that could be easily refactored out by using composite specifications. I tried to name the specifications and factories so they conveyed clearly to the developers what business rules they were encapsulating.

To recap, the refactorings are as follows:

  • Introduce Parameter Object
  • Replace business specific conditionals with Specification (that is not an actual Refactoring, but I think I’m going to coin that name!!)
  • Introduced discrete factories for the different configurations.

Of course, taken it to the Nth degree you could introduce the following interface (I won’t bother showing the implementation, but I’ll give you a hint ‘Use Object Composition’):

 

public interface ISegmentConfigurationSpecificationBasedFactory : ISegmentConfigurationParametersSpecification,ISegmentConfigurationFactory { }

With that interface in hand SegementConfigurationFactory can become:

public class SegmentConfigurationFactoryToTheMaxx : ISegmentConfigurationFactory { private IEnumerable<ISegmentConfigurationSpecificationBasedFactory> configurationFactories; public SegmentConfigurationFactoryToTheMaxx(ISegmentConfigurationFactory defaultConfigurationFactory, IEnumerable<ISegmentConfigurationSpecificationBasedFactory> configurationFactories) { this.configurationFactories = configurationFactories; } public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters) { foreach (ISegmentConfigurationSpecificationBasedFactory factory in configurationFactories) { if (factory.IsSatisfiedBy(parameters)) return factory.CreateUsing(parameters); } throw new ArgumentException( "There is no factory configured to create a configuration from the set of parameters"); } }

Which now leaves the SegmentConfigurationFactory adhering to OCP.

Once again, like all of the refactorings I have demonstrated on this blog, this is just an example to show that there are always ways you can refactor code. Whether the extent of the refactoring is warranted is something that you have to figure out between you and your team members. I am not suggesting that this is the route you want to go (although it could be).

Have I had to introduce more classes and interfaces? Absolutely. Do I have more testability from going this route? Absolutely. Have I made the domain more resilient to change? I think so.

When you are refactoring to reveal intent, don’t expect that your codebase is going to shrink. To make the model more expressive sometimes you will need to introduce new concepts into the codebase that up the LOC, but increase the readability and maintainability. 

At the end of the day, if the original code conveys intent more clearly (Good rule of thumb is to use the 6 month rule, in 6 months when you come back to look at the code, will it still convey its intent) then that trumps elegance of the code.

In all of this make sure that “Maintainability” trumps all the other “ilities”.

Comments [3] | | # 
 Friday, May 25, 2007
Friday, May 25, 2007 11:04:41 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | ScreenCasts )

After I finished up recording part 3. I realized that I was not showing off as many ReSharper shortcuts as I could have. That will definitely change over the course of the next set of episodes. For the remainder of the series I will be recording the entire series “sans mouse”. Hopefully this will give people an idea of how productive you can actually be without using the keyboard mouse. As soon as I had finished recording the session I thought to myself “yikes, I made that list enumerable way more complicated that it should have been”. Instead of this:

 

public class ListEnumerable<T> : IEnumerable<T> { private IList<T> itemsToEnumerate; public ListEnumerable(IList<T> itemsToEnumerate) { this.itemsToEnumerate = itemsToEnumerate; } public IEnumerator<T> GetEnumerator() { return new ListEnumerator<T>(itemsToEnumerate); } IEnumerator IEnumerable.GetEnumerator() { return new ListEnumerator<T>(itemsToEnumerate); } }

I could have simply done this:

public class ListEnumerable<T> : IEnumerable<T> { private IList<T> itemsToEnumerate; public ListEnumerable(IList<T> itemsToEnumerate) { this.itemsToEnumerate = itemsToEnumerate; } public IEnumerator<T> GetEnumerator() { return itemsToEnumerate.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return itemsToEnumerate.GetEnumerator(); } }

And of course, an even easier way (if you have .Net 2.0) is to just leverage the yield keyword inside of a method returning IEnumerable. Which is how I started off the discussion on iterators.

Comments [4] | | # 
 Wednesday, May 23, 2007
Wednesday, May 23, 2007 6:26:25 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | ScreenCasts )

I have just concluded part 3 of a dnrTV series trying to demonstrate the usage of common design patterns in the context of building a simple employee contact book application.

So far I have been able to cover the following design patterns:

  • Singleton
  • Monostate
  • Strategy
  • Factory
  • Gateway
  • Iterator

I plan to conclude the series by talking about the following remaining design patterns:

  • Command
  • Proxy
  • Decorator
  • Specification

I thought now would be a good time to release the source so far so that people can follow along with the examples/refactorings going forward from this point on.

You can download the source code from here. You can also watch the first 2 episodes at these links:

The example is being kept simple enough so that people can hopefully grok the application of the design patterns. For any people who are already watching the series, your feedback is greatly appreciated.

Comments [8] | | # 
 Monday, May 07, 2007
Monday, May 07, 2007 10:10:19 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

I was just asked a question that I thought I would share with everyone in the event that it actually might help anyone else out.

The question was in regards to how (in a unit test) I can have a mock object raise an event when using Rhino Mocks. The particular case in question is to verify that a presenter actually consumes and handles an event published and broadcasted by a view.

Let’s write a test to first encapsulate the requirement that a presenter should subscribe to a particular event of the view interface in the presenters constructor. I have a ReSharper file template that sets me up a MockTestFixture with the following structure: 

using MbUnit.Framework; using Rhino.Mocks; namespace NothinButDotNetStore.Test.Presentation { [TestFixture] public class EmployeeBrowserPresenterTest { private MockRepository mockery; [SetUp] public void Setup() { mockery = new MockRepository(); } [TearDown] public void TearDown() { mockery.VerifyAll(); } } }

I am making use of MbUnit and Rhino Mocks. MbUnit for unit testing and Rhino Mocks as my mock object framework. You’ll notice that I create a MockRepository in the SetUp method and I call VerifyAll in the teardown method. This ensures that I never forget to make the call to VerifyAll as I never need to explicitly call it in any of my test methods.

Let’s get to that first test:

[Test] public void Construction_ShouldSubscribeToEventsOnView() { IEmployeeBrowserView mockView = mockery.CreateMock<IEmployeeBrowserView>(); mockView.Initialize += null; LastCall.Constraints(Is.NotNull()); mockery.ReplayAll(); new EmployeeBrowserPresenter(mockView); }

The 2 most important lines in this test are the following: 

mockView.Initialize += null; LastCall.Constraints(Is.NotNull());

These two lines make up the requirement that:

  • At some point in running this test, the object under test better subscribe to the Initialize event on the view with a Non-Null event handler.

Here is the initial code for the EmployeeBrowserPresenter: 

public class EmployeeBrowserPresenter : IEmployeeBrowserPresenter { private IEmployeeBrowserView view; public EmployeeBrowserPresenter(IEmployeeBrowserView view) { } }

The view interface looks as follows: 

public interface IEmployeeBrowserView { event EventHandler Initialize; }

If I were to run this test right now it would fail, because there is nowhere in the constructor of the presenter that it is subscribing to the events exposed by the view. To get the test running and passing I’ll have to add the following code:

 

public class EmployeeBrowserPresenter : IEmployeeBrowserPresenter { private IEmployeeBrowserView view; public EmployeeBrowserPresenter(IEmployeeBrowserView view) { this.view = view; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(IEmployeeBrowserView view) { view.Initialize += delegate { }; } }

You can see that in the constructor, the presenter now subscribes to the Initialize method with a non null event handler (in this case an empty anonymous method). This gets my test passing. Now I need to write a separate test to verify that the presenter actually does something when the event is raised. Because I will be creating the presenter for each test, each test would need to setup the expecation for the event subscription. I don’t want to duplicate my efforts so I will move some code to the setup method. This will cause my test class to look as follows:

 

[TestFixture] public class EmployeeBrowserPresenterTest { private MockRepository mockery; private IEmployeeBrowserView mockView; [SetUp] public void Setup() { mockery = new MockRepository(); mockView = mockery.CreateMock<IEmployeeBrowserView>(); mockView.Initialize += null; LastCall.Constraints(Is.NotNull()); } [TearDown] public void TearDown() { mockery.VerifyAll(); } [Test] public void Construction_ShouldSubscribeToEventsOnView() { mockery.ReplayAll(); new EmployeeBrowserPresenter(this.mockView); } }

Now I can write the test to ensure that the presenter does something when the view raises its Initialized event. For arguments sake, let’s have the presenter Invoke a method on the view in response to handling the Initialize event:

[Test] public void ViewInitializationHandler_PresenterShouldPushMessageToView() { mockView.DisplayMessage(null); LastCall.Constraints(Is.NotNull()); mockery.ReplayAll(); IEmployeeBrowserPresenter presenter = new EmployeeBrowserPresenter(mockView); IEventRaiser eventRaiser = new EventRaiser((IMockedObject) mockView, "Initialize"); eventRaiser.Raise(null,null); }

Notice how I am leveraging the EventRaiser class to simulate the mock object raising an event. Unfortunately, using this approach defeats the purpose for using Rhino over NMock2 in the sense that you have to resort to providing the name of the event as a string. No good. Let’s refactor this to eliminate the need for the string. I’ll make a change to the Setup method as follows:

private IEventRaiser initializeEventRaiser; [SetUp] public void Setup() { mockery = new MockRepository(); mockView = mockery.CreateMock<IEmployeeBrowserView>(); mockView.Initialize += null; LastCall.Constraints(Is.NotNull()); initializeEventRaiser = LastCall.GetEventRaiser(); }

Using LastCall.GetEventRaiser provides me a way to get access to an event raiser bound to a particular event on a mock object. The caveat is that you have to ensure that the previous mock object expectation (in this call mockView.Initialize += null) was an expectation on an event exposed by the interface. With this IEventRaiser in hand I can refactor my test as follows:

 

[Test] public void ViewInitializationHandler_PresenterShouldPushMessageToView() { mockView.DisplayMessage(null); LastCall.Constraints(Is.NotNull()); mockery.ReplayAll(); IEmployeeBrowserPresenter presenter = new EmployeeBrowserPresenter(mockView); initializeEventRaiser.Raise(null,null); }

The Raise method expects a set of parameters that match up with the signature for the delegate type of the event. In this case the Initialize event on the view interface is an EventHandler delegate type. The EventHandler delegate is the basic event handler signature in the framework that takes a sender and an EventArgs. In this scenario, because my presenter does not care about either, I pass null for both. To get this test to pass I can write the following code on my presenter:

 

private void HookupEventHandlersTo(IEmployeeBrowserView view) { view.Initialize += delegate { view.DisplayMessage(DateTime.Now.ToString());}; }

In the anonymous event handler, I have the presenter invoke the DisplayMessage method on the view, passing it the current time as a string. This satisfies the new requirement in the test:

mockView.DisplayMessage(null); LastCall.Constraints(Is.NotNull());

Now you know how to raise events in a refactorable way using Rhino Mocks.

 

Develop with passion!

Comments [6] | | # 
 Tuesday, April 17, 2007
Tuesday, April 17, 2007 1:35:11 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Programming )

This morning had a good question asked:

Q: Basically we're writing the billing processing part of our business
application.  On the 1st and 15th of the month, we bill all our
policy holders and it's usually 10,000 or so transactions that need to
be run.  The processor gateway runs as a webservice.  Now since these
10,000 don't rely on each other at all, I figured to speed it up I
could run 10-20 at a time in a job.
 
So I wrote this simple class so far, but I'm not sure if it's even
close, it just takes a processing date, loads all the queued
transactions, and sends them into the authorize and payment manager.
It seems that async threads you have to delegate to a void
parameterless method, so I built a locked incrementer for the index on
the generic list of transactions and try to process them like that.
It's the while loop stuff that is lame, I'd really like it to just
spawn X number of threads where X is configurable.  Maybe I just dont'
get it, here's the code though: 

public class Billing { public Billing(DateTime ProcessDate) { _ProcessDate = ProcessDate; PopulateTransactions(); ExecuteBilling(); } private Int32 _TransactionIndex = 0; private List<Transaction _TransactionsToBill; private DateTime _ProcessDate; private void PopulateTransactions() { _TransactionsToBill = TransactionManager.GetQueuedTransactions(_ProcessDate); } private void ExecuteBilling() { do { Thread t1 = new Thread(new ThreadStart(ProcessTransaction)); t1.Start(); Thread t2 = new Thread(new ThreadStart(ProcessTransaction)); t2.Start(); Thread t3 = new Thread(new ThreadStart(ProcessTransaction)); t3.Start(); Thread t4 = new Thread(new ThreadStart(ProcessTransaction)); t4.Start(); Thread t5 = new Thread(new ThreadStart(ProcessTransaction)); t5.Start(); } while (_TransactionIndex < _TransactionsToBill.Count); } private void ProcessTransaction() { string Message; Transaction transaction = GetNextTransaction(); if (transaction != null) CyberSourceManager.AuthorizeAndCapture(transaction.InvoiceID,transaction.ID, out Message); } private Transaction GetNextTransaction() { Interlocked.Increment(ref _TransactionIndex); if (_TransactionsToBill.Count _TransactionIndex) { return _TransactionsToBill[_TransactionIndex - 1]; } return null; } }

A: The main problem that you are concerned about is : “I'd really like it to just spawn X number of threads where X is configurable”. The following code is another alternative implemented using the Monitor class to create a producer/consumer queue:

public class Billing { private Queue<Transaction> transactionQueue; private IList<Thread> workerThreads; private object mutex; public Billing(int numberOfWorkerThreadsToUse,IEnumerable<Transaction> itemsToProcess) { mutex = new object(); workerThreads = new List<Thread>(); transactionQueue = new Queue<Transaction>(); InitializeConsumers(numberOfWorkerThreadsToUse); QueueUp(itemsToProcess); QueueEmptyTransactionsForEachActiveThread(); } private void QueueUp(IEnumerable<Transaction> toProcess) { foreach (Transaction transaction in toProcess) { QueueForProcessing(transaction); } } private void QueueEmptyTransactionsForEachActiveThread() { foreach (Thread wokerThread in workerThreads) { QueueForProcessing(null); } } private void QueueForProcessing(Transaction transaction) { lock (mutex) { transactionQueue.Enqueue(transaction); Monitor.PulseAll(mutex); } } private void InitializeConsumers(int numberToInitialize) { for (int i = 0; i < numberToInitialize; i++) { Thread thread = new Thread(ProcessTransactions); workerThreads.Add(thread); thread.Start(); } } private void ProcessTransactions() { while (true) { Transaction transaction = null; lock (mutex) { while (transactionQueue.Count == 0) Monitor.Wait(mutex); transaction = transactionQueue.Dequeue(); } if (transaction == null) return; Process(transaction); } } private void Process(Transaction transaction) { //Do you work here } }

The advantage of this code over the prior code is it mitigates unecessary allocation of an unknown number of threads and opts for the creation of an explicit “known” number of worker threads that will process items on the queue. This code leverages the ability to wait on a locked object. When a transaction is Queued up, Monitor.PulseAll is invoked (on the mutex) to wake up all threads that may already be waiting on that mutex,based on which thread is currently highest in the lock queue, it will be able to Dequeue a single transaction from the “transaction” queue and process it.

The constructor for the Billing class allows you to specify how many worker threads should be created. You should notice, that the Consumer threads can start immediately processing Transactions the second a Transaction is queued for processing. This has the benefit of not needing to have the queue populated in its entirety before processing. As new items are added to the queue, a worker thread can pick it up and process it. Once all of the real transactions have been added to the queue for processing, a “null” transaction is placed onto the queue for each worker thread that was created. This ensures that each thread will actually terminate.

Notice how in the ProcessTransactions method, it does not stop processing if the number of items in the queue == 0. This is because (again, multi threaded coding is hard) since items are being added to the queue from a separate thread, and items are being processed by 1 of the many worker threads, the client thread may not have had the opportunity to place items on the queue before the (transactionQueue.Count == 0) condition is evaluated. If I used the count of the items in the queue as my termination condition, the worker thread would most likely terminate too early. Hence the need for the null transaction that each thread will have to handle. Once the worker dequeues a null transaction, it knows that it is time for it to finish.

I’m not saying this is the only way to solve this problem, I just wanted to demonstrate how you could share the load of the processing between a finite amount of worker threads, while utilizing the Monitor class to perform fine grained synchronization.

The usage for this class becomes very simple:

new Billing(5,transactionService.GetTransactionsToProcess());

 

 

Comments [2] | | # 
 Thursday, March 01, 2007
Thursday, March 01, 2007 5:04:19 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Presentations )

I had a blast presenting at the Edmonton .Net User Group last week. With the presentation and finishing the course I neglected to upload the source code for the presentation.

It is a little rough around the edges, but the cool part was that almost all of the code was churned out during the course of the session. It was a frenzy, but I feel confident that a lot of awesome concepts got disseminated to the crowd.

Thanks Edmonton for having me, I look forward to the next time.

You can download the source code from here (you will need WinRar to extract it).

Comments [5] | | # 
 Friday, February 02, 2007
Friday, February 02, 2007 3:47:58 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Presentations )

Thanks again to everyone who attended my talks last Saturday. The following are the links to the source code (and slides) that were produced during the presentations. Enjoy.

Comments [1] | | # 
 Tuesday, January 30, 2007
Tuesday, January 30, 2007 9:19:09 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Tools | VS2005 )

If, like me, you are a keyboard junkie wanting to sharpen you keyboarding skills in VS 2005 you might appreciate this PDF that contains the default keybinding for Visual C# 2005. Thanks to Lucio Assis for providing me with the link!!

This is a great place to start getting more proficient navigating around studio without the mouse. If you really want to take your keyboarding skills in studio to the next level do yourself a favour and pick up a copy of JetBrains ReSharper, then you can really start to fly.

Comments [1] | | # 
 Friday, January 19, 2007
Friday, January 19, 2007 12:43:03 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

Following on from the last post, Ayende reminded me that I forgot to use reflector on the offending piece of code. Here is code taken straight from the System.Timers.Timer class that shows exactly why it is behaving the way it is (pay attention to the try block):

 

private void MyTimerCallback(object state) { if (state == this.cookie) { if (!this.autoReset) { this.enabled = false; } Timer.FILE_TIME file_time1 = new Timer.FILE_TIME(); Timer.GetSystemTimeAsFileTime(ref file_time1); ElapsedEventArgs args1 = new ElapsedEventArgs(file_time1.ftTimeLow, file_time1.ftTimeHigh); try { ElapsedEventHandler handler1 = this.onIntervalElapsed; if (handler1 != null) { if ((this.SynchronizingObject != null) && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.BeginInvoke(handler1, new object[] { this, args1 }); } else { handler1(this, args1); } } } catch {
//if an exception occurs in the forest, does anyone handle it? } } }

And there we have it (ok, so I added in the comment in the catch block)!!

Comments [3] | | # 
 Thursday, January 18, 2007
Thursday, January 18, 2007 11:03:19 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

I was working on a project at a client site almost a month ago, and ran into an annoying issue with the System.Timers.Timer class. The following code snippet should demonstrate the issue clearly:

 

public static void Main() { System.Timers.Timer timer = new System.Timers.Timer(3000); timer.Elapsed+=delegate { Console.WriteLine("About to throw unhandled exception"); throw new Exception(); }; Console.ReadLine(); }

 

If you go ahead an run this code you can quickly take note that the program does not die. It will continually output the message "About to throw unhandled exception" until you press a key and hit enter.

If , however, you make use of the System.Threading.Timer class :

 

public static void Main() { Timer timer = new Timer(delegate { Console.WriteLine("About to throw unhandled exception"); throw new Exception(); },null,3000,3000); Console.ReadLine(); }

The program will die a horrible death (as expected) and you could deal with the error accordingly using a global error handler. Of course, using a global error handler is only useful if the unhandled error can be caught in the first place in the case of the System.Timers.Timer this is not the case:

 

public static void Main() { AppDomain.CurrentDomain.UnhandledException += delegate { Console.WriteLine("An unexpected error occurred."); }; Timer timer = new Timer(3000); timer.Elapsed+=delegate { Console.WriteLine("About to throw unhandled exception"); throw new Exception(); }; timer.Start(); Console.ReadLine(); }

Just a quick bit of information in case you ever run into this problem.

Comments [1] | | # 
 Saturday, January 13, 2007
Saturday, January 13, 2007 1:15:15 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Presentations )

Just in case my last post was not clear enough (as you had to read to the bottom to see that there was a link to the source code!!) I am reposting a link to the source code for the presentation I gave to the Calgary .Net User Group on Enterprise Design Patterns. The talk quickly turned into a primer on the concepts of Dependency Inversion and Dependency Injection, which in my opinion are great concepts to be familiar with when wanting to tackle enterprise patterns properly.

During the course of the presentation I demonstrated how to first create a lightweight interface for an IOC container. I then developed a simple implementation that was then replaced with an implementation bound to the Windsor container which also utilized Binsor (great little tool developed by Oren Eini) for the container configuration.

If anyone has any questions about the source please do not hesitate to contact me.

One last time the source code is here!!

Comments [3] | | # 
 Thursday, November 23, 2006
Thursday, November 23, 2006 10:35:13 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

Lots of people ask me "How do you get better as a developer?" my answer is simple, "Develop"!! You can read all you want, until you start applying what you are learning the information is useless.

On that note, I greatly appreciate the work that Billy McCafferty is doing for the dev community by taking the time to create and publish a set of Refactoring challenges. It takes a lot of personal time and effort to put something like that out there (speaking from experience), so show him your appreciation by downloading the code and "Refactor mercilessly". As a mentor in a dev shop, some (one) of the keeners are eager to download the code and clean it up, which gives me an opportunity to share some small nuggets of wisdom also!!

Thanks again Bill.

Comments [0] | | # 
 Wednesday, October 25, 2006
Wednesday, October 25, 2006 10:47:25 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Presentations )

There is no better way to appreciate the effectiveness of Test Driven Development, that seeing it done real time. Today I spent a couple of hours with the good people at Focus, and was attempting to cover in a small 4 hour session:

  • Test Driven Development
  • Interface Based Programming
  • Dependency Inversion Principle – followed by Dependency Injection
  • Mock Objects

In such a short amount of time you can only hope to cover these topics at a pretty high (and quick) level.

The fun part, was coming up with a problem on the fly that I could use to demonstrate the values of Test Driven Development/Behavior Driven Development. By not going to the session with a prepared application, it allowed me to drive out a solution right before their eyes, and hopefully left them with a good impression as to the effectiveness that TDD can bring into an evolutionary design process.

 

 

Comments [2] | | # 
 Friday, October 20, 2006
Friday, October 20, 2006 10:41:21 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

I stumbled onto this awesome operator after a month or 2 of working with C# 2.0 (almost 2 years ago now). Take advantage of it to make your lazy initialization a lot simpler (not worrying about thread safety here). The operator simply returns the left-hand operand if it is not null otherwise it returns the right-hand operand. Take a look at the following progression of the code:

 

Simple If Statement:

 

        public ISession ActiveSession
        {
            get
            {
                if (activeSession == null)
                {
                    activeSession = mappingSessionFactory.Create();
                }
                return activeSession;
            }
        }

 

Made tighter by eliminating the braces:

 

        public ISession ActiveSession
        {
            get
            {
                if (activeSession == null) activeSession = mappingSessionFactory.Create();                
                return activeSession;
            }
        }
 
Further condensed by taking advantage of the ternary operator :
 
        public ISession ActiveSession
        {
            get { return (activeSession == null ? activeSession = mappingSessionFactory.Create() : activeSession); }
        }
 
Made readable again by taking advantage of the ?? operator:
 
        public ISession ActiveSession
        {
            get { return activeSession ?? (activeSession = mappingSessionFactory.Create()); }
        }

 

Notice what is happening in that line? If the left hand side of the operand (the activeSession field) evaluates to null,  the right-hand operand is returned; which in this case results in an initialization of the field that was null in the first place.Again, this is not new information, I just thought I would throw it out there as a reminder.

 

JP

Comments [7] | | # 
Friday, October 20, 2006 1:49:22 AM (Mountain Standard Time, UTC-07:00) ( C Sharp )

I'm not sure why you would want to do this (and I may be the last person in the world who actually figured this out), in C# if you try to do something like this it will be completely invalid:

 

            public void SomeMethod()
            {
                object object = new object();
            }
 
You can ,however, do this:
 
            public void SomeMethod()
            {
                object @object = new object();
            }
 
Notice the use of the @ symbol.
 
Again, I can't see any value in taking advantage of this, take care with using this feature!!!
Comments [1] | | # 
 Tuesday, October 10, 2006
Tuesday, October 10, 2006 2:55:48 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

In response to Stevens' post on the Decompose Conditional refactoring, I thought I would offer up a quick alternative that I could share with others. Take a look at the code after Stevens original refactoring (I am making guesses as to the actual implementations, but it should convey pretty accurately the general idea of what is going on. I converted the code to C#, for my sanity!! 

public enum PaymentType { Cash, CreditCard } public interface IPaymentView { PaymentType PaymentType{get;} event EventHandler Save; decimal Amount{get;} void ShowMessage(string message,bool someFlag); void CloseView(); } public interface IPaymentTask { void SaveCashPayment(decimal amount); void SaveCreditCardPayment(decimal amount); } public class PaymentPresenter { private IPaymentTask task; private IPaymentView view; public PaymentPresenter(IPaymentView view,IPaymentTask task) { this.task = task; this.view = view; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(IPaymentView view) { view.Save+=delegate{ ProcessPayment(); }; } public void ProcessPayment() { if (PaymentTypeIsCash()) { SaveCashPayment(); } else { SaveCreditCardPayment(); } } private bool PaymentTypeIsCash() { return view.PaymentType == PaymentType.Cash; } private void SaveCashPayment() { try { task.SaveCashPayment(view.Amount); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } private void SaveCreditCardPayment() { try { task.SaveCreditCardPayment(view.Amount); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } }

By utilizing the Decompose Conditional refactoring, he was able to make the code in the ProcessPayment method a bit more readable. Steven asked for suggestions to help further refactor the code, and I am going to offer this one tidbit. Anytime I am switching on some data and then performing some processing based on the data, it screams like a good candidate for the "Replace Conditional with Strategy" refactoring. However, I am not going to go crazy. I will offer up a similar solution, that does not require the introduction of a whole strategy hierarchy.

The goal is to eliminate the conditional completely (and also, offer up a good migration path, in the event other payment types come into play). The key to this solution is to take advantage of delegates, and the PaymentType itself. One thing we can take advantage of in this scenario is the fact that the methods to process a payment have identical signatures. Let's create a delegate that can be used to invoke both of these methods:

 

private delegate void PaymentProcessor();

 

Armed with that signature we can now do the following:

 

public class PaymentPresenter { private IPaymentTask task; private IPaymentView view; private delegate void PaymentProcessor(); private IDictionary<PaymentType,PaymentProcessor> paymentProcessors; public PaymentPresenter(IPaymentView view,IPaymentTask task) { this.task = task; this.view = view; InitializePaymentProcessors(); HookupEventHandlersTo(view); } private void InitializePaymentProcessors() { paymentProcessors = new Dictionary<PaymentType,PaymentProcessor>(); paymentProcessors.Add(PaymentType.Cash,SaveCashPayment); paymentProcessors.Add(PaymentType.CreditCard,SaveCreditCardPayment); } private void HookupEventHandlersTo(IPaymentView view) { view.Save+=delegate{ ProcessPayment(); }; } public void ProcessPayment() { paymentProcessors[view.PaymentType](); } // public void ProcessPayment() // { // if (PaymentTypeIsCash()) // { // SaveCashPayment(); // } // else // { // SaveCreditCardPayment(); // } // } // private bool PaymentTypeIsCash() // { // return view.PaymentType == PaymentType.Cash; // } private void SaveCashPayment() { try { task.SaveCashPayment(view.Amount); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } private void SaveCreditCardPayment() { try { task.SaveCreditCardPayment(view.Amount); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } }

By taking advantage of the dictionary we have removed the need for both the if statement in the ProcessPayment method, as well as the method that determines whether a payment type is cash. Each payment type will be initialized to be processed by a particular process method. If a new payment type is added, it is as simple as adding a new method for processing the payment type, and an accompanying line to the InitializePaymentProcessors method, no change would be required to the ProcessPayment method.

For one last refactoring, let's eliminate the duplication that is happening in both of the Save methods. Both methods try to call the appropriate method on the service layer, if they fail the presenter tells the view to display a message, otherwise they tell the view to close. We can consolidate that logic into the ProcessPayment method as follows:

 

public void ProcessPayment() { try { paymentProcessors[view.PaymentType](); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); }

With that change in place our respective save methods become one liners:

 

private void SaveCashPayment() { task.SaveCashPayment(view.Amount); } private void SaveCreditCardPayment() { task.SaveCreditCardPayment(view.Amount); }

 

Once those methods are collapsed as such, you can also inline the method calls themselves, and eliminate the methods that are just wrapping calls to the underlying service layer. To do that we need to change the signature of our delegate to a signature that matches the methods that will get called on the underlying service layer. The final result of this refactoring results in a much tighter presenter:

 

public class PaymentPresenter { private IPaymentTask task; private IPaymentView view; private IDictionary<PaymentType,PaymentProcessor> paymentProcessors; private delegate void PaymentProcessor(decimal amount); public PaymentPresenter(IPaymentView view,IPaymentTask task) { this.task = task; this.view = view; InitializePaymentProcessors(); HookupEventHandlersTo(view); } private void InitializePaymentProcessors() { paymentProcessors = new Dictionary<PaymentType,PaymentProcessor>(); paymentProcessors.Add(PaymentType.Cash,task.SaveCashPayment); paymentProcessors.Add(PaymentType.CreditCard,task.SaveCreditCardPayment); } private void HookupEventHandlersTo(IPaymentView view) { view.Save+=delegate{ ProcessPayment(); }; } public void ProcessPayment() { try { GetPaymentProcessorFor(view.PaymentType)(view.Amount); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } private PaymentProcessor GetPaymentProcessorFor(PaymentType paymentType) { return paymentProcessors[paymentType]; } }

 

Of course, another option altogether is to offset the strategy for processing a payment off to the service layer (backed up by a rich domain model, with strategies for handling different payment types). With such a scenario in place you could end up with a presenter that looks like the following:

 

public class ProcessPaymentDTO { private decimal amount; private PaymentType paymentType; public ProcessPaymentDTO(decimal amount,PaymentType paymentType) { this.amount = amount; this.paymentType = paymentType; } public PaymentType PaymentType { get{return this.paymentType;} } public decimal Amount { get{return this.amount;} } } public interface IModifiedPaymentTask { void Process(ProcessPaymentDTO paymentToProcess); } public class ModifiedPaymentPresenter { private IModifiedPaymentTask task; private IPaymentView view; public ModifiedPaymentPresenter(IPaymentView view,IModifiedPaymentTask task) { this.task = task; this.view = view; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(IPaymentView view) { view.Save+=delegate{ ProcessPayment(); }; } public void ProcessPayment() { try { task.Process(new ProcessPaymentDTO(view.Amount,view.PaymentType)); } catch (Exception) { view.ShowMessage("There was a problem saving the payment.",false); } view.CloseView(); } }

Again, this is just another option you could choose,based on the requirements and architecture you already have in place. The nice thing about this solution is that the presenter and view do not need to change in order to handle new types of payments. All the work is done in the back end!!

Comments [5] | | # 
 Monday, October 09, 2006
Monday, October 09, 2006 7:09:07 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | ScreenCasts )

Well, it's been a long time coming, I am finally posting the second video in my applied test driven development for web applications series.

Although this is video number 3, it is really a fresh start that tries to start with less plumbing than was originally present when I started the first video. This was done on purpose. The video has now been revamped to show people how to start working with the Passive View flavour of Model View Presenter. The lack of infrastructure will also allow me the opportunity to show people how TDD will be applied to all layers of the application. At the end of this video you will have a (semi) working Customer management screen. Over the course of the next couple of weeks (I will be consistent this time), we will proceed to drive out the remaining functionality of both the screen itself and the underlying layers required.

You will note that I am still making use of the old Northwind database. If anyone has any ideas for a small application that requires the use of a database, I am all ears. I would much rather build something that may be used (other than for learning), as opposed to the fictitious example that focuses around the Northwind database. Again, feel free to fire your ideas at me, and I can easily change the future video to actually build out the app in mind.

You will have to excuse the coughing and sputtering in this video, as I am recovering from a nasty bout of Sinusitis (first ever encounter).

Feel free to give me feedback on this video as you see fit!!

**** If you want to run the build on your local machine, make sure you make any necessary changes to the local.properties.xml file, and ensure that the folder specified by the database path in your local.properties.xml file exists******

I will also point out, that I am going to try to release a video at least every 2 weeks. It could be more frequent based on feedback and demand!!

Resources

Comments [18] | | # 
 Wednesday, September 20, 2006
Wednesday, September 20, 2006 4:24:31 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

There are many times when you are coding up a solution that you want to get a quick idea for how long a given operation is taking. A common first attempt at this is the following:

 

[Test] public void ShouldTimeMethodUsingOldSchoolMethod() { DateTime startTime = DateTime.Now; someClass.MethodToTime(); Console.Out.WriteLine(DateTime.Now.Subtract(startTime).Milliseconds); }

This test should be self explanatory. You set a start time, invoke a method, output the difference between the current time and the start time. So this is all well and good (I'm not even bringing up the issue of timer resolution), but anytime you want to quickly time an operation you will be duplicating yourself. Remember the DRY principle, it will guide you toward much more maintainable codebases.

Remembering the DRY principle, you start to think of ways to encapsulate the concept of a StopWatch in your codebase. If you are in .Net 2.0, the framework has already taken care of this for you with the addition of the Stopwatch class in the System.Diagnostics namespace. If you are still in .Net 1.1, and want an equivalent to the 2.0 Stopwatch, then head over to Jeff Atwood's blog and take a look at his Stopwatch implementation. Using either class, you retrofit you code to take advantage of its functionality:

  

[Test] public void ShouldTimeMethodUsingFrameworkStopwatch() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); MethodToTime(); stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); }

As you can see this takes us a step closer to being able to quickly time methods (for quick curiosity). This still seems a bit verbose for my liking. Anytime I want to time a method using this technique I have to:

 

  • Instantiate a stopwatch
  • Start the stopwatch
  • Invoke the method to be timed
  • Stop the stopwatch
  • Output the duration

The only variant in those steps is the method that is going to be invoked (operation to perform). Anyone who knows me, will tell you that I stress the value of eliminating duplication. Let's eliminate the duplication by introducing a new layer of abstraction:

 

public class MyStopwatch : IDisposable { private Stopwatch internalStopwatch; public MyStopwatch() { internalStopwatch = new Stopwatch(); internalStopwatch.Start(); } public void Dispose() { internalStopwatch.Stop(); Console.Out.WriteLine(internalStopwatch.ElapsedMilliseconds); } }

 Notice the use of the IDisposable interface. With this class in place, my previous method now changes to this:

[Test] public void ShouldTimeMethodUsingCustomStopwatch() { using (new MyStopwatch()) { someClass.MethodToTime(); } }

 

Ahh, duplication be gone. Ok, so what if we now want the ability to time a method executing a certain number of times. We could do this:

  

[Test] public void ShouldTimeMethodExecutingACertainNumberOfTimeWithLoopAndCustomStopwatch() { using (new MyStopwatch()) { for (int i = 0; i < 10; i++) { someClass.MethodToTime(); } } }

Again, this is something that is often done a lot of times, so why not take advantage of the class we have created and use accordingly (requires some refactoring):

 

public class MyStopwatch : IDisposable { public delegate void MethodToTime(); private readonly MethodToTime methodToTime; private int numberOfTimesToInvokeMethod; public MyStopwatch(MethodToTime methodToTime):this(methodToTime,1) { } public MyStopwatch(MethodToTime methodToTime, int numberOfTimesToInvokeMethod) { this.methodToTime = methodToTime; this.numberOfTimesToInvokeMethod = numberOfTimesToInvokeMethod; } public void Dispose() { TimeMethodInvocation(); } private void TimeMethodInvocation() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); } }

As you can see, the MyStopwatch class has undergone a serious facelift. To construct an instance of this, you now have to specify a delegate that points to the method you want to invoke!! You can also optionally specify a number of times you want the method to run. Here is a sample demonstrating how to use the upgraded class:

     

[Test] public void ShouldTimeMethodExecutingACertainNumberOfTimesUsingCustomStopwatch() { new MyStopwatch(someClass.MethodToTime,10).Dispose(); }

Now we are getting somewhere!! Although, I am not sure if I like the fact that the client of the stopwatch has to either use it in a using block, or explicitly call dispose (as in the last example), in order to receive timing details. How about exposing a couple of static methods on MyStopwatch: 

 

public static void Time(MethodToTime methodToTime) { Time(methodToTime, 1); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { new MyStopwatch(methodToTime,numberOfTimesToInvokeMethod).Dispose(); }
 

Which leads to a much more convienient usage syntax of:

 

[Test] public void ShouldTimeMethodANumberOfTimesUsingConvenienceMethods() { MyStopwatch.Time(someClass.MethodToTime); MyStopwatch.Time(someClass.MethodToTime,10); }

The nice thing about the convenience methods, is that there is no question about whether or not the client will get its output, as the static methods are ensuring that dispose is getting called on the object. And from my perspective, it eliminates the need for a completely static class (which I am not a big fan of).

 

If you are a fan of static classes (which depending on what you are doing, could become the bane of your developer existence), you could also use the following Stopwatch implementation (which ends up being a lot more compact):

  

public class StaticStopWatch { public delegate void MethodToTime(); public static void Time(MethodToTime methodToTime) { Time(methodToTime, 1); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); Console.Out.WriteLine(stopwatch.ElapsedMilliseconds); } }

And of course, to top it off, if you want to allow for a more flexible mechanism of outputting the results you could do this:

 

public class StaticStopWatch { public delegate void MethodToTime(); public static void Time(MethodToTime methodToTime) { Time(methodToTime, Console.Out); } public static void Time(MethodToTime methodToTime,TextWriter output) { Time(methodToTime, 1,output); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod) { Time(methodToTime, numberOfTimesToInvokeMethod, Console.Out); } public static void Time(MethodToTime methodToTime,int numberOfTimesToInvokeMethod,TextWriter output) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < numberOfTimesToInvokeMethod; i++) { methodToTime(); } stopwatch.Stop(); output.WriteLine(stopwatch.ElapsedMilliseconds); } }

Notice the convenience methods that will pass in the Console.Out as the TextWriter to use. This leaves you the ability to pass in your own TextWriter; if you want to,for example, write to a file.

I hope the "timing" of this blog entry was good for you, and that it helped spark you brain with new ideas for implementing your own (ad-hoc) timers in your applications.

Comments [2] | | # 
 Tuesday, September 19, 2006
Tuesday, September 19, 2006 10:02:25 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

Ever since .Net came on the scene, developers have been able to "easily" add multithreaded features to their codebases. I say "easily" because even in .Net, multithreading is something that lots of developers are still not completely comfortable with, or understand well enough to take advantage of it without the pitfalls commonly associated.

Take a look at a code fragment for a class I want to have used in a multithreaded environment (note that in this code fragment, the code that takes advantage of invoking methods on the Console object is not particularly thread-safe, but for the purpose of demonstrating work being done ignore it!!).

 

public class NotSoSafeConsumer : IConsumer { public void DoSomething() { lock(this) { Console.WriteLine("DoSomething"); Thread.Sleep(8000); } } public void DoSomethingElse() { lock(this) { Console.WriteLine("DoSomethingElse"); Thread.Sleep(8000); } } }

Notice that I am locking on this. Here is a sample console app that demonstrates utilizing this class from multiple threads:

 

 

public static void Main() { LockAndWorkWith(new NotSoSafeConsumer()); Console.ReadLine(); } private static void LockAndWorkWith(IConsumer consumer) { Thread firstMethod = new Thread(consumer.DoSomething); Thread secondMethod = new Thread(consumer.DoSomethingElse); firstMethod.Start(); secondMethod.Start(); firstMethod.Join(); secondMethod.Join(); Console.Out.WriteLine("Finished"); }

If you run the code you will notice that it behaves as expected. Ok, JP, what's the point!! Here is all that it takes to break this code:

  

private static void LockAndWorkWith(IConsumer consumer) { lock (consumer) { Thread firstMethod = new Thread(consumer.DoSomething); Thread secondMethod = new Thread(consumer.DoSomethingElse); firstMethod.Start(); secondMethod.Start(); firstMethod.Join(); secondMethod.Join(); Console.Out.WriteLine("Finished"); } }

Notice that the only change that I made was to add the lock statement around the consumer that is passed into the method. Once I have done that the method has acquired a lock on the consumer object. So when the consumer inside of its own method, tries to lock on itself, it cannot acquire the lock as it is already owned.

This happens because when you are taking advantage of locking on "this" you are basically saying I want to lock critical sections of my code using a global locking construct (this), that is available to any object that can access "this"(the object in question). Here is another implementation of the IConsumer that will not suffer from the safe problems as the NotSoSafeConsumer:

 

 

public class SafeConsumer : IConsumer { private object lockObject = new object(); public void DoSomething() { lock(lockObject) { Console.WriteLine("DoSomething"); Thread.Sleep(8000); } } public void DoSomethingElse() { lock(lockObject) { Console.WriteLine("DoSomethingElse"); Thread.Sleep(8000); } } }

If I replace the code in the main method with the following:

 

public static void Main() { LockAndWorkWith(new SafeConsumer()); Console.ReadLine(); }

You will notice that the code now works. I have made no changes to the LockAndWorkWith method, it is still acquiring a lock on the object itself. The object is unaffected by this now because it is using a private locking construct that no other class has access to.

There are lots more interesting locking mechanisms available in .Net such as Mutexes, Semaphores, WaitHandles etc. A large percentage of people have their needs satisfied by taking advantage of the Monitor class, which can actually provide all of the functionality of the other classes when used properly. A larger percentage of people accomplish their simple locking schemes by making use of the lock keyword. If you are going to do that, I suggest making the small change required to protect your "mutex" from the outside world.

Comments [1] | | # 
 Wednesday, August 23, 2006
Wednesday, August 23, 2006 7:06:14 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Agile | C Sharp )

After talking with a lot of people who have been unable to successfully download Part 1 of the TDD series, I decided I would post a link where people can download the first video again.

In order to watch this movie (offline), you will need to make sure you download the Swiff Player, for offline viewing of the flash movie.

I know it has been a while since the first video. I have finished recording the second movie and will be posting it in a couple of days to give people a chance to get back into the rhythm of where things will be going.

You can download the movie here (right click and Save As, if you want to save it to your hard drive).

During the course of these episodes you will be exposed to different ways of utilizing TDD practices along with tools that support TDD. If you do not have it already, you should download a copy of ReSharper 2.0 to follow along with what I am doing!!

Comments [4] | | # 
 Monday, August 21, 2006
Monday, August 21, 2006 12:57:35 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Tools )
A couple of people have been interested in grabbing the latest build of NMock2 so that they can give this "Mock Object Thing" a whirl. There is also a bit of confusion about where the NMock2 codebase actually resides.

If you want to download the latest build you can go here for more information.

Comments [5] | | # 
 Monday, July 03, 2006
Monday, July 03, 2006 11:55:58 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Agile | C Sharp | ScreenCasts )

Thanks to everyone who has provided awesome feedback to the current set of posts and screencast. My family and I are going on vacation tomorrow; so this will most likely be my last post for the next 2 weeks. I am making a request for people who are either following along with the screencast or interested in applying TDD to do the following:

  • Submit requests for features you would like to see implemented in the sample application
  • Submit aspx pages (no codebehind), that contain layouts for a screen(s) you want to see implemented using TDD
  • High level client centric use cases

Here are my reasonings for this request. I have been practicing TDD for 3 years. I have been involved in the development of many applications of all shapes and sizes and technologies utilizing TDD methods. Unfortunately, I can’t bring most of you with me onto these projects (although you could bring me onto yours!!). Instead of me coming up with fictitious scenarios and features, I am counting on my readers to take the place of the client and help drive out the functionality of this “fictitious!!” application. With the submission of high-level use cases, combined (hopefully) with screen prototypes; this provides us with a scenario which is typical of well-run agile environments. A majority of the projects I have worked on have followed this approach, going so far as having the analysts creating screen mockups using plain old powerpoint!! Once the screen mockups and high level use cases are in hand, I can take the use case and break it down into measurable tasks that will become focal points for driving out small pieces of functionality using TDD.

I want this series of podcasts to become one of the places where people who are interested in seeing TDD practically applied to turn to. To do that successfully I need to depend on my readership to help drive the direction of the project. That way I will be providing information that will hopefully convey TDD in a meaningful,pragmatic way.

Thanks and get those requests in!!

Comments [10] | | # 
 Wednesday, June 28, 2006
Wednesday, June 28, 2006 10:53:32 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns | ScreenCasts )

For those of you who are following along with my Applied TDD series there is one refactoring I forgot to do yesterday:

            using (mockery.Ordered())

            {

                Expect.Call(mockTask.GetAllContacts()).Return(mockResults);

                mockView.Contacts = mockResults;

            }

Notice the bolded code. It used to read mockView.Employees. Halfway through the session I decided to first tackle displaying a list of contacts and not employees.

 

Comments [0] | | # 
 Tuesday, June 27, 2006
Tuesday, June 27, 2006 7:56:24 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns | ScreenCasts )

I have just finished recording the second session for the ATDD series. The video is approximately 37minutes in length. In this session all that I focus on is getting a presenter and accompanying view working to display a list of Contacts in the AdventureWorks database. Topics that are introduced are:

  • Constructor based dependency injection
  • Interface based programming
  • RhinoMocks for creating mock objects

The completed code and movie are in this torrent.

Any feedback/comments would be greatly appreciated.

Comments [21] | | # 
 Sunday, June 25, 2006
Saturday, June 24, 2006 11:09:23 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

Geoff Stockham asked a good question on my "Dark Side Of Declaritive Databinding" post. My comments for that post got all messed up so I am reposting the question for everyone to view, along with the answer:

Q:JP, I've just been flicking through the Wrox ASP.NET MVP Hacks book, and one of the sections is about inheriting from the built-in data sources (such as ObjectDataSuurce) to create more specific domain-based data sources. This set me to thinking that this may be a way to get a "best of both worlds" approach of testability and ease of use. I haven't looked into it yet, but wondered if this might be the way you were thinking?

A: Once you start watching the series that I will be posting on applied test driven development, you will see why I have not found a need to take advantage of controls such as the object data source control. I am not discounting it as a viable solution to build apps with; it is just not the solution I go with. A decent MVP implementation coupled with test driven development, usually leads me down a path that diverges quite far from the solution offered by the object data source and the like.

Comments [0] | | # 
 Saturday, June 24, 2006
Saturday, June 24, 2006 10:33:33 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns )

Hey everyone. I know a lot of people have been waiting patiently for this series, and I don’t want to disappoint. I was sitting down to write entry number 2 and I realized that a lot of the feel and flow can get lost when I write a test, write some code etc, and then write up what I did. I really want to give people a feel for how the process actually works. To this end, I am going to be doing the rest of the series as a set of videos (with accompanying code) that people can follow along and watch. This will give people a much better idea of how TDD actually works, and over the course of the next couple of months, you will get to see the construction of a fairly non-trivial application.

I have to once again apologize for the delay, as I have been extremely busy as of late. I will not be doing any posting whatsoever during the first 3 weeks of July, as my family and I will be heading out for a big vacation!!

I hope to get the first video out by the end of Monday.

Thanks

Comments [3] | | # 
 Friday, June 23, 2006
Friday, June 23, 2006 9:41:09 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )
Most people who have talked/worked with me know that I am not the biggest fan of the demoware databinding techniques. When choosing to implement databinding in your application you have to decide what you will use as a data source. Of the many sources of data that can be bound to, the most common are

 

-DataSets

-XML

      -Custom Objects

 

I am going to (eventually) focus in particular on the use of the Custom object scenario. I will, however, start by using datasets as for the purpose of contrasting it to my approach. In my first attempt at databinding I will utilize some of the new controls made available in ASP.Net 2.0, namely the new Data Source Controls. Here is the markup required to configure the SqlDataSource control as well as an accompanying gridview to display the information.

 

 

<asp:SqlDataSource     ID="customersDataSource"

      runat="server"

         ConnectionString="<%$ ConnectionStrings:DatabaseConnection %>"

         SelectCommand="SELECT * FROM Customers" />

   <asp:GridView ID="customersGridView" runat="server" DataSourceID="customersDataSource"

            AutoGenerateColumns="false">

            <Columns>

                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"/>

                <asp:BoundField DataField="ContactName" HeaderText="ContactName"/>

                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"/>

                <asp:BoundField DataField="Address" HeaderText="Address"/>

                <asp:BoundField DataField="City" HeaderText="City"/>

                <asp:BoundField DataField="Region" HeaderText="Region"/>

                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"/>

                <asp:BoundField DataField="Country" HeaderText="Country"/>

                <asp:BoundField DataField="Phone" HeaderText="Phone"/>

                <asp:BoundField DataField="Fax" HeaderText="Fax"/>  

            </Columns>

        </asp:GridView>

 

And here is the app in action:

 

ScreenShot1

On the surface this all looks great. I’ve developed a fully data driven web page in under 2 minutes and didn’t have to type a single line of code. What could be wrong with that?

 

First, the use of the SqlDataSource control requires that the view have initimate knowledge of the database. The view is responsible for determining where to pull the data from as well as how to display that data. And if it were not for the fact that the connection string was stored in a configuration file, then it would also be responsible for providing a connection string used to connect to the database. This is just plain old poor separation of responsibility.

 

Second and no less important. One of the biggest problems with this method of databinding is the fact that you have to run the application in order to verify that the databinding will work. I’ll prove this by making a small change to the db schema. I’m going to change the name of the “Customers” table to “Customer”. I’ve made the change and rebuilt the db (using Nant of course!!).

 

 

Now I’ll run the app.

 

invalidobject

 

Ouch. And to add insult to injury; the only reason I found this error was by running the app and navigating to the page in question. Not efficient.

 

This is all too common a scenario I experience when going in to mentor teams of developers who are strong proponents of a data-driven approach to application development. One small change can cause ripple effects which are often not realized until the application is run. This is a very slow process and is not conducive to rapid, confident development of application functionality. In future installments I will talk about ways to handle this issue with a bit more style and grace, using a TDD perspective!!

kick it on dotnetkicks.com
Comments [2] | | # 
 Monday, June 19, 2006
Monday, June 19, 2006 9:33:55 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns )

I had an interesting comment to a previous post I made about validation rules:

I'm actually leaning toward limiting the use of interfaces... and here's why.

If your interface defines every aspect of the concrete class, then what's the benefit? I'm guessing you'll say mocking, which is a valid concern. While mocking is a useful testing technique, you can still effectively test the behaviour of your classes.

Interfaces aren't objects, so they do not get the benefits of System.object overrides, such as Equals() or ToString(). I'm all in favor of using interfaces where they are defined well and WILL be reused, but I'd stick with a base class until refactoring proves otherwise.

A colleague of mine suggests to use interfaces for behavior only. He further suggests that defining properties inside of interfaces is a full-on Code Smell.

I'm not 100% sure I agree with him on that, but I do believe that interfaces should focus on behavior, not on non-functional aspects like Name or Id.

All an interface is, is a contract that defines the expected behaviours/attributes an object is supposed to implement (remember, implementing may not necessarily mean defining a body for the method/property itself. I definitely disagree with the statement that interfaces should contain only methods. Although lots of the framework classes leave a lot of room to the imagination, I could name a handful of clean interfaces in the framework that make use of a interfaces ability to contain properties,methods, and events.

I want to stress a point here, in the .Net world we have gotten hung up on the term interface. Remember that this term is overloaded. There is the concept of an interface, but there is also a concept in C# of an interface language construct. You can program to an interface without needing to actually use an interface. This is what people often achieve using a supertype. The fact that you can program to an interface using both an "interface" construct and a "class" construct is irrelevant. The benefit of either approach is to make use of polymorphism by programming to an interface/supertype so that code in the system is not (as much as possible) tied to concrete implementations. Coding to an interface/supertype allows the client code consuming the objects to not care about the object that it is working with, only that it supports a certain 'interface'.

I personally err to the side of using interface constructs to drive out the initial implementations, and then will refactor to a supertype in the event that it is necessary. And even then, I think people often jump to the use of inheritance way to quickly.

Rich interfaces are almost a necessity when you are creating component based systems utilizing the separated interface pattern. In these scenarios you may not want you client to have any knowledge whatsoever of the implementation code you are putting in place. Interface constructs are a great clean way to separate the client code from the actual server implementations (think remoting).

This whole question about interfaces vs abstract classes leads me to leave you with 2 OO/design thoughts to ponder:

  • Favour object composition over concrete inheritance
  • Code to interfaces (interface construct/abstract classes) not implementations 
Comments [6] | | # 
 Friday, June 16, 2006
Friday, June 16, 2006 6:27:34 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

I had a great question from Andy MacDonald about my previous post on validation in the domain layer:

Q: Is there anyway that the rule delegates can be stored in a database/xml file as this would provide a really powerful way of implementing ever shifting business rules about age and so forth without having to recompile any of the layers in the application (as well as supporting context rules)?

While I am not going to dive into the question today, I am going to give Andy and others some thoughts to chew on (which should actually enable them to proceed without waiting for part 2 of this post!):

  • A couple of questions you need to ask yourself before answering this question are as follows:
    • “How often does a given rule change?”
    • “Is the end user going to be provided a mechanism to dynamically alter a given rule”?

I am asking these question because I want you to realize that if a rule does not change very often, and the user has not requested a UI that will allow them to manipulate the rule, the effort involved in making the rule more dynamic may not be worth the effort. If you already have an automated build in place, one that allows you to deploy a new version of the app by just typing in the name of a target at the command line. Then the effort involved to “change” a rule every once in a while is next to nothing. Now remember, this deploy on the fly model also works for Windows applications, if you are using a deployment model that allows for automatic updating of the clients (ex. ClickOnce / Updater components). If this is the case, changing a rule involves a couple of steps:

  • Update any tests that utilize the rule directly
  • Update the rule
  • Run the tests
  • Deploy the app

I am suggesting this for infrequent rule changes as it is still a viable option. Being a programmer, and a lazy one at that, makes me try to look for the simplest solution first.

Of course, there are lots of situations where rules can change daily, and different installations of the system utilize slight variations on rules. In these situations, you need to isolate the rules that change frequently from the ones that don’t. For these “dynamic” rules, you can take advantage of the IBusinessRule<T> interface and create implementations that are parameterized with information from external sources. In the example that Andy talks about with the age example, a dynamic rule could be created to take in the minimum and maximum age of people allowed to vote:

 

 

public class ValidVotingAgeRule : IBusinessRule<Vote> { private int minimumAge; private int maximumAge; public ValidVotingAgeRule(int minimumAge, int maximumAge) { this.minimumAge = minimumAge; this.maximumAge = maximumAge; } public bool IsSatisfiedBy(Vote item) { return item.voter.Age >= minimumAge && item.voter.Age <= maximumAge; } public string Name { get { return "Valid Voting Age"; } } public string Description { get { return string.Format("Must be between {0} - {1} to vote", minimumAge, maximumAge); } } }

 

Again, I’ve said it before (maybe not on this blog) and I’ll say it again. I love interfaces. Here I have created a dynamic rule called ValidVotingRule, you construct it using a minimumAge and maximumAge (which could easily come from the database. Notice how even the description is now parameterized based on the min and max age!! Notice also, that it implements the IBusinessRule<Vote> interface, which means that it could be added to any BusinessRule<Vote> instance, which gets passed into the constructor of a Vote class!!

Hopefully this gives Andy and others, some other things to think about!!

kick it on dotnetkicks.com
Comments [8] | | # 
Thursday, June 15, 2006 11:42:11 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

It has been quite a while since I posted the first part of this scenario. I left off in a pretty good place, but now I need to revisit and solve the validation problems that I posed in the first entry:

  • Must be between the age of 18 – 75 to vote (yes there is an upper limit!!)
  • Must live in the country the candidate is running for

As well as the rules for voting, upon submitting a vote the person voting has to supply all of the required voter information:

  • FirstName
  • LastName
  • Age
  • Address
  • Gender
  • CountryOfResidence

We left off with having a Person domain object be able to perform validation. We now need to expand the scope to the vote class. A vote consists of both a Candidate and a Person. With the framework that is already in place, it becomes trivial to add the necessary validation for a Vote Class.

public sealed class Rules { private Rules() { } public static IBusinessRule<Vote> Age { get { return new BusinessRule<Vote>("Age", "Must be between 18 - 75 to vote", delegate(Vote vote) { return vote.voter.Age >= 18 && vote.voter.Age <= 75; }); } } public static IBusinessRule<Vote> Country { get { return new BusinessRule<Vote>("Country", "Must live in same country as Candidate", delegate(Vote vote) { return vote.voter.CountryOfResidence.Equals(vote.candidate.CountryOfResidence); }); } } public static IBusinessRuleSet Default { get { return new BusinessRuleSet<Vote>(Age,Country); } } }

This Rules class lives as a nested class inside of the Vote class. You will notice that the validation is fairly trivial. One thing that I have done is decrease the strong typing of the IBusinessRuleSet interface. Why? I want to have a layer supertype for all of my domain object that contains an IsValid property, and that will also invoke the appropriate BrokenBy method on the rule set. I accomplish this with minimum change required to the actual BusinessRuleSet class by changing the interface of IBusinessRuleSet<T> to the following:

 

public interface IBusinessRuleSet { IBusinessRuleSet BrokenBy(IDomainObject item); bool Contains(IRule rule); int Count { get; } IList<string> Messages { get; } bool IsEmpty { get;} }

With that change in place it means I now require a layer supertype for all of my domain objects:

 

public class DomainObject : IDomainObject { private IBusinessRuleSet rules; public DomainObject(IBusinessRuleSet rules) { this.rules = rules; } public IBusinessRuleSet Validate() { return rules.BrokenBy(this); } public bool IsValid { get { return Validate().IsEmpty; } } }

Notice how all DomainObjects will be constructed with a set of rules against which validation will be executed (great for testing, as well as loosening validation depending on the context). The layer supertype also takes care of performing the validation against itself. Even though it looks like I have lost some strong typing, this is not the case, as the main implementer of the IBusinessRuleSet interface is the BusinessRuleSet<T> class. It is still a generic class, and look at how it now implements the BrokenBy method:

 

public IBusinessRuleSet BrokenBy(IDomainObject item) { IList<IBusinessRule<T>> brokenRules = new List<IBusinessRule<T>>(); foreach (IBusinessRule<T> rule in rules) { if (! rule.IsSatisfiedBy((T) item)) { brokenRules.Add(rule); } } return new BusinessRuleSet<T>(brokenRules); }

Notice, that the BrokenBy method still ensures that the type of “item” is the type that it expects to be able to work with. It does this by performing a cast using the type T that it was constructed to hold rules for. Tests that exercise this method for specific types of objects will fail if the object passed into the BrokenBy call is not of type T.

So by making a small change to the interface we have now allowed for any new domain object  to now inherit from a layer supertype and have and its disposal a Validate and IsValid methods. Here is the first test that I wrote when it came to validating the rules for a vote:

  

[Test] public void ShouldVerifyVoterLivesInSameCountryAsCandidate() { IPerson person = new Person("JP", "Boodhoo", "Test", 20, Country.CANADA, Gender.MALE); Candidate candidate = new Candidate("JP", "Boodhoo", "Test", 20, Country.CANADA, Gender.MALE, Party.CONSERVATIVE); IPerson notInSameCountryAsCandidate = new Person("JP", "Boodhoo", "Test", 20, Country.USA, Gender.MALE); Vote vote = new Vote(person, candidate); Assert.IsTrue(vote.IsValid); vote = new Vote(notInSameCountryAsCandidate, candidate); Assert.IsFalse(vote.IsValid); }

As you can see, small focused tests can help drive out lots of functionality. Last but not least is the introduction of a PollingStation class, that makes use of all of the code we have put into place:

 

 

public class PollingStation { private IList<Vote> invalidVotes; private IList<Vote> validVotes; private IList<IPerson> incompleteVoters; private int voteNumber; public PollingStation() { invalidVotes = new List<Vote>(); validVotes = new List<Vote>(); incompleteVoters = new List<IPerson>(); } public void RegisterVoteFor(IPerson person,ICandidate candidate) { if (person.IsValid) { Vote vote = new Vote(++voteNumber,person, candidate); if (vote.IsValid) { validVotes.Add(vote); } else { invalidVotes.Add(vote); } } else { incompleteVoters.Add(person); } } public IList<Vote> InvalidVotes { get { return invalidVotes; } } public IList<Vote> ValidVotes { get { return validVotes; } } public IList<IPerson> IncompleteVoters { get { return incompleteVoters; } } }

Here is the test that I wrote to drive out the usage of the PollingStation class:

 

[Test] public void ShouldRegisterPolls() { ICandidate liberalCandidate = new Candidate("Lib", "Lib", "LibAddress", 30, Country.CANADA, Gender.MALE, Party.LIBERAL); ICandidate conservativeCandidate = new Candidate("Lib", "Lib", "LibAddress", 30, Country.CANADA, Gender.MALE, Party.CONSERVATIVE); ICandidate ndpCandidate = new Candidate("Lib", "Lib", "LibAddress", 30, Country.CANADA, Gender.MALE, Party.NDP); PollingStation station = new PollingStation(); IPerson tooYoungToVote = new Person("DF", "DF", "dfd", 17, Country.CANADA, Gender.MALE); IPerson tooOldToVote = new Person("DF", "DF", "dfd", 78, Country.CANADA, Gender.MALE); IPerson livesInDifferentCountry = new Person("DF", "DF", "dfd", 18, Country.USA, Gender.MALE); IPerson incompleteInfo = new Person("", "DF", "dfd", 35, Country.CANADA, Gender.MALE); IPerson liberalVoter = new Person("fd", "DF", "dfd", 35, Country.CANADA, Gender.MALE); IPerson conservativeVoter = new Person("fd", "DF", "dfd", 35, Country.CANADA, Gender.MALE); IPerson ndpVoter = new Person("fd", "DF", "dfd", 35, Country.CANADA, Gender.MALE); station.RegisterVoteFor(tooYoungToVote,liberalCandidate); station.RegisterVoteFor(tooOldToVote,liberalCandidate); station.RegisterVoteFor(livesInDifferentCountry,liberalCandidate); station.RegisterVoteFor(incompleteInfo,liberalCandidate); station.RegisterVoteFor(liberalVoter,liberalCandidate); station.RegisterVoteFor(conservativeVoter,conservativeCandidate); station.RegisterVoteFor(ndpVoter,ndpCandidate); Assert.AreEqual(1,station.IncompleteVoters.Count); Assert.AreEqual(3,station.InvalidVotes.Count); Assert.AreEqual(3,station.ValidVotes.Count); OutputStats<IPerson>("Incomplete Voters", station.IncompleteVoters); OutputStats<Vote>("Invalid Votes", station.InvalidVotes); }

Are you wondering what is going on in the OutputStats<T> method. This was just something I put in so you could visualise the validation errors. When this test is run the following will be output to the console window:

 

Incomplete Voters
	First name is required

Invalid Votes
	Must be between 18 - 75 to vote

	Must be between 18 - 75 to vote

	Must live in same country as Candidate

As is common lately, the source code for this completed project is here. And once again, comments are always encouraged and appreciated.

JP

kick it on dotnetkicks.com
Comments [6] | | # 
 Wednesday, June 07, 2006
Wednesday, June 07, 2006 3:36:14 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

As cool as some of the new features in ASP.Net are, there are some simple interfaces that can open a door to a boatload of functionality for your web applications. I am talking specifically about the IHttpModule and IHttpHandler interfaces. Lots of developers are aware of the interesting problems that you can solve (cleanly) by taking advantage of these interfaces. Lots, however, are still in the mindset that to add new pieces of functionality that an .aspx / .ascx file has to be involved in the picture somewhere. This is just not the case. I am not going to rehash information that is already out there for consumption. Instead I will direct you to the site of James Kovacs, who has just published a great writeup on using an IHttpModule implementation for dealing with Site Availability issues.

If you are not familiar with these interfaces, read the article (along with his article on the ImpostorHttpModule), and start thinking of ways you can use these interfaces in your application. Some examples that I have used in the past are:

  • IHttpHandler implementation that watermarks all images in the application with a company logo
  • IHttpHandler implementation for doing 2 step transform/view implementation without the need for an aspx page
  • Pre 2.0, IHttpHandler for securing non asp.net releated web resources
  • IHttpModule implementation for creating strongly typed payload objects and attaching them to the executing request
  • IHttpModule implementation for custom authorization
  • IHttpHandler implementation for retrieving images from a database

Just think of the things you could do!!

kick it on dotnetkicks.com
Comments [3] | | # 
 Friday, June 02, 2006
Friday, June 02, 2006 10:45:24 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Agile | C Sharp | Patterns | VS2005 )

I have been promising for a long time to start a series that details the creation of a project similar to the one that I presented on my first set of DNRTv episodes. Here is the beginning of that promise!! The goals of this series is to develop a highly testable web application that demonstrates a lot of the principles that can be utilised when developing a web (or any) application using Test Driven Development. I have chosen to base the examples around the new AdventureWorks database. Why AdventureWorks you may ask? Since it is the successor to Northwind, you are going to see (or already have) many examples/demos that utilise it as a DB. It stands to reason that a lot of the techniques and approaches that I am going to show you, will be counter to what is in the mainstream MS world right now. This is not a bad thing, it is always good to open your eyes to new ways to accomplish tasks!!

In this episode, I am just going to start by discussing solution structure for the project as well as the building of the database. This is by no means meant to be an introduction to NAnt, if you want to see how NAnt can be utilised as build tool for your projects then read my NAnt Start Series. Download this zip file and you will be able to start off at the same point that I am starting at. Drop the zip file in a folder you typically do your development and unzip it to that location:

Unzipping

 

Once you have extracted the contents of the build file there should now be a directory named adventureworks.

UnzippedFolder

The first thing you will need to do is go into the adventureworks directory (from this point referred to as the trunk) and copy the local.properties.xml.template file to a file named local.properties.xml (don’t delete the local.properties.xml.template file):

LocalProperties

With that taken care of, you will need to go in and edit the local.properties.xml file (not the template) and change any settings that may be specific to your machine:

<?xml version="1.0"?>
<properties>
 <property name="sqlToolsFolder" value="C:\Program Files\Microsoft SQL Server\90\Tools\Binn"/>
 <property name="osql.ConnectionString" value="-E"/>
 <property name="initial.catalog" value="AdventureWorks"/>
 <property name="config.ConnectionString" value="data source=(local);Integrated Security=SSPI;Initial Catalog=${initial.catalog}"/> 
 <property name="database.path" value="C:\root\development\databases" />
 <property name="osql.exe"  value="${sqlToolsFolder}\osql.exe" />
</properties>

Pay special attention to the database.path property. You can change the value to point to a different directory on your machine. Make sure that the folder exists, as the build process does not create this folder for you (it could, but I chose not to). Another setting that might vary on your machine is the osql.ConnectionString property. This is basically the connection parameters that you would need to specify if you used OSQL from the command line. For me, I use integrated windows authentication so I can just use the -E switch. You will have to experiment with your settings (you might even need to specify a server name etc).

Once you have changed the properties you can open up a command prompt pointing to your trunk directory. From the command line run the command “build run”. If all of your settings are configured properly (and you have a local instance of IIS), you should see a blank web page pop up in your browser:

DefaultASPX

Last but not least, once you have closed down the browser, you can run the following command from the command line “build builddb”. This will copy the adventureworks database files located in the [trunk]\sql\original directory and place them in the directory that you specified in the “database.path” property of your local configuration file. It will also run a sp_attach_db command and it will name the database using the name you provided in the “initial.catalog” property of your local configuration file.

I have explicitly chosen not to build the DB from scripts, why? I had a hard time finding any original SQL scripts for the AVWorks. If anyone feels like taking the time to create script files that we can use (as well as the accompanying seed data) please let me know.

The main build targets that we will be using during the course of these walkthroughs are “build test” and “build run”.

Let’s take a quick look at the initial solution structure (double click on the AdventureWorks.sln file, this is a VS2005 projects):

InitialSolution

So far we have a Web project, a Presentation project, and a Presentation.Test project. Pretty standard fare. Right now the 2 classes that are in each of the Presentation, and Presentation.Test project are just there so the “build test” target in the build file will execute properly. We will replace both of those classes with meaningful classes next week.

Ok, we are ready to start. Take a look around (there’s nothing much to see right now), read my NAnt Starter Series if you have’nt already. And most important, submit requests for what you would like to see in this project. Keep in mind that I am going to try and use it as a vehicle to teach both TDD and good development practices (design patterns, refactoring etc, OO). Next week I will start by building a screen similar to the one that I created for DNRTv, once I have gotten completely through that example we will have a fairly good ground from which to branch out from. I have already talked to a handful of people and have a good idea of what they would like to see demonstrated. If you have’nt got your request in, now is the time to do it. If you can’t comment on this blog post email me directly at bitwisejp@gmail.com.

Here are some ideas to get you thinking:

  • Manageable Databinding
  • Passing information between pages
  • Master/Detail pages
  • Managing master pages better
  • Ajax
  • Layered Architecture
  • Validation

 

Let the coding begin (almost!!).

kick it on dotnetkicks.com
Comments [5] | | # 
 Friday, May 26, 2006
Friday, May 26, 2006 2:23:44 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns )

I have been thinking for a while about coming up with a series of posts that talk about real world applications of many of the design patterns that get thrown around. I have been meaning to post about the decorator pattern for quite some time. I was trying to come up with an example that would practically demonstrate the Decorator pattern and then it hit me. An image browser. Here is the sample app in action:

MainForm

OpenDialogViewingPlainImage

As you can see, it is pretty standard fare. When the button is clicked, a file dialog browser will pop-up and the user will have the option to choose a file to display. If they pick a file the file will be displayed. If they don’t pick a file nothing will happen. The code-behind for the form is pretty simple:

public partial class ImageBrowser : Form, IImageBrowserView { private OpenFileDialog openFileDialog; private ImageBrowserPresenter presenter; public ImageBrowser() { InitializeComponent(); presenter = new ImageBrowserPresenter(this); openFileDialog = new OpenFileDialog(); HookupEventHandlers(); } private void HookupEventHandlers() { this.retrieveImageButton.Click += delegate { presenter.DisplayImage(); }; } public bool WatermarkRequired { get { return watermarkCheckBox.Checked; } } public string ImagePath { get { openFileDialog.ShowDialog(); return openFileDialog.FileName; } } public void Display(Image image) { this.pictureBox.Image = image; } }

As you can see, I am using the model view presenter, and the presenter has the responsibility of pushing an image to the view that the view will display. This article is not about the MVP so try not to get too hung up on it if you have not seen it before. As you can see from the code, the main work will be performed inside the DisplayImage method of the presenter. The code for the presenter turns out to be very trivial: 

public class ImageBrowserPresenter { private IImageBrowserView view; public ImageBrowserPresenter(IImageBrowserView view) { this.view = view; } public void DisplayImage() { string pathOfImageToDisplay = view.ImagePath; if (IsValid(pathOfImageToDisplay)) { view.Display(Bitmap.FromFile(pathOfImageToDisplay)); } } private bool IsValid(string imagePath) { return !string.IsNullOrEmpty(imagePath); } }

So what is going on here. When the view tells the presenter to “DisplayImage”, the presenter turns back around to the view and asks it for the path of the image that it should display:

string pathOfImageToDisplay = view.ImagePath;
 
 

The view (form) responds to this request by popping up a file open dialog and returning the filename of the dialog to the presenter:

 

public string ImagePath { get { openFileDialog.ShowDialog(); return openFileDialog.FileName; } }

The code in the form is actually feature complete for this example. There will be no changes required to make to the code behind to support new functionality (for this scenario). A scenario that people often run into for commercial web sites it needing to apply a water mark to an image so that people cannot just download their images and use them as their own. This is our first perfect candidate for the decorator pattern. We want to “Decorate” an image with a watermark, that brands it as our own.

What is the Decorator Pattern

Simply (and the decorator is a very simple,elegant pattern) the Decorator pattern allows us to attach additional responsibilities/behaviours to an object without the need for subclassing. The following class diagram shows the structure of a typical decorator implementation:

Decorator(taken from DoFactory.com)

One of the principles of the decorator pattern ensures that to the client, a decorator looks no different that the object it is decorating. In this scenario we want to decorate Images. The base class for Images in the framework (Bitmaps and Metafiles) is the System.Drawing.Image class. Unfortunately I can’t inherit from this as the constructor for an Image is internal. I also can’t inherit from Bitmap as that class is sealed. How can I decorate when I can’t create a Decorator that implements the same interface as the object it is decorating. Adding a small layer of indirection will solve this problem:

 

public interface ICoreImage { Image Picture { get; } }

I now have an interface that can be implemented by a class that really just wraps an image:

 

public class CoreImage : ICoreImage { private Image image; public CoreImage(Image image) { this.image = image; } public Image Picture { get { return image; } } }

As the saying goes "Another layer of indirection will solve any problem!!, now I have an interface that can be readily implemented by any class. Now, I promised that no changes would affect the code-behind of the form in anyway. To make use of this new class, I just need to change the presenter a little:

public void DisplayImage() { string pathOfImageToDisplay = view.ImagePath; if (IsValid(pathOfImageToDisplay)) { view.Display(GetImageFrom(pathOfImageToDisplay).Picture); } } private ICoreImage GetImageFrom(string pathOfImageToDisplay) { return new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); }

All I have done is introduced a method into the presenter that will retrieve an ICoreImage from a filename. Once the DisplayImage method retrieves the ICoreImage, it invokes the Picture property to return image data to the view. The current model of the application looks as follows:

initialmodel

We now have to deal with a new requirement. When the user has the “Watermark” checkbox checked, the image should display with a watermark rendered on it. To accomplish this new requirement we can come up with a decorator that will add the watermark to the image it is decorating. In this scenario I am only going to utilize a text based watermark. Options for a Watermark are encapsulated in a class called WatermarkOptions:

public class WatermarkOptions { private const int DEFAULT_SIZE = 26; private static readonly Font DEFAULT_FONT = new Font("Consolas", DEFAULT_SIZE, FontStyle.Bold, GraphicsUnit.Point); private Color color; private Font font; private string watermarkText; private Brush brush; private StringFormat format; public WatermarkOptions():this(DEFAULT_FONT,"SAMPLE",new StringFormat(StringFormatFlags.FitBlackBox),new SolidBrush(Color.Red)) { } public WatermarkOptions(Font font, string watermarkText,StringFormat format,Brush brush) { this.font = font; this.watermarkText = watermarkText; this.format = format; this.brush = brush; } public Font Font { get { return font; } } public string WatermarkText { get { return watermarkText; } } public Brush Brush { get { return brush; } } public StringFormat Format { get { return format; } } }

As you can see, all this class contains is different settings for a watermark. Notice the use of the overloaded constructor, which allows people to construct a watermark and settle with defaults. To make use of this class we will create a “WatermarkDecorator”. The decorator (from the clients point of view) has to look the same as the object it is decorating. In our case, the client is the “DisplayImage” method of the presenter. Because we have the ICoreImage interface, I can utilize it to create the WatermarkDecorator:

public class WatermarkDecorator : ICoreImage { private const int BORDER = 4; private ICoreImage coreImageToWatermark; private readonly WatermarkOptions options; public WatermarkDecorator(ICoreImage coreImageToWatermark) : this(coreImageToWatermark, new WatermarkOptions()) { } public WatermarkDecorator(ICoreImage coreImageToWatermark, WatermarkOptions options) { this.coreImageToWatermark = coreImageToWatermark; this.options = options; } public Image Picture { get { return DecorateWithWatermark(coreImageToWatermark.Picture); } } private Image DecorateWithWatermark(Image picture) { using (Graphics graphics = Graphics.FromImage(picture)) { SizeF textSize = graphics.MeasureString(options.WatermarkText, options.Font, picture.Width - BORDER, options.Format); RectangleF textRectangle = new RectangleF(BORDER, BORDER, picture.Width, textSize.Height); graphics.DrawString(options.WatermarkText, options.Font, options.Brush, textRectangle, options.Format); graphics.Flush(); return picture; } } }

Now you can see the Decorator pattern in action. Decorators always need to know about the object they are adding behaviour/functionality to, a great way to accomplish this is through constructor injection. When constructed with only an image, the decorator makes use of the parameterless WatermarkOptions constructor, to create options with default settings. Remember, decorators are adding new functionality to existing objects at runtime, the magic of adding the watermark happens when the Picture property on the decorator gets invoked. Instead of just immediately delegating to the object being decorated, it invokes the “DecorateWithWatermark” method, passing in the image retrieved from the underlying “decorated” ICoreImage. The DecorateWithWatermark method contains the logic to apply a watermark to the image, making use of the WatermarkOptions that got passed in. I am not going to delve into the details of the graphics jargon, for the most part it is pretty simple.

Ok, so I have this decorator, how do I use it? Switching back to the method in the presenter that actually instantiates the CoreImage, I can apply the decorator quickly by performing a quick check as to whether the user wants Watermarks applied:

 

private ICoreImage GetImageFrom(string pathOfImageToDisplay) { ICoreImage image = new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); return (view.WatermarkRequired ? new WatermarkDecorator(image) : image); }

You will note that the DisplayImage method in the presenter did not need to change at all, why? Because all it cared about was when it called the GetImageFrom method, was that it received an ICoreImage implementation, it doesn't know or care if it is a decorator. If I run the application now any files that are opened while the checkbox is checked will have a watermark drawn over them:

imageshownwithwatermark

Our revised class diagram looks like so:

revisedmodel

To finish off, a decorator also doesn't care what it is decorating either, as long as the object that it is decorating implements the same interface as what it does. So if the customer came to you all of a sudden and said “Regardless of whether the image has a watermark or not, we want a border around all images”, you could satisfy that requirement with another discrete decorator:

 

public class BorderDecorator : ICoreImage { private const int PEN_WIDTH = 10; private ICoreImage imageToDecorate; public BorderDecorator(ICoreImage imageToDecorate) { this.imageToDecorate = imageToDecorate; } public Image Picture { get { return WrapWithBorder(imageToDecorate.Picture); } } private Image WrapWithBorder(Image picture) { using (Graphics graphics = Graphics.FromImage(picture)) { RectangleF border = new RectangleF(0, 0, picture.Size.Width, picture.Size.Height); Pen pen = new Pen(new SolidBrush(Color.Black), PEN_WIDTH); graphics.DrawRectangle(pen,border.X,border.Y,border.Width,border.Height); graphics.Flush(); } return picture; } }

To ensure that all images have borders, I can just apply the new decorator to the existing decorator!!:

 

private ICoreImage GetImageFrom(string pathOfImageToDisplay) { ICoreImage image = new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); return new BorderDecorator(view.WatermarkRequired ? new WatermarkDecorator(image) : image); }

With that change applied, if I run the application now, all images (watermarked or not) will have a border around them:

plainimagewithborder  watermarkedimagewithborder

Now of course. In this example I had the presenter explicitly wrap the objects with decorators, but think about the flexibility of introducing factories/composite decorators that would allow the code in the presenter to stay static also. But those are patterns for another day!!

If anyone wants the source for this entry, please contact me.

TODO
Comments [5] | | # 
 Thursday, May 25, 2006
Thursday, May 25, 2006 8:14:51 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Tools )

It has been quite a bit of time since the last installment of the NAnt Starter Series. We left off being able to successfully compile and test the main libraries of our application, and we progressed to bringing the database into the fold and looked at ways to manage the database in a multiple developer environment. In this installment we are going to talk about compiling and distributing the web portion of the application. Specifically, we are going to write a NAnt target that will build and deploy our entire web application into a directory that can be immediately deployed to a remote server if need be. Take a look at the current solution structure that is set up:

SolutionStructure

As you can see from the diagram, in this example I am going to be using the web-site project model, as opposed to the newly available Web Application Project model. You will quickly see that the only file that exists in this project is the ViewCustomers.aspx file. I am not using any of the new directories like the App_Code, App_Data etc. My web project should be extremely simple, consisting of purely UI elements like:

– Web Pages

– User Controls

– JavaScript Libraries

– Styles and Templates

 

By limiting the amount of code that is placed in this project, I can write unit tests against the real objects that will actually get work done. These objects , of course, live in projects separate from the web application. You might be asking yourself “Where is the web.config file?”. That file is actually a template file that will have pre-processing done on it during the build process. The contents of that file before processing look as follows:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">       
 <appSettings>  
  <add key="DatabaseConnection" value="SqlServer"/>
 </appSettings>
 
 <connectionStrings>
  <add name="SqlServer"
   connectionString="@CONFIG_CONNECTION_STRING@" 
   providerName="System.Data.SqlClient"
  />
 </connectionStrings>
 <system.web>
  <compilation debug="true"/>
  <authentication mode="Windows"/>
   <authorization>
       <deny users="?" />
   </authorization>
  <customErrors mode="Off" />
  <sessionState mode="Off" />  
 </system.web> 
</configuration>

If you look at the connectionStrings element, you will notice that the SqlServer connectionString is set up as a replaceable token in the Web.config.template file. Again, this is to ensure that at deploy time, the connectionString will be replaced with the appropriate string based on the environment that is getting deployed to.

Ok, let’s turn our attention to the process of building and deploying the application. Take a look at a new target that will compile our web application from inside of NAnt:

 <target name="asp.compile" description="Compiles the webapp" depends="init, compile">
        <delete dir="build\dist" if="${directory::exists('build\dist')}" />
       
        <loadtasks assembly="tools\nant\NAnt.Contrib.Tasks.dll" />
 
 <delete>
     <fileset basedir="build\aspprecompile">
  <include name="**\*" />
     </fileset>
 </delete>
        <copy todir="build\aspprecompile">
            <fileset basedir="src\app\DotNetRocks.Web.UI">
                <include name="*" />
                <include name="images\**\*.*" />
                <include name="javascript\**\*.js" />
            </fileset>
        </copy>

        <copy todir="build\aspprecompile\bin">
            <fileset basedir="build">
                <include name="*.dll" />
            </fileset>
        </copy>

        <mkiisdir dirpath="build\aspprecompile" vdirname="aspprecompile" />
        <exec program="C:\WINDOWS\Microsoft.NET\Framework\${framework.version}\aspnet_compiler.exe"
  useruntimeengine="true">
            <arg value="-p" />
            <arg value="build\aspprecompile" />
            <arg value="-v" />
            <arg value="aspprecompile" />
            <arg value="build\dist" />
        </exec>
        <deliisdir vdirname="aspprecompile" />       
    </target>

Whoa, there is a lot going on here so let’s break it down piece by piece. We are making use of the “depends” attribute to ensure that the asp.compile target cannot be run until all of the supporting libraries have been compiled:

                         target name="asp.compile" description="Compiles the webapp" depends="init, compile"

Don’t worry about the deletes that are happening at the beginning of the target, they are just ensuring that cleanup happens from a prior build process. The first step to compiling the ASP application is copying all of the files that the ASP.Net precompiler will require for compilation into a transient build directory (I don’t want to affect my main web project directory in any way whatsoever):

<copy todir="build\aspprecompile">
            <fileset basedir="src\app\DotNetRocks.Web.UI">
                <include name="*" />
                <include name="images\**\*.*" />
                <include name="javascript\**\*.js" />
            </fileset>
</copy>

I continue by copying all of the assemblies that the web project uses into an appropriate bin directory under the aspprecompile directory. Again, I am just pulling from the build directory any dll’s that would have been created during the running of the compile target:

 <copy todir="build\aspprecompile\bin">
            <fileset basedir="build">
                <include name="*.dll" />
            </fileset>
 </copy>

If I were to stop the target there my build directory would look as follows:

BuildDirectory

The aspprecompile directory would look like this:

AspprecompileDirectory

And the aspprecompiles bin directory would look like this:

AspPrecompileBinDirectory

You will see that I am copying pretty much all of the files from the DotNetRocks.Web.UI directory into this transient precompile directory. That’s right every file, including code-behind files. Notice how at the beginning of the target I used the loadtasks task :

<loadtasks assembly="tools\nant\NAnt.Contrib.Tasks.dll" />

LoadTasks will load any custom NAnt tasks that are contained in the named assembly and make them available to you for use during the build process. The NAntContrib library, is an open source library that contains a plethora of tasks that you can make use of during your own build processes. The ones that I need specifically are the ones that let me manipulate IIS Virtual Directories. I create a new virtual directory called aspprecompile that will point to the build\aspprecompile directory:

 <mkiisdir dirpath="build\aspprecompile" vdirname="aspprecompile" />

All right the stage is set. The last time we compile a project we used the standard NAnt csc task that would compile a set of C# class files into a library. Even though there are cs files in the aspprecompile directory we cannot use the csc task to compile the web project. I need to take advantage of the ASP .Net precompiler to compile the web application for me. With .Net 2.0, you could actually deploy all of your *.cs files for the project into the web directory and the ASP.Net runtime would compile the cs files dynamically when the pages are requested. I am not a fan of this approach, I would rather just keep my source files out of the web directory completely. To allow you to do this, you have to take advantage of the ASP.Net precompiler. If you are not familiar with the ASP.Net precompiler you can read some more information about it here. I use the NAnt exec task to shell out to the asp.net precompiler to compile my site in place:

<exec program="C:\WINDOWS\Microsoft.NET\Framework\${framework.version}\aspnet_compiler.exe"
  useruntimeengine="true">
            <arg value="-p" />
            <arg value="build\aspprecompile" />
            <arg value="-v" />
            <arg value="aspprecompile" />
            <arg value="build\dist" />
        </exec>

 Notice I am using a modified method to pass parameters to the aspnet_compiler executable. The full commandline would expand to this:

aspnet_compiler.exe -p “build\aspprecompile” -v “aspprecompile” “build\dist”

The meaning of each of the arguments is a follows:

  • -p : Specifies the full network path or local disk path of the root directory that contains the application to be compiled. This option must be combined with the -v option.
  • -v : Specifies the virtual path of the application to be compiled
  • targetdir : This is not a named argument but if provided, specifies the directory to which the asp_compiler will place the final files for deployment

After running the target the build\aspprecompile directory looks no different that the before the compilation happened, but notice that a new directory has been added to the build directory:

DistDirectory

     The following screenshots show the contents of this directory:

    DistDirectoryContents   DistBinDirectoryContents

    Take a look at the interesting names that the aspnet_compiler generates for us!! Notice also, that although the aspprecompile directory contained a .cs file the the ViewCustomers.aspx page, the dist folder has no source files whatsoever!! The dist folder now contains everything that we would need to deploy to a production server. With the compilation safely taken care of I can go ahead and remove the temporary virtual directory I created for asp precompile purposes:

     <deliisdir vdirname="aspprecompile" />

    Again, the deliisdir task lives is a task that is defined in the NAntContrib library.

    To wrap it up, I can quickly add a target that will deploy the application to a local directory on my machine :

     

    <target name="deploy" depends="asp.compile">
            <deliisdir vdirname="DotNetRocks" failonerror="false" />
            <delete>
                <fileset basedir="deploy">
                    <include name="**/*" />               
                </fileset>
            </delete>
            <mkdir dir="deploy" />
            <copy todir="deploy">
                <fileset basedir="build\dist">
                    <include name="**\*" />               
                </fileset>
            </copy>
            <copy file="config\Web.Config" tofile="deploy\Web.config" /> 
            <mkiisdir dirpath="deploy" vdirname="DotNetRocks" authntlm="true" defaultdoc="Default.aspx" />
        </target> 

     

    I am not going to break this target down, as you have already seen all of the tasks that I am using. At the end of this target running I will be able to navigate to the ViewCustomers.aspx page by opening up my browser and typing in : http://localhost/DotNetRocks/ViewCustomers.aspx which brings me to:

    ViewCustomers

     

    TODO
    Comments [9] | | # 
     Friday, May 19, 2006
    Friday, May 19, 2006 1:45:19 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

    I have been receiving a lot of email's centered around the topic of validation in the domain layer. If you are a developer who is trying to utilize a rich domain layer in your applications, then you might have struggled with the whole issue of validation. Conceptually, most of us know how to perform validation using some predefined set of business rules. Unfortunately, the way the validation is implemented often leaves us with a solution where validation is scattered haphazardly throughout multiple layers in the application. Worse yet, is the case where validation is duplicated in multiple layers in the application, and changing a rule entails changing the code in multiple places. To demonstrate one solution to this issue I am going to focus on building a simple voting application. Some of the business rules are as follows:

    • Must be between the age of 18 – 75 to vote (yes there is an upper limit!!)
    • Must live in the country the candidate is running for

    Ok, so my rules about the voting process are a little weird to say the least, but hey, it’s just an example. As well as the rules for voting, upon submitting a vote the person voting has to supply all of the required voter information:

    • FirstName
    • LastName
    • Age
    • Address
    • Gender
    • CountryOfResidence

    Take a look at the class diagram for the initial domain model:

    InitialClassDiagram

    As you can see. This is a pretty simple domain. Let’s switch back to validating the simple properties for now. Let’s start with the strings (firstname,lastname,address). Remember, I am going to be performing all of my validation in the domain layer, so the buck stops here. I am not trusting anything that may have come from the UI. I am going to write a test to capture the validation I want to perform against the first name of a person:

     

    [Test]
    public void ShouldValidateUsingRule()
    {
    IBusinessRule
    <Person> firstNameRule = new BusinessRule<Person>(delegate(Person person)
    {
    return string.IsNullOrEmpty(person.FirstName);
    });

    Person personWithInvalidFirstName
    = new Person("", "", "", 0, null, null);
    Person personWithValidFirstName
    = new Person("JP", "", "", 0, null, null);

    Assert.IsTrue(firstNameRule.IsBrokenBy(personWithInvalidFirstName));
    Assert.IsFalse(firstNameRule.IsBrokenBy(personWithValidFirstName));


    }

    As you can see from this test. I am trying to encapsulate the simple business rule “A person must have a non-null firstname” into a full fledged BusinessRule object instance. You will notice the use of the Predicate delegate that I plan on passing into the constructor of the BusinessRule class. This is the method that will perform the validation against the person. The implementation of this class should prove to be fairly simplistic:

     

    public class BusinessRule<T> : IBusinessRule<T> { Predicate<T> brokenPredicate;

    public BusinessRule(Predicate<T> brokenPredicate)
    {
    this.brokenPredicate = brokenPredicate;
    }

    public bool IsBrokenBy(T item)
    {
    return brokenPredicate(item);
    }
    }

    Notice how I am making use of generics so that I can use the BusinessRule to work with any type. When I instantiate the BusinessRule for a certain type it will also constrain the type for the Predicate. If you take a look at the IBusinessRule<T> interface. You will notice that there is not much to it:

     

    public interface IBusinessRule<T> { bool IsBrokenBy(T item);
    }
     
     
     

    I now want a way to encapsulate a set of rules that need to be checked against an entity. Let’s take a look at another test:

     

    [Test]
    public void ShouldRetrieveAllRulesBrokenByItem()
    {
    IBusinessRule
    <Person> mockRule1 = mockery.CreateMock<IBusinessRule<Person>>();
    IBusinessRule
    <Person> mockRule2 = mockery.CreateMock<IBusinessRule<Person>>();
    IBusinessRule
    <Person> mockRule3 = mockery.CreateMock<IBusinessRule<Person>>();

    Person person
    = new Person("", "", "", 0, null, null);
    Expect.Call(mockRule1.IsBrokenBy(person)).Return(
    true);
    Expect.Call(mockRule2.IsBrokenBy(person)).Return(
    true);
    Expect.Call(mockRule3.IsBrokenBy(person)).Return(
    false);


    mockery.ReplayAll();

    IBusinessRuleSet
    <Person> ruleSet = new BusinessRuleSet<Person>(mockRule1, mockRule2, mockRule3);
    IBusinessRuleSet
    <Person> brokenRules = ruleSet.BrokenBy(person);
    Assert.AreEqual(
    2,brokenRules.Count);
    }

     

    Once again, I am making use of RhinoMocks to mock out the business rules. As you can see, you can ask a BusinessRuleSet for all of the rules that are broken by an item. With the test in place, the implementation becomes a breeze:

     

    public class BusinessRuleSet<T> : IBusinessRuleSet<T> { private IList<IBusinessRule<T>> rules;

    public BusinessRuleSet(params IBusinessRule<T>[] rules) : this(new List<IBusinessRule<T>>(rules))
    {
    }

    public BusinessRuleSet(IList<IBusinessRule<T>> rules)
    {
    this.rules = rules;
    }

    public IBusinessRuleSet<T> BrokenBy(T item)
    {
    IList
    <IBusinessRule<T>> brokenRules = new List<IBusinessRule<T>>();

    foreach (IBusinessRule<T> rule in rules)
    {
    if (rule.IsBrokenBy(item))
    {
    brokenRules.Add(rule);
    }
    }
    return new BusinessRuleSet<T>(brokenRules);
    }

    public int Count
    {
    get { return rules.Count; }
    }
    }

    With the business rule set in place let’s turn our attention to how we could go about asking domain objects to validate themselves:

     

     

    [Test]
    public void ShouldValidateUsingBusinessRuleSet()
    {
    IBusinessRuleSet
    <Person> mockRuleSet = mockery.CreateMock<IBusinessRuleSet<Person>>();
    IBusinessRuleSet
    <Person> mockBrokenRules = mockery.CreateMock<IBusinessRuleSet<Person>>();

    Person person
    = new Person("", "", "", 0, null, null,mockRuleSet);

    Expect.Call(mockRuleSet.BrokenBy(person)).Return(mockBrokenRules);
    mockery.ReplayAll();

    IBusinessRuleSet
    <Person> brokenRules = person.Validate();
    Assert.AreEqual(mockBrokenRules,brokenRules);
    }

     

    Being a big fan of dependency injection, I am making the decision that domain objects will be constructed with the rules they can use to validate themselves. This is especially handy in situations where the validation is context sensitive ie. In migration you often relax validation rules. I have decided that I will be able to ask a domain object to validate itself, and the result of this call will be a IBusinessRuleSet<T> containing all of the broken rules. With what we already have in place this should be fairly trivial:

     

    public Person(string firstName, string lastName, string address, int age, Country countryOfResidence, Gender gender, IBusinessRuleSet<Person> ruleSet)
    {
    this.firstName = firstName;
    this.lastName = lastName;
    this.address = address;
    this.age = age;
    this.countryOfResidence = countryOfResidence;
    this.gender = gender;
    this.ruleSet = ruleSet;
    }

    public IBusinessRuleSet<Person> Validate()
    {
    return ruleSet.BrokenBy(this);
    }

     

    That’s it. In the constructor for the Person class I pass in the rule set that it can use for validation, and the Validate method becomes a simple one line delegation. The solution I have used to encapsulate the business rules can easily allow me to utilize the flyweight pattern to share RuleSet’s between multiple instances of the same type. More on that later. Let’s look at the completed code required to validate a person class:

     

    public class Person
    {
    private string firstName;
    private string lastName;
    private string address;
    private int age;
    private Country countryOfResidence;
    private Gender gender;
    private readonly IBusinessRuleSet<Person> ruleSet;

    public Person(string firstName, string lastName, string address, int age, Country countryOfResidence, Gender gender):this(firstName,lastName,address,age,countryOfResidence,gender,Rules.Default)
    {

    }

    public Person(string firstName, string lastName, string address, int age, Country countryOfResidence, Gender gender, IBusinessRuleSet<Person> ruleSet)
    {
    this.firstName = firstName;
    this.lastName = lastName;
    this.address = address;
    this.age = age;
    this.countryOfResidence = countryOfResidence;
    this.gender = gender;
    this.ruleSet = ruleSet;
    }

    public IBusinessRuleSet<Person> Validate()
    {
    return ruleSet.BrokenBy(this);
    }


    public string FirstName
    {
    get { return firstName; }
    }

    public string LastName
    {
    get { return lastName; }
    }

    public string Address
    {
    get { return address; }
    }

    public int Age
    {
    get { return age; }
    }

    public Country CountryOfResidence
    {
    get { return countryOfResidence; }
    }

    public Gender Gender
    {
    get { return gender; }
    }

    public sealed class Rules
    {
    private Rules()
    {

    }

    public static IBusinessRule<Person> FirstName
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.FirstName);
    });
    }
    }

    public static IBusinessRule<Person> LastName
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.LastName);
    });
    }
    }

    public static IBusinessRule<Person> Address
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.Address);
    });
    }
    }

    public static IBusinessRule<Person> Age
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return person.Age > 0;
    });
    }
    }

    public static IBusinessRule<Person> Country
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return person.CountryOfResidence != null;
    });
    }
    }


    public static IBusinessRule<Person> Gender
    {
    get { return new BusinessRule<Person>(delegate(Person person)
    {
    return person.Gender != null;
    });
    }
    }


    public static IBusinessRuleSet<Person> Default
    {
    get { return new BusinessRuleSet<Person>(FirstName, LastName, Age, Address, Country, Gender);
    }
    }
    }
    }
     
     

    Notice how I am making use of the nested rules class inside of Person to place all of the distinct business rules for a person inside of the Person class itself. This is for demonstration, and to not go to the full blown effort of creating a RuleRegistry or the like. Notice how the constructor for the Person class that does not take a rule set, calls into the greedy constructor passing in the Default rule set, which is composed of each of the individual business rules. Let’s write some quick tests to verify that the default validation actually works:

     

    [Test]
    public void ShouldValidateFirstNameUsingDefaultRules()
    {
    Person person
    = new Person("", "JP", "Address", 1, Country.CANADA, Gender.MALE);
    IBusinessRuleSet
    <Person> broken = person.Validate();
    Assert.AreEqual(
    1,broken.Count);
    Assert.IsTrue(broken.Contains(Person.Rules.FirstName));
    }

    Currently the test will not compile because the IBusinessRuleSet interface does not provide the contains method. I need to implement the method (which I won’t bother showing) and then I can run the test. Once I have added the necessary code I will still get a failure because the object references for the 2 rules are not the same, even though in reality the rules are identical. To circumvent this issue we can add a custom equals implementation for the BusinessRule class. To make it simpler, I am going to add a new field to the business rule class to store the name of the business rule:

     

     

    [Test]
    public void BusinessRulesForATypeWithTheSameNameShouldBeEqual()
    {
    IBusinessRule
    <Person> firstNameRule = new BusinessRule<Person>("FirstName",delegate(Person person)
    {
    return false;
    });

    IBusinessRule
    <Person> firstNameRule2 = new BusinessRule<Person>("FirstName",delegate(Person person)
    {
    return false;
    });

    Assert.IsTrue(firstNameRule.Equals(firstNameRule2));
    }

    Initially this test will fail, this is because I need to add a custom equals implementation for the BusinessRule class:

     

    public override bool Equals(object obj)
    {
    IBusinessRule
    <T> other = obj as IBusinessRule<T>;
    return (other == null ? true : this.Name.Equals(other.Name));
    }

    public override int GetHashCode()
    {
    return brokenPredicate.GetHashCode() + 29*name.GetHashCode();
    }

    With this code in place the equals method will now work. Of course, with this refactoring I need to go back to the Rules class inside of person, and change all of the rules so a name is passed in also. An example of one such rule change is as follows:

     

    public static IBusinessRule<Person> Country
    {
    get { return new BusinessRule<Person>(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return person.CountryOfResidence != null;
    });
    }
    }

    Notice, in this initial incarnation I am using the Name of the property itself to determine the rule name!! Ok, this post is quickly turning into an essay, so I am going to cover one more point and then carry on another day. Take a look at the following rules in the Person class:

     

     

                public static IBusinessRule FirstName
    {
    get
    {
    return new BusinessRule(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.FirstName);
    });
    }
    }

    public static IBusinessRule LastName
    {
    get
    {
    return new BusinessRule(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.LastName);
    });
    }
    }

    public static IBusinessRule Address
    {
    get
    {
    return new BusinessRule(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return ! string.IsNullOrEmpty(person.Address);
    });
    }
    }

    You will notice that I am making use of the same method call in each argument string.IsNullOrEmpty. Unfortunately, what happens for any one of those checks when the string for any one of them is " ". The IsNullOrEmpty method will not catch this scenario. I need to fix the string checks so that they all behave the same. So now I have three pieces of code to change. Let me show you a way to encapsulate the checks:

    public interface ISpecification<T>
    {
    bool IsSatisfiedBy(T item);
    }

    public class NonEmptyStringSpecification : ISpecification<string> { public bool IsSatisfiedBy(string item)
    {
    return (! string.IsNullOrEmpty(item)) && item.Trim().Length > 0;
    }
    }

    I am making use of a toned down Specification pattern. If you are not familiar with that pattern, go ahead and pick up a copy of Eric Evans Domain Driven Design book. I promise I will devote a separate post to the Specification pattern (if people remind me!!). With the NonEmptyStringSpecificaton in place I can change the code in the Person rules class to the following:

     

    public static IBusinessRule<Person> FirstName
    {
    get { return new BusinessRule<Person>(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return new NonEmptyStringSpecification().IsSatisfiedBy(person.FirstName);
    });
    }
    }

    public static IBusinessRule<Person> LastName
    {
    get { return new BusinessRule<Person>(MethodInfo.GetCurrentMethod().Name,delegate(Person person)
    {
    return new NonEmptyStringSpecification().IsSatisfiedBy(person.LastName);
    });
    }
    }

    Notice that because the check for a Non-Empty string is now encapsulated in “another object”, if the rules for a non empty string change, I now only need to change one place!! I could carry on and add a NonNullObject specification that would encapsulate the null checks, this would be added solely for consistency and readability.

    Ok, so we now have a faily flexible validation engine in place, we have one problem. I can perform validation, but how am I going to get validation errors back to the client? Let’s write a quick test to prove out how I can go about this. In my head I think that it is going to take another change to the business rule class as well as the rule set:

     

     

    [Test]
    public void ShouldRetrieveMessagesForAllRules()
    {
    IBusinessRule
    <Person> mockRule1 = mockery.CreateMock<IBusinessRule<Person>>();
    IBusinessRule
    <Person> mockRule2 = mockery.CreateMock<IBusinessRule<Person>>();

    Expect.Call(mockRule1.Description).Return(FIRST_NAME_MESSAGE);
    Expect.Call(mockRule2.Description).Return(LAST_NAME_MESSAGE);

    mockery.ReplayAll();

    IBusinessRuleSet
    <Person> rules = new BusinessRuleSet<Person>(mockRule1, mockRule2);
    IList
    <string> ruleMessages = rules.Messages;

    Assert.AreEqual(
    2,rules.Count);
    Assert.Contains(FIRST_NAME_MESSAGE,(IList)ruleMessages);
    Assert.Contains(LAST_NAME_MESSAGE,(IList)ruleMessages);
    }

    The addition of a description for the rule requires me to add a new field and constructor to the BusinessRule class (the Description property gets added to the IBusinessRule interface):

     

     

    public class BusinessRule<T> : IBusinessRule<T> { Predicate<T> brokenPredicate;
    private string name;
    private string description;

    public BusinessRule(string name,string description,Predicate<T> brokenPredicate)
    {
    this.name = name;
    this.description = description;
    this.brokenPredicate = brokenPredicate;
    }

    public bool IsSatisfiedBy(T item)
    {
    return brokenPredicate(item);
    }

    public string Name
    {
    get { return name; }
    }

    public string Description
    {
    get { return description; }
    }

    public override bool Equals(object obj)
    {
    IBusinessRule
    <T> other = obj as IBusinessRule<T>;
    return (other == null ? true : this.Name.Equals(other.Name));
    }

    public override int GetHashCode()
    {
    return brokenPredicate.GetHashCode() + 29*name.GetHashCode();
    }


    }
     

    With that change in place. I need to update the rules that I create in the person class to add a description (you can check that out in the actual code). The code needed to implement the Messages property on the BusinessRuleSet class becomes a snap (with the aid of another anonymous delegate):

     

    public IList<string> Messages
    {
    get
    {
    return new List<IBusinessRule<T>>(rules).ConvertAll<string>(delegate(IBusinessRule<T> rule)
    {
    return rule.Description;
    });
    }
    }

    I make use of the ConvertAll method on the List class, to convert each of the rules into a plain old string, by passing in a delegate that just retrieves the Description from the rule!! Great. Everything is in place, let’s put all of this stuff through its paces. Take a look at the following WinForm:

     

    PersonWinForm

    This form will allow the user to enter in all of the basic information (minus Country and Gender). An accompanying presenter that can be consumed from this view is as follows:

     

     

    public class PersonPresenter
    {
    private IPersonView view;

    private IBusinessRuleSet<Person> rulesInContext = new BusinessRuleSet<Person>(Person.Rules.FirstName, Person.Rules.LastName, Person.Rules.Address, Person.Rules.Age);

    public PersonPresenter(IPersonView view)
    {
    this.view = view;
    }

    public void Submit()
    {
    IBusinessRuleSet
    <Person> broken = CreateFromView().Validate();
    if (broken.Count > 0)
    {
    view.DisplayErrors(broken.Messages);
    }
    else { view.DisplaySuccess(); } } private Person CreateFromView()
    {
    int age = 0;
    int.TryParse(view.Age, out age);

    return new Person(view.FirstName, view.LastName, view.Address, age, Country.CANADA, Gender.MALE);
    }
    }

    With that code in place (plus an accompanying view interface), if you run the app you will notice that the rules (for the context of the presenter) are being utilized to perform validation. I think I have probably given you a bit to think about. And keep in mind, this is one of several ways that validation in the domain layer can be performed. There are more refactorings that can be performed, and I still have not even looked at how we are going to perform the validation for the real voting scenario. I'll leave that for another day, unless one of my readers feels like submitting an extension to this piece to support the extended scenario.

    Please take the time to provide feedback if you have any. One of the main reasons that I try to post quality content is knowing that people out there are getting something from it. For the many who take the time to respond, it is greatly appreciated. I had to re- enable the captcha image, as I got spammed hard the other day. If you cannot place comments on the blog feel free to email me at bitwisejp@gmail.com

    The complete code (so far) for this entry is here.

    TODO
    Comments [9] | | # 
     Thursday, May 11, 2006
    Thursday, May 11, 2006 9:05:42 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Articles )

    I am posting the code for an article  that will appear in the May issue of Visual Studio Magazine. When the article was originally written it was written from a TDD perspective (which the tests will reflect). Unfortunately, my editor felt that the TDD approach detracted from the content of the article.  For those of you who know me personally, you know that I have a passion for showing people how to practically apply TDD to solve business problems. To that end, I have ensured that the source code that accompanies the article contains all of the tests that I wrote to drive out the functionality of the AddressBook.

    Please feel free to provide feedback on the article, I am constantly looking for ways to improve my writing skills to achieve greater impact on the masses.

    Thanks.

    JP

    Comments [7] | | # 
     Friday, May 05, 2006
    Friday, May 05, 2006 3:20:02 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )

    I thought I would take the time to post a simple example of TDD that people can use to build a class that could potentially add value to their current project. I am going to build a Money class test first. Lots of us work on projects that have to manipulate money in one form or another. For me, when I work on e-commerce apps I typically have to perform many different operations that deal and manipulate with monetary values. Traditionally people would use decimal or double types to represent the monetary amount. Unfortunately, this also meant that logic to perform rounding related issues was usually placed in some utility class or worse yet, in multiple places in the code where money was being manipulated. I don’t want to delve to far into discussion, as I feel that code speaks louder than words. Let’s start with the first test:

    1 [TestFixture]
    2 public class MoneyTest
    3 {
    4 [Test]
    5 public void ShouldBeAbleToCreateMoney()
    6 {
    7 Money money = new Money(20.00);
    8 Assert.AreEqual(20.00,money.Amount);
    9 Assert.AreEqual(2000,money.Cents);
    10
    11 money = new Money(10.25);
    12 Assert.AreEqual(10.25,money.Amount);
    13 Assert.AreEqual(1025,money.Cents);
    14 }
    15 }
    16

    As you can see. This test is pretty simple. It is just asserting that I can construct a new money instance that can be used to represent some monetary amount. Currently I am not in a build state, so I need to write enough code to make the test compile, and then pass. The following snippets show the progression of the Money class to make the test compile

     

    1 public class Money
    2 {
    3 public Money(double amount)
    4 {
    5 throw new NotImplementedException();
    6 }
    7 }
    8

     

    1 public class Money
    2 {
    3 public Money(double amount)
    4 {
    5 throw new NotImplementedException();
    6 }
    7 8 public double Amount
    9 {
    10 get { throw new NotImplementedException(); }
    11 }
    12 }
    13
    1 public class Money
    2 {
    3 public Money(double amount)
    4 {
    5 throw new NotImplementedException();
    6 }
    7 8 public double Amount
    9 {
    10 get { throw new NotImplementedException(); }
    11 }
    12 13 public int Cents
    14 {
    15 get { throw new NotImplementedException(); }
    16 }
    17 }
    18

    Ok, so we can easily see that there is no hope for these tests passing (from this point on I will skip showing the class generation step using ReSharper). Let’s write enough code to make the tests pass.

     

    1 public class Money
    2 {
    3 private readonly double amount;
    4 5 public Money(double amount)
    6 {
    7 this.amount = amount;
    8 }
    9 10 public double Amount
    11 {
    12 get { return this.amount; }
    13 }
    14 15 public int Cents
    16 {
    17 get { return Convert.ToInt32(amount * 100); }
    18 }
    19 }
    20

    Hopefully we are all in agreement that at the outset, this is currently the simplest way to implement the functionality described by the test. Which is exactly the point. Solve problems in small increments. Don’t future proof your designs. If a requirement changes or gets added, account for that fact by adding a new test and implementing the change/ new functionality. Ok, let’s write a test that is definitely going to cause us to rethink the design:

     

    1 [Test]
    2 public void ShouldRoundOnCreation()
    3 {
    4 Money money = new Money(20.678);
    5 Assert.AreEqual(20.68,money.Amount);
    6 Assert.AreEqual(2068,money.Cents);
    7 }

    If you add this new “requirement” you will quickly see that the current scheme I have come up with for storing the internal amount of the money as double is going to cause grief. The following ReSharper dialog shows the failure that occurs when this test is run:

     

    Exception1

    I am fairly confident that most of us are aware of some of the rounding issues that can arise from using double as a storage type for money. For that reason I am going to refactor the money class to use an int to store the number of pennies that the money consists of :

     

    1 public class Money
    2 {
    3 private readonly int cents;
    4 private double roundedAmount;
    5 6 public Money(double amount)
    7 {
    8 roundedAmount = Math.Round(amount, 2);
    9 cents = Convert.ToInt32(roundedAmount * 100);
    10 }
    11
    12 public double Amount
    13 {
    14 get { return roundedAmount; }
    15 }
    16 17 public int Cents
    18 {
    19 get { return cents; }
    20 }
    21 }

    As you can see the implementation of the class has not changed all that much. With the addition of the call to round and a field to now store the amount of the money object in pennies. You may ask why I bother to keep the field “roundedAmount” which stores the double value of the money as opposed to just calculating it every time the Amount property is accessed. Because Money is a classic “value object” once constructed it is completely immutable (read-only). For that reason, I don’t really care to recalculate every time the Amount property is accessed, as it will never change for a particular instance of Money. I perform the rounding right off the bat, and then continue to use it from that point on.

    If I run the tests, everything will now be passing. Unfortunately I am not done yet. Due to the way that the .Net framework implements rounding, I am going to run into a problem when I add the following new lines to the existing test for rounding:

     

    1 [Test]
    2 public void ShouldRoundOnCreation()
    3 {
    4 Money money = new Money(20.678);
    5 Assert.AreEqual(20.68,money.Amount);
    6 Assert.AreEqual(2068,money.Cents);
    7
    8 money = new Money(37.535);
    9 Assert.AreEqual(37.54,money.Amount);
    10 }

    The assertion on line 9 will fail. I could try using overloads of the Math.Round method, but they will all produce the same result. So once again, I am going to have to refactor the Money class to perform the rounding itself.

     

    1 public class Money
    2 {
    3 private readonly int cents;
    4 private double roundedAmount;
    5 6 public Money(double amount)
    7 {
    8 double quotient = amount / 0.01;
    9 int wholePart = (int)quotient;
    10 decimal mantissa = ((decimal)quotient) - wholePart;
    11
    12 roundedAmount = mantissa >= .5m ? .01 * (wholePart + 1) : .01 * wholePart;
    13 cents = Convert.ToInt32(roundedAmount * 100);
    14 }
    15
    16 public double Amount
    17 {
    18 get { return roundedAmount; }
    19 }
    20 21 public int Cents
    22 {
    23 get { return cents; }
    24 }
    25 }

    Ok, all of the tests are now passing and I am taking care of rounding myself. Unfortunately, the constructor has gotten a little hairy. Remember the mantra “Red – Green – Refactor”. I think we are sorely in need of a refactoring at this point. Let’s try and extract some methods out of the constructor. First off, let’s get the rounding calculation out of there:

     

    1 public class Money
    2 {
    3 private readonly int cents;
    4 private double roundedAmount;
    5 6 public Money(double amount)
    7 {
    8 roundedAmount = RoundToNearestPenny(amount);
    9 cents = Convert.ToInt32(roundedAmount * 100);
    10 }
    11
    12 private double RoundToNearestPenny(double amount)
    13 {
    14 double quotient = amount / 0.01;
    15 int wholePart = (int)quotient;
    16 decimal mantissa = ((decimal)quotient) - wholePart;
    17 18 return mantissa >= .5m ? .01 * (wholePart + 1) : .01 * wholePart;
    19 }
    20
    21 public double Amount
    22 {
    23 get { return roundedAmount; }
    24 }
    25 26 public int Cents
    27 {
    28 get { return cents; }
    29 }
    30 }
    31

    Things are looking a little better. One more thing that I want to do, even though it is a one liner, is extract out the conversion to pennies:

    1 public class Money
    2 {
    3 private readonly int cents;
    4 private double roundedAmount;
    5 6 public Money(double amount)
    7 {
    8 roundedAmount = RoundToNearestPenny(amount);
    9 cents = ToPennies(roundedAmount);
    10 }
    11 12 private int ToPennies(double amount)
    13 {
    14 return Convert.ToInt32(amount * 100);
    15 }
    16
    17 private double RoundToNearestPenny(double amount)
    18 {
    19 double quotient = amount / .01;
    20 int wholePart = (int)quotient;
    21 decimal mantissa = ((decimal)quotient) - wholePart;
    22 23 return mantissa >= .5m ? .01 * (wholePart + 1) : .01 * wholePart;
    24 }
    25
    26 public double Amount
    27 {
    28 get { return roundedAmount; }
    29 }
    30 31 public int Cents
    32 {
    33 get { return cents; }
    34 }
    35 }
    36

    Ok, things are looking good. The 2 new methods we introduced as part of the refactoring are getting tested by the tests that already exist. Of course, there is no problem with increasing the visibility of these new methods if you wanted to directly exercise them. We can be assured that they are being exercised as the constructor makes direct use of them. So with rounding taken care of we can now move on to add new functionality to the money class.

    Remember the Money class is completely immutable, so once constructed there is no way to change the value that the Money object represents. That being said, we should be able to treat our Money class like any of the intrinsic value types in the framework (note that currently the Money type is a class not a struct), meaning we should be able to add two Monies together, subtract, multiply etc. Let’s first write a test to ensure that two different instance of the same value of money evaluate to be equal to one another:

     

    1 [Test]
    2 public void IdenticalMonetaryValuesShouldBeEqual()
    3 {
    4 Money tenDollars = new Money(10.00);
    5 Money anotherTenDollars = new Money(10.00);
    6
    7 Assert.AreEqual(tenDollars,anotherTenDollars);
    8 }

    Initially this test will fail because by default, all reference types use ReferenceEquals to determine object equality. I can quickly get the test passing by changing the Money class to be a struct (value type). To make that possible I will need to make the ToPennies and RoundToNearestPenny methods static:

     

    1 public struct Money
    2 {
    3 private readonly int cents;
    4 private double roundedAmount;
    5 6 public Money(double amount)
    7 {
    8 roundedAmount = RoundToNearestPenny(amount);
    9 cents = ToPennies(roundedAmount);
    10 }
    11 12 private static int ToPennies(double amount)
    13 {
    14 return Convert.ToInt32(amount * 100);
    15 }
    16
    17 private static double RoundToNearestPenny(double amount)
    18 {
    19 double quotient = amount / .01;
    20 int wholePart = (int)quotient;
    21 decimal mantissa = ((decimal)quotient) - wholePart;
    22 23 return mantissa >= .5m ? .01 * (wholePart + 1) : .01 * wholePart;
    24 }
    25
    26 public double Amount
    27 {
    28 get { return roundedAmount; }
    29 }
    30 31 public int Cents
    32 {
    33 get { return cents; }
    34 }

    Again, with that “small” change, I can run the test for equality and it will now pass. Let’s now write a test to add two money objects together:

     

    1 [Test]
    2 public void ShouldBeAbleToAddMoney()
    3 {
    4 Money tenDollars = new Money(10.00);
    5 Money tenFifty = new Money(10.50);
    6
    7 Assert.AreEqual(new Money(20.50),tenDollars.Add(tenFifty));
    8 }

    You may be asking why I am not using operator overloading. No particular reason! With that failing test in place, we can carry on to add what proves to be a very simple method (thanks to all of the work we already did with the Rounding and Conversion)  (from this point I will only include new code fragments as opposed to the entire class):

     

    1 public Money Add(Money other)
    2 {
    3 return new Money(this.Amount + other.Amount);
    4 }

    As you can see. This does not break the immutabilty rule of the Money class, as the Add method returns a brand spanking new instance of Money that reflects that new value. Finishing off for today (there are other pieces of functionality that could be added, but I will leave that to you) let’s deal with one more piece of functionality – Multiplication. Multiplication is a good one as we are often wanting to calculate the GST for a certain amount of money when performing order totalling for E-comm sites. Let’s write a test to ensure that we can use Money to calculate GST correctly:

     

    1 [Test]
    2 public void ShouldCalculateGSTCorrectly()
    3 {
    4 Money tenDollars = new Money(10.00);
    5 Assert.AreEqual(new Money(.70),tenDollars.MultiplyBy(.07));
    6 }
    7

    Once again, implementing this new piece of functionality proves to be very simple:

    1 public Money MultiplyBy(double multiplicationFactor)
    2 {
    3 return new Money(this.Amount * multiplicationFactor);
    4 }

    Although there are other operations that could be added onto this money class (as well as the ability to have a Money class that can be used for multiple currencies), because we have Money encapsulated as an object in the domain we can now perform complex operations that previously would have been messily placed in utility classes and the like. This last "large" segment of code shows a family of classes taking advantage of the Money class for an Order scenario: 

    1 [Test]
    2 public void ShouldTotalOrderCorrectly()
    3 {
    4 Item chocolate = new Item(new Money(20.00),"Specialty Chocolate" );
    5 Item pop = new Item(new Money(10.00),"Pop" );
    6 Item chips = new Item(new Money(25.00),"Chips" );
    7
    8 Order order = new Order();
    9 order.Add(chocolate);
    10 order.Add(pop);
    11 order.Add(chips);
    12
    13 Assert.AreEqual(new Money(3.85),order.TotalGST);
    14 Assert.AreEqual(new Money(55.00),order.SubTotal);
    15 Assert.AreEqual(new Money(58.85),order.Total);
    16
    17 }
    18
    19 private class Order
    20 {
    21 private IList<Item> items;
    22 private delegate Money Summarize(Item item);
    23
    24 public Order():this(new List<Item>())
    25 {
    26
    27 }
    28
    29 public Order(IList<Item> itemsInOrder)
    30 {
    31 items = itemsInOrder;
    32 }
    33
    34 public void Add(Item item)
    35 {
    36 items.Add(item);
    37 }
    38
    39 public Money TotalGST
    40 {
    41 get 42 {
    43 return TotalUsing(delegate(Item item)
    44 {
    45 return item.GST;
    46 });
    47 }
    48 }
    49
    50 public Money SubTotal
    51 {
    52 get 53 {
    54 return TotalUsing(delegate(Item item)
    55 {
    56 return item.Price;
    57 });
    58 }
    59 }
    60
    61 private Money TotalUsing(Summarize summarizer)
    62 {
    63 Money result = new Money();
    64 65 foreach (Item item in items)
    66 {
    67 result = result.Add(summarizer(item));
    68 }
    69 70 return result;
    71 }
    72
    73
    74
    75 public Money Total
    76 {
    77 get 78 {
    79 return SubTotal.Add(TotalGST);
    80 }
    81 }
    82 }
    83
    84 private class Item
    85 {
    86 private const double TAX_RATE = .07;
    87 private Money price;
    88 private string name;
    89 90 public Item(Money price,string name)
    91 {
    92 this.price = price;
    93 this.name = name;
    94 }
    95 96 public Money GST
    97 {
    98 get 99 {
    100 return price.MultiplyBy(TAX_RATE);
    101 }
    102 }
    103
    104 public Money Price
    105 {
    106 get 107 {
    108 return price;
    109 }
    110 }
    111
    112 public string Name
    113 {
    114 get 115 {
    116 return name;
    117 }
    118 }
    119 }
    120 }
     

    Enjoy.


    TODO
    Comments [4] | | # 
     Thursday, May 04, 2006
    Thursday, May 04, 2006 12:04:16 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Tools )

    Ok, it's been a few weeks since my last post on automating your build with NAnt. We left off being able to compile and run all of the unit tests for the code. This is an essential step to be able to perform quickly. When solution sizes get bigger and the codebase gets larger, you will be glad that you spent the time automating the build process. There is a large difference between the time required to perform build activities at the command line using NAnt vs Studio. So far, we have not even talked about the database. As most of us are building applications with some sort of database back-end, it is essential that we can also automate the steps necessary to prep the database for use in our builds. Remember back to folder structure for our root directory?

    folderstructure1

    It is now time to shift our attention to the “sql” directory. In this post, I am making the assumption that the schema you will be creating will be your own (ie. You are not needing to deal with 3rd party databases that you need to integrate with. That is a story for another day). Let’s take a quick look at the contents of the sql directory. Here are the files that I have set up so far:

    • data.sql.template – File containing any seed data that is required to actually run the application.
    • nwind.sql.template – File containing the sql necessary to recreate the database,tables,indexes etc
    • security.sql.template – File containing the sql necessary to add roles,grant roles, add users etc to the database
    • storedProcedures.sql.template - File containing the CRUD procedures for data access
    • views.sql.template – File containing any views required by the application

    As you can see. This list is pretty short, and you could add files for different responsibilities very easily.

    You are probably asking yourself what the .template extension is for? Take a look at the first couple of lines in the nwind.sql.template file (pay attention to the items that have the red boxes around them):

    StartOfSqlScript All of the items that are surrounded by the @ symbol will actually get replaced at build time by values that NAnt retrieves from a local settings file for the user. This is what will allow multiple developers on the team to build the database to whatever location they want on their own hard drives, as well as naming the catalog for the database whatever they want. This allows for a lot of flexibility when it comes to how individual developers configure their workstations and dev environments. With this (and the other sql files in place), I need to add a target(s) to actually build the database using NAnt.

    The first thing I am going to do is add a couple of new properties to the top of the build file:

        <!-- environment-specific properties -->   
        <property name="osql.exe" value="C:\program files\microsoft sql server\90\Tools\Binn\osql.exe" />
        <property name="osql.ConnectionString" value="-E" />   
        <property name="env.COMPUTERNAME" value="${environment::get-variable('COMPUTERNAME')}" />
        <property name="aspnet.account" value="${env.COMPUTERNAME}\ASPNET" />   
        <property name="framework.version" value="v2.0.50727" />   

    Notice that I have specified values for the location of osql and the connection string with which to connect to OSQL. Now of course, I can’t assume that everyone on my team has loaded SQL to the default location. In which case, their path to SQL will be different. I also can’t assume that all of the developers on my team have integrated windows authentication enabled on their sql server install. If they don’t the -E switch for OSQL won’t work. Let me stress a point I am about to make “All Developers On A Team Regardless of machine configuration, should be able to utilise the build file without changing it”. Now as you can see, if I relied solely on the properties that I have created in the buildfile, I would be constraining the machine configurations of my team to have to use the exact same settings. This is where local property files come into play. Notice in the root directory I have a file named local.properties.xml.template. LocalPropertiesXmlTemplate

    The local.properties.xml.template file contains all of the properties that could possibly differ on each individual developers workstation. The template file is actually a repository artifact. So when a new setting gets introduced that could potentially be different of each persons machine, it is added to the template file. Take a look at the contents of the template file:

    <?xml version="1.0"?>
    <properties>
      <property name="sqlToolsFolder" value="C:\Program Files\Microsoft SQL Server\90\Tools\Binn"/>
      <property name="osql.ConnectionString" value="-E"/>
      <property name="initial.catalog" value="Northwind"/>
      <property name="config.ConnectionString" value="data source=(local);Integrated Security=SSPI;Initial Catalog=${initial.catalog}"/> 
      <property name="database.path" value="C:\root\development\databases" />
      <property name="osql.exe"  value="${sqlToolsFolder}\osql.exe" />
    </properties>

    Notice that it is a well formed xml document. You should also notice that the names of some of the properties are named identically to the names of properties that already exist in the build file (osql.ConnectionString, osql.exe). When a developer performs a fresh check out or the template file is changed, they will copy the template file into the same directory as the template file and rename it to local.properties.xml. Once renamed, the developer will open up the local.properties.xml file (not under source code control), and change the value of any of the properties that they need to, to reflect the configuration of their own machines. Ok, so this is great, but how do the settings in this file make integrate themselves into the actual build file? If I switch back to my build file, I will now add a check to include the settings from the local.properties.xml file, if the file is present:

    <!-- environment-specific properties -->   
        <property name="osql.exe" value="C:\program files\microsoft sql server\90\Tools\Binn\osql.exe" />
        <property name="osql.ConnectionString" value="-E" />   
        <property name="env.COMPUTERNAME" value="${environment::get-variable('COMPUTERNAME')}" />
        <property name="aspnet.account" value="${env.COMPUTERNAME}\ASPNET" />   
        <property name="framework.version" value="v2.0.50727" />    
                
        <if test="${file::exists('local.properties.xml')}">
            <echo message="Loading local.properties.xml" />
            <include buildfile="local.properties.xml" />
        </if>

    Notice I am telling NAnt to include an external file into the buid file. If the developer has created and modified their local.properties.xml file, then all of the settings they specified in that file will overwrite the default values of the properties that were already in the build file. Voila, multi-dev setup taken care of.

    Now it is time to focus on performing activities with the database. The first thing we need to take care of is changing the template files in the sql directory into the appropriate .sql files. Remember, as I said before. The .template files are the files that actually get placed/versioned in the repository. The .sql files will get automatically created by NAnt but not get stored in the repository. Let’s add a new target that will be able to convert a .template file into a file that can actually get worked with.

    <target name="convert.template">
            <copy file="${target}.template" tofile="${target}" overwrite="true">
                <filterchain>
                    <replacetokens>
                        <token key="INITIAL_CATALOG" value="${initial.catalog}" />                   
                        <token key="ASPNETACCOUNT" value="${aspnet.account}" />
                        <token key="OSQL_CONNECTION_STRING" value="${osql.ConnectionString}" />
                        <token key="CONFIG_CONNECTION_STRING" value="${config.ConnectionString}" />                   
                        <token key="DBPATH" value="${database.path}"/>
                    </replacetokens>
                </filterchain>
            </copy>
        </target>

    The convert.template target will copy a file with the .template extension to a file without the .template extension. At the same time, I am taking advantage of NAnt ability to apply filters during the copy process. In this scenario I am using the replacetokens filter to replace any occurrence of a token in the file (tokens in NAnt are specified by surrounding the item with the @ symbol), with a specific value. If you look back to the beginning of the nwind.sql.template file you will see that there are several tokens that will be replaced with settings pulled from my local settings file:

    • All instances of @INITIAL_CATALOG@ will be replaced by the value of the initial.catalog property (“Northwind”)
    • All instances of @DBPATH@ will be replaced by the value of the database.path property (“C:\root\development\databases”)

    Some of the other files in the sql directory make use of some of the other tokens. Some of the tokens do not exist in any of the sql files, but exist in other template files that I will talk about in future posts. With the “convert.template” target in place. I now want to create a target that I can use to execute a sql script:

     <target name="exec.sql.template">
            <call target="convert.template" />
            <exec program="${osql.exe}" commandline="${osql.ConnectionString} -n -b -i ${target}" />
     </target>

    Notice that the exec.sql.template is taking advantage of the fact that each developer could have a different location and connection specifics for osql. For the astute reader, you will note that if you were to just call exec.sql.template on its own, nothing would happen as the convert.template target assumes that a ${target} property has been set up before being invoked. You will notice that the exec.sql.template does not provide a value for the ${target} property, it is also attempting to make use of a ${target} property that should have already been assigned. For this reason, the exec.sql.template target is meant to be called from a target that will actually execute the scripts for db creation in the correct order. And here it is:

    <target name="builddb">
            <property name="target" value="sql\nwind.sql" />
            <call target="exec.sql.template" />
        
            <property name="target" value="sql\views.sql" />
             <call target="exec.sql.template" />

             <property name="target" value="sql\storedProcedures.sql" />
             <call target="exec.sql.template" />
                    
             <property name="target" value="sql\security.sql" />
             <call target="exec.sql.template" />
    </target>

    Notice that the builddb target knows the correct order in which to execute the sql scripts. Also notice the use of the call task that can be used to invoke targets from other targets. You will see that before the execution of the exec.sql.template target, the builddb target will set the value for the ${target} property for the file to act against next. Remember, first time builddb is run there will be no .sql files in the sql directory only .sql.template files. The convert.template target knows to tack on the .template extension and copy/transform accordingly.

    After running the builddb target, the database will be completely rebuilt from scratch (it will be deleted if it exists already). Again, something that I haven't talked about is the usefulness of keeping all of the db in .sql files. They are easy to maintain in the repository. When another developer on your team adds a table,view etc (making sure that they make changes to the .template files not the .sql files). You just need to update your sql directory and run your builddb target again. If 2 or more of you have made changes to the same table, worst case scenario you will need to use your merge/diff tool to see the differences. Best case scenario, your files will merge together seamlessly with all of your combined changes. Once the application has been deployed to production you can create subdirectories under the sql directory corresponding to each release/db update. These folder would only contain alters/new table additions. Once you have deployed to production you will want to leave the existing scripts under the sql directory as is. That way when you do a builddb, your database will get deleted created from the original sql scripts, and then all of the alters that have been applied in production will be applied against your local database. This is a much better process that changing the original sql files, as your DB’s probably don’t have the luxury of tearing down/recreating the database whenever a change goes into place. It also makes providing sql for the DB’s easy as you can just send them the alter file that you will also have in your repository. Of course, I can post about strategies for maintaining DB’s for deployed apps another time. After the builddb target runs, the sql directory will now look like this:

    SqlDirectoryAfterBuildDb

     

     

     

     

     

     

     

     

     

    As you can see, NAnt took care of copying the files and renaming them as necessary. If you take a look at the first couple of lines in the nwind.sql file (pay attention to the items in the red boxes) StartOfSqlScriptAfterTransform.

     

     

     

     

     

     

     

     

     

     

     

     

     

    You will notice that what use to be tokens are now concrete settings specific to my machine!! Feel free to ask questions, provide feedback etc. Enjoy automation.

     

     

    TODO
    Comments [3] | | # 
     Tuesday, May 02, 2006
    Tuesday, May 02, 2006 3:25:51 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns )

    I just had a great question asked by David Woods about one scenario that often comes up when utilising the Model View Presenter pattern:

    Q: How do you deal with drop down lists? They vary from web to windows and I want to refactor my app so that it can use either

    A: The code for this post shows one solution to the problem. An interface (ILookupList) is created to abstract the details of the UI specific list controls from the presenter:

     

    namespace Lists.Web.Controls.Test
    { public interface ILookupList
    { void Add(ILookupDTO dto); void Clear(); } }

     

    One concrete implementation of this interface is the WebLookupList class:

     

    using System.Web.UI.WebControls;
    
    namespace Lists.Web.Controls.Test
    { public class WebLookupList : ILookupList
    { private readonly ListControl listControl; public WebLookupList(ListControl listControl) { this.listControl = listControl; } public void Add(ILookupDTO dto) { listControl.Items.Add(new ListItem(dto.Text, dto.Value)); } public void Clear() { listControl.Items.Clear(); } } }
    Notice how all the WebLookupList does is delegate to an actual “Web” ListControl. ListControl is the base class for both DropDownList and ListBox, so it is useful to use the superclass in this case. The last piece of the puzzle is the LookupCollection class:
    using System.Collections.Generic;
    
    namespace Lists.Web.Controls.Test
    { public class LookupCollection
    { private readonly IEnumerable<ILookupDTO> dtos; public LookupCollection(IEnumerable<ILookupDTO> dtos) { this.dtos = dtos; } public void BindTo(ILookupList list) { list.Clear(); foreach (ILookupDTO dto in dtos) { list.Add(dto); } } } }
    A LookupCollection gets instantiated with an IEnumerable<ILookupDTO> and can then be told to bind itself to any ILookupList. The ILookupDTO interface is just an interface that can be implemented by objects that want to be used as values in a lookup list. With all of these pieces in place it becomes relatively trivial to populate a list on a web page with all of the customers in the system. Take a look at an interface for such a view:
    namespace Lists.Web.Controls.Test
    { public interface IViewContactView
    { ILookupList Contacts { get;} } }

    Notice that the Contacts property is readonly. A presenter that can work with this view looks as follows:

     

    using System.Collections.Generic;
    
    namespace Lists.Web.Controls.Test
    { public class ViewContactsPresenter
    { private IViewContactView view; public ViewContactsPresenter(IViewContactView view) { this.view = view; } public void Initialize() { new LookupCollection(GetAllContacts()).BindTo(view.Contacts); } public IEnumerable<ILookupDTO> GetAllContacts() { for (int i = 0; i < 20; i++) { yield return new ContactDTO(i.ToString("Name 0"), i.ToString("Address 0"), i.ToString()); } } } }
    In this example, assume that the GetAllContacts method actually lives in a service layer. The code in the Initialize method is now taking advantage of the LookupCollection class to populate the list on the view. The resulting code-behind for a web page becomes much tighter
    using System;
    using System.Web.UI;
    using Lists.Web.Controls.Test;
    
    public partial class _Default : Page,IViewContactView
    { ViewContactsPresenter presenter; protected void Page_Load(object sender, EventArgs e) { presenter = new ViewContactsPresenter(this); if (! IsPostBack) { presenter.Initialize(); } } public ILookupList Contacts
    { get { return new WebLookupList(this.contactDropDown); } } }

    Hope this brief explanation, along with the accompanying source code, gives you a place to start David!!

     

    For those of you who are curious about the order I wrote the tests (as this was done using TDD) here it  is:

    • 1)WebLookupListTest.cs – ShouldAddItemToUnderlyingList
    • 2)WebLookupListTest.cs – ShouldClearUnderlyingList
    • 3)LookupCollectionTest.cs – ShouldBindToLookupList

    Those 3 tests alone helped drive out the interfaces,classes etc. I did not write tests for the presenter and the view as MVP was not the main focus of the post, as much as how to have the presenter talk to the list controls. If you have any questions or feedback, please don’t hesitate to ask.

     

    Resources:


    TODO
    Comments [2] | | # 
     Tuesday, April 25, 2006
    Tuesday, April 25, 2006 6:27:13 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )
    I have had numerous people contact me asking to deliver the source code that I used for the DNRTv episodes. Obviously, I am happy to release the source code as my main goal is to share information. To that end, I am going to suggest an alternative to just “releasing the source”. I am proposing a series of blogs and or screencasts that will detail building the entire application used on the DNRTv segment from UI to data access. This would allow for full detailed coverage of what is going on under the hood, and could provide for some meaningful discussions etc. This is just an idea that I am throwing around. If the majority would just prefer the source to be released as is, then that is the route I will take. I can only release the source for the 3rd episode of DNRTv as the material from episodes 1 & 2 are part of an upcoming (July hopefully) MSDN article. At which time the source code will be released. If people opt to go with the detail route, we will start with the buildfile and end with the data access layer. That’s right, we’ll use TDD, Mocks, etc to build the application from front to back as opposed to back to front!!
    Comments [14] | | # 
     Wednesday, April 19, 2006
    Wednesday, April 19, 2006 3:25:23 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns )

    After my last presentation on DNRTv MauricioC asked some good questions that I thought I should post some answers for. I am reposting the questions from the comments that he made to give you a context for the answers:

    Q: By the way, I also have an architecture question. When implementing the Service Layer pattern (as in Martin Fowler's Patterns of Enterprise Application Architecture), where would you put persistence code? The example on the book puts methods for filling the Domain Objects in themselves, but I am a little uncomfortable in introducing a dependency for the Data Access Layer in my Domain Layer (even while using Inversion of Control). Would you retrieve/persist data in the Service Layer itself, or the dependency is manageable and I am being paranoid?

    A: As with many patterns there are a multitude of ways that the pattern can be implemented. As Martin points out, the two most common approaches for the service layers are the “Domain Facade” and “Operation Script”. I tend to lean toward the domain facade approach as it keeps my logic inside of the domain objects as opposed to dispersed through multiple methods in the service layer. As far as persistence is concerned the approach that Mauricio is talking about when having domain objects responsible for persisting themselves is the Active Record approach. As he says, this places a dependency on the data access layer in the domain model. I prefer having a completely isolated domain model, one that knows nothing about the service layer, data access etc. This allows you to drive out the functionality of the domain model in isolation from anything else. In this scenario, the service layer would be responsible for talking to some sort of MapperRegistry to retrieve mappers that know how to persist objects that need to go back to the database. Again, with a domain facade the service layer code is kept as thin as possible. Having discrete mappers that know how to persist objects/families of objects, removes this responsibility from both the domain model and the service layer and puts it where it should be, in a mapping layer. Mappers can be developed test first to ensure that if a mapper is given a particular object that it can read/delete/insert that object. So the long and short of it is :

    The Service Layer coordinates the persistence, but it doesn't perform the persistence.

    Again, the active record pattern is still a viable alternative if you are working with a simpler object model, and you are comfortable with domain objects being responsible for persisting themselves.


    Q:Another very related question: Would you use test-driven development to create the service layer (I mean, it is a very thin wrapper that should not need inversion of control, as it's common for such facades)? The same question applies for the view in the MVP pattern: If you had used TDD in DNRtv, what parts of the view would have been tested?

    A: The short answer is yes. Assume you were asked to build out a new method that needs to exist on a service layer class. This method will be called whenever a new Customer is to be added to the system. Here’s the catch, there is currently no mapper for a Customer object. And yet you still want to carry on developing the method without that in place. You can utilize TDD to drive out this scenario, even without the actual concrete mapper in place. If everything was already in place, then the test serves as a sanity check that the service layer class is talking and interacting with its dependencies as it should. An example of such a test would look like this.

     



    using System;
    using NUnit.Framework;
    using Rhino.Mocks;
    
    namespace DataLayer.DataAccess.Test
    {
        [TestFixture]
        public class CustomerTaskTest
        {
            MockRepository mockery;
    
            [SetUp]
            public void Setup()
            {
                mockery = new MockRepository();
            }
    
            [TearDown]
            public void TearDown()
            {
                mockery.VerifyAll();
            }
    
            [Test]
            public void ShouldBeAbleToCreateNewValidCustomer()
            {
                ICustomerMapper customerMapper = mockery.CreateMock<ICustomerMapper>();
                CustomerDTO dto = new CustomerDTO("JP","Boodhoo");
    
                ICustomerTask task = new CustomerTask(customerMapper);
    
                customerMapper.Insert(null);
    
                LastCall.On(customerMapper).Constraints(
                    Is.NotNull() &
                    Is.TypeOf(typeof(Customer)) &
                    Property.Value("FirstName","JP") &
                    Property.Value("LastName","Boodhoo"));
    
                mockery.ReplayAll();
    
                task.CreateNewCustomer(dto);        
    
           }
        
    
        
        }
    }
    
    

    Notice that I am taking advantage of a new mocking framework that I have come to love (RhinoMock .Net). I am going to write up another post about working with RhinoMock, for those of you who have used NMock2 (also a great framework), the immediate distinction between the two is that I can actually set expectations by actually invoking the methods on a mock interface. Again, I will save the details of using RhinoMock for another post. This test was written test first without any existing code in place, but the intent of what the concrete service layer class should do is evident. After calling the CreateNewCustomer method we know that the service layer class is going to invoke the “Insert” method on a ICustomerMapper implementation, and the Customer object that gets passed to the insert method will have had its firstname and lastname properties set. That is is. Thin service layer. We are not testing that the service layer can actually map the Customer to the database, we are testing that given a CustomerDTO, the service layer class can:

    • Unwrap the DTO and create the necessary Customer domain object
    • Invoke the Insert method on a ICustomerMapper implementation

    A test around a concrete ICustomerMapper implementation would actually verify whether a customer could be mapped to the database. If you want to see the code for the CustomerTask class, here it is:

     

    public class CustomerTask : ICustomerTask
    {
            private ICustomerMapper customerMapper;
    
            public CustomerTask(ICustomerMapper customerMapper)
            {
                this.customerMapper = customerMapper;
            }
    
            public void CreateNewCustomer(CustomerDTO dto)
            {
                customerMapper.Insert(new Customer(dto.FirstName,dto.LastName));
            }
    }
    
     
    In this scenario, this results in an extremely "thin" service layer class. As far as testing the view in an MVP triad, now we are getting into the functional testing layer where you would want to use some sort of automated UI runner. For windows NUnitForms is a great free one, and for the web Ruby & Watir are a great combination. Again, when testing at the actual UI layer, you are really trying to test the thin layer that can’t easily be accessed by the presenter (unless you tie presenters specifically to one particular UI framework).
    Comments [6] | | # 
     Tuesday, April 11, 2006
    Tuesday, April 11, 2006 3:15:45 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Tools )

    In the last post I talked about compiling the main supporting assemblies for the web/win project. Let’s shift focus now to talk about building the associated unit tests for the application. The solution I was working with SolutionStructureactually had a 1–1 (almost) correspondence of Test projects per deployable projects. In my opinion, this structure is a lot better than placing the tests in the same project that you are testing as it makes separating the files from test/deployment builds a lot simpler, as you don’t need to worry about naming your files in a special way to exclude them from the build process. I have already successfully compiled each of the assemblies that needs to be tested, using NAnt I compiled all of the source from the 8 projects into a single assembly.

    Before I can run my tests (in an automated fashion from the command line), they need to be compiled. It stands to reason that the NAnt xml required to accomplish this task is very similar to compiling the non-test projects:

    <target name="test.compile">
            <csc target="library" output="build\${nant.project.name}.Test.dll" debug="${debug}">
                <sources>
                    <include name="src\test\**\*.cs" />
                    <exclude name="src\test\**\AssemblyInfo.cs" />
                </sources>                                                                            
                                                                 </csc>
                                                         </target>

    Everything looks good, right? I should be able to switch to the command line and run the “build test.compile” command. If I do that right now I will run into a few problems. I won’t even show you the screenshot for what the errors look like, as it will take up too much space. The long and short of it is that I cannot compile the test project without preserving references that are essential to allow the dll to be built. Wait, why was this not an issue for the last time I compiled? This was because the only things the other dll depended on were System assemblies that are automatically resolved by NAnt. The fact that all of the code from the 8 projects was being compiled into a single assembly eliminated the need to duplicate project level references. Unfortunately, as picture 2 shows, most (if not all) of the test projects Referencesneed to have a reference to the actual projects that they are testing as well as 2 third party utilities (NMock and NUnit).

    Of course, I took care to ensure that when I created these references in Visual Studio that I pointed to the correct location of the tools within my tools folder (for NUnit and NMock2 that is). As far as the project references, all I had to do was add a standard project reference. Unfortunately, when I am in NAnt it knows nothing about these things. I have to set it up manually. Let’s make a small change to the test.compile target to compensate for this:

    <target name="test.compile" depends=”compile”>
            <csc target="library" output="build\${nant.project.name}.Test.dll" debug="${debug}">
                <sources>
                    <include name="src\test\**\*.cs" />
                    <exclude name="src\test\**\AssemblyInfo.cs" />
                </sources>                                                                            
            </csc>
     </target>

    Remember, the “depends” attribute for a target ensures that any targets listed for the value of that attribute have to run before this target can run. I am ensuring that the code to be tested has been compiled before I can compile the tests. Of course, I am still going to get compilation errors if I try to compile, as I have still not taken care of the references needed to build the test library. I’ll take care of NUnit and NMock2 first by making use of the references element:

    <target name="test.compile" depends=”compile”>
            <csc target="library" output="build\${nant.project.name}.Test.dll" debug="${debug}">
                <sources>
                    <include name="src\test\**\*.cs" />
                    <exclude name="src\test\**\AssemblyInfo.cs" />
                </sources>

                <references>
                    <include name="tools\nunit\bin\nunit.framework.dll" />
                    <include name="tools\nmock\NMock2.dll" />                               
                </references>
                                                                            
            </csc>
     </target>

     

    The references element is used by the csc task, to tell the compiler where to look for references required to build the project. As mentioned before, I don’t need to worry about framework libraries as NAnt resolves those for me. Again, note how referencing “references” becomes simpler when everything you need is located within your checkout directory!! Ok, I’m one step closer, but I still cantCompileError compile as it still cannot see classes that live in the assembly that should be being tested. As you have probably already guessed, I can fix this quickly by just adding another reference. But wait, what do I reference? Now you will see the important of having the “build” staging area, if you remember the compile target :

    <target name="compile"
                depends="init"
                description="compiles the application">
            <csc target="library" output="build\${nant.project.name}.dll" debug="${debug}">
              <sources>
                <include name="src\app\**\*.cs" />
                <exclude name="src\app\DotNetRocks.Web.UI\*.*" />
                <exclude name="src\app\**\AssemblyInfo.cs" />                                
             </sources>                        
            </csc>

    </target>

    I already know where the dll that I need to reference is going to get placed, so I can just add a reference to it!!:

    <target name="test.compile" depends="compile">
            <csc target="library" output="build\${nant.project.name}.Test.dll" debug="${debug}">
                <sources>
                    <include name="src\test\**\*.cs" />
                    <exclude name="src\test\**\AssemblyInfo.cs" />
                </sources>           
                <references>
                    <include name="build\${nant.project.name}.dll" />
                    <include name="tools\nunit\bin\nunit.framework.dll" />
                    <include name="tools\nmock\NMock2.dll" />                               
                </references>
            </csc>
        </target>

    With that change in place, I can now run the test.compile target, which will result in a new dll being placed in the build directory!! Next up, I’ll talk about running the tests in an automated setup, that will prepare us for when we start talking about CC.Net integration!!

    TestCompile

    TODO
    Comments [3] | | # 
     Friday, April 07, 2006
    Friday, April 07, 2006 1:03:58 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Tools )

    Ok, last time we left off being able to clean/create a staging area for the build. Let’s now work on actually compiling the projects in the solution. If you take a quick look at the solution structure SolutionStructure you will notice that there are 16 projects. More than half of these projects are test projects, and one of them is a web project. To be more specific, I am using the standard VS2005 web project model to organize my web project. Some of you may not be aware but there is another model called the Web Application Project model, that basically looks and behaves very similar to the way web projects worked pre VS2005. More on that another day!! Today I will focus on just building the supporting assemblies for the web project. Right now, I am talking about a build for test, not for deployment. These are 2 quite different animals. When I am doing a build for test I can choose to take a very simple route and just compile all of the code from the 8 supporting projects into a single dll, as opposed to compiling them the way studio does. This also keeps the build file a lot simpler. More often than not, as developers we utilize projects as a way to logically organize the application. Whether or not each of the individual projects actually resolves to one deployable unit is a choice that you have to make as a project team. Personally, once you have an automated deployment scenario in place, it really does not matter. As deploying becomes (almost) as simple as running a NAnt target.

    Let’s get back to actually building the 8 projects we are interested in. It stands to reason that some of the projects in the solution have dependencies on other projects in the solution ProjectReferences. Obviously these projects will not be able to build properly unless those references are maintained and obligated within the build file. A better question to ask is how do you actually go about compiling the 8 projects using NAnt? If you have been taking a look at the NAnt NAnt Task Reference reference you will notice that one of the tasks in there is the csc  task. This is a dedicated task with the sole responsibility of compiling C# programs. It stands to reason that this would have to enter the mix somewhere!!

    I am not even going to try and attempt to cover all of the attributes/flags that can be used in conjunction with the csc task. I believe an example will speak louder than words and get you going in the right direction. Let’s switch back to the build file and start working on adding in the compile task. In case you forgot what the build file currently looks like, here it is:

    <?xml version="1.0"?>
    <project name="DotNetRocks" default="all">

        <property name="debug" value="true" />

       <target name=”all”/>

       <target name="clean" description="remove all build products">
            <delete dir="build"  if="${directory::exists('build')}" />
        </target>

        <target name="init">
            <mkdir dir="build" />
        </target>

    </project>

    I’ll add the entire compile target and then discuss and dissect for the remainder of the post:

    <?xml version="1.0"?>
    <project name="DotNetRocks" default="all">

        <property name="debug" value="true" />

       <target name=”all”/>

       <target name="clean" description="remove all build products">
            <delete dir="build"  if="${directory::exists('build')}" />
        </target>

        <target name="init">
            <mkdir dir="build" />
        </target>

        <target name="compile"
                depends="init"
                description="compiles the application">
            <csc target="library" output="build\${nant.project.name}.dll" debug="${debug}">
                <sources>
                    <include name="src\app\**\*.cs" />
                    <exclude name="src\app\DotNetRocks.Web.UI\*.*" />
                    <exclude name="src\app\**\AssemblyInfo.cs" />                               
                </sources>                       
            </csc>
        </target>

    </project> 

    First point of interest is the use of the new “depends” attribute in the compile target. This tells NAnt to ensure that the “init” target has been run before the compile target runs. If the init target has not already been executed in this NAnt session, then NAnt will ensure that the init target is run before it carries on processing the compile target. NAnt processes dependencies from left to right so you can have a target depend on multiple targets using comma-separated lists such as : depends = “clean,init”. If you have a dependency on a target that also has a dependency on init, NAnt will make sure that the init target is only executed once, as not to waste execution cycles. The rest of the target deals with the actual csc task itself.

    First off, I tell NAnt that I am going to be compiling a “library” (dll) and that it should place the resulting dll in the build directory. What’s with the ${nant.project.name} syntax? This is the way you access properties in NAnt. We did not, however, define that particular property in our build file. This is because ${nant.project.name} is one of many predefined NAnt properties that we can make use of during the build process. The value of the ${nant.project.name} property will resolve to the name you give your project in the project element of the build file:

    <project name="DotNetRocks" default="all">

    So when this dll is compiled it will actually be compiled to : build\DotNetRocks.dll.

    Finally I have to tell the csc task, what files (sources) to include in the compile process. The sources element is actually just a NAnt fileset. I can include/exclude files from the fileset. Notice how I am excluding everything in the Web.UI project? Why, this is because I am using the WSP model and a lot of the code for web projects, when using this model, is dynamically generated. In a future post, I will show one way to compile the Web.UI project. I am also excluding any AssemblyInfo.cs file from the list of sources. If I did not do this, the compiler would choke because there would be multiple classes of type AssemblyInfo attempting to be compiled into the assembly. MultipleAssemblyInfos When I usually compile multiple projects into a single assembly, I usually create a single AssemblyInfo file for that group of projects, and include that AssemblyInfo file into the compile process.

    With that target completed, I can run the compile target from the command line and see the result placed into my build directory.BuildDirectoryWithNewAssembly 

    Next up is testing the assembly!!

     





    TODO
    Comments [2] | | # 
     Monday, March 27, 2006
    Monday, March 27, 2006 10:59:37 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns | Training )

    A couple of people have contacted me asking for a list of reading materials that I recommend for people who are looking to dive more into the development of layered enterprise applications. The following list is a small sampling of books that I think everyone will find some point of interest in:

     

    • Head First Design Patterns - This is a great book from O’Reilly. The examples are java based, but that should not be an issue. This book does talk about patterns and their applicability. It does, however, also discuss the dangers of  “patternitis” and how patterns at the end of the day are just another tool in a developers toolbox. More importantly, this book gives developers new to OO development a solid grounding in some basic OO design principles, and shows how the application of these few principles alone can lead to more solid object models.
    • Refactoring – The one stop reference for all you need to know to get started refactoring applications. An awesome book, written by a brilliant author. Show how to practically apply refactoring to improve the design of your code base.
    • Patterns Of Enterprise Application Architecture  – Great book that talks about patterns that developers often can utilize when building enterprise applications.
    • Applied .Net Framework Programming – Want to learn all there is to know about the architecture and inner working of the .Net framework. This is the book.
    • Design Pattern (GOF) – The original work on patterns. This is a great reference book that can give you a good grounding in the usage of design patterns.
    • Domain Driven Design – Want to build true rich domain object models. This is an absolute must read. I love the segment that talks about the much over-used “Smart UI” Anti Pattern.
    • Pragmatic Version Control Using Subversion – Often people forget the importance of a good version control system when building applications. Subversion is currently my favorite version control software, and best of all it is free. Lots of hands on examples of how to set up your repository structure, as well as practical, pragmatic advice on how to actually utilize subversion (and version control) on a day to day basis.
    • Programming .Net Components 2nd Edition – Excellent book covering many of the topics that often go unmentioned (or weakly covered) in many other .Net offerings.

    Well, I think that is enough for now. I will post more books at a later time.

     

    Comments [3] | | # 
     Wednesday, March 08, 2006
    Wednesday, March 08, 2006 9:57:19 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp )
    A new article I just published on building a Generic Range class with .Net 2.0 generics is available for viewing here on devx.com. Please feel free to provide any feedback (positive and negative) about the article.

    Thanks.

    Comments [4] | | # 
     Monday, January 09, 2006
    Monday, January 09, 2006 12:34:44 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | VS2005 )
    Thought I would try something different and show a video of how you can use anonymous methods as event handlers. This is my first try at using screen recording software for this purpose. If it proves successful and popular then I will probably make a video posting or 2 every month.

    Click here to watch the movie.
     
    Enjoy
    Comments [2] | | # 
     Friday, January 06, 2006
    Friday, January 06, 2006 2:59:41 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Patterns )
    Last year I had the opportunity to present several MSDN webchats related to application development with .Net. The following links will allow you to view the webchats on demand and at your leisure.

    Enjoy!

    Implementing the MVP pattern in Win forms Applications
    Utilizing the Factory and Strategy patterns to alter program behavior
    Change notification in the UI using the Observer pattern
    Testing the UI Layer in Smart Client Applications (Using MVP Pattern)
    Intro to TDD and Smart Clients

    Comments [5] | | # 
    Friday, January 06, 2006 8:29:11 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns | Training | VS2005 )
    For all who may be interested. On the week of February 6th - 10th I will be holding a .Net 2.0 Bootcamp in Calgary,AB.

    The event will be held at CTC TrainCanada in Calgary.

    It will be an intense week of getting up to speed on building enterprise level applications with the .Net 2.0 Framework. You can view the course outline here and if you are interested in attending you can register here.

    Look forward to seeing you there.
    Comments [0] | | # 
     Thursday, January 05, 2006
    Thursday, January 05, 2006 12:57:35 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | VS2005 )
    Well I finally published my first article. Hopefully the first of many. The article is going to be published in the January edition of Visual Studio Magazine. It is available for viewing here. Hope you find it useful.

    Comments [0] | | # 
     Thursday, December 15, 2005
    Thursday, December 15, 2005 8:36:03 AM (Mountain Standard Time, UTC-07:00) ( .Net 3.0 | C Sharp )
    As you already may know, Microsoft released the preview of Linq a while ago, to give developers a chance to play with some of the language features that are going to be in C# 3.0. Some of the new features that will be introduced are:

    • Extension Classes
    • Lambda Expressions
    • Language Integrated Query(LINQ)


    So what does all this mean to you as a developer? Here is an example of what can be accomplished with extension classes. How many times have you found yourself writing some sort of StringUtility class in your applications? Would'nt it be nice if you could just add methods that all instances of string would be able to call? Well with C# 3.0 it looks like this:


    1 using System;
    2 using System.Collections.Generic;
    3 using System.Text;
    4 using System.Query;
    5 using System.Xml.XLinq;
    6 using System.Data.DLinq;
    7 using NUnit.Framework;
    8 using LinqMadness.Core;
    9 using System.Query;
    10 namespace LinqMadness.Test
    11 {
    12 [TestFixture]
    13 public class StringExtensionTest
    14 {
    15 [Test]
    16 public void ShouldBeAbleToReverseString()
    17 {
    18 Assert.AreEqual("tsaoT","Toast".Reverse());
    19 }
    20
    21 [Test]
    22 public void ShouldBeAbleToTestForPalindrome()
    23 {
    24 Assert.IsTrue("pop".IsPalindrome());
    25 Assert.IsTrue("barcrab".IsPalindrome());
    26 Assert.IsTrue("elbertandednatreble".IsPalindrome());
    27 Assert.IsFalse("nonPalindrome".IsPalindrome());
    28 }
    29
    30
    31 }
    32 }
    As you can see from the above test class, using extension classes I have been able to dynamically add methods to any instance of a string object. How did he do that?? Look at the following code that shows how this is accomplished:

    1 using System;
    2 using System.Collections.Generic;
    3 using System.Text;
    4 using System.Query;
    5 using System.Xml.XLinq;
    6 using System.Data.DLinq;
    7 8 namespace LinqMadness.Core
    9 {
    10 public static class StringExtensions
    11 {
    12 public static string Reverse(this string stringToReverse)
    13 {
    14 StringBuilder builder = new StringBuilder(stringToReverse.Length);
    15 for(int i = stringToReverse.Length-1;i>=0;i--)
    16 {
    17 builder.Append(stringToReverse[i]);
    18 }
    19 return builder.ToString();
    20 }
    21
    22 public static bool IsPalindrome(this string toCheck)
    23 {
    24 25 for(int i = 0;i < toCheck.Length/2;i++)
    26 {
    27 if (toCheck[i] != toCheck[toCheck.Length -1 -i])
    28 {
    29 return false;
    30 }
    31 return true;
    32 }
    33 34 }
    35 }



    A couple of key points to note here. Notice the use of a static class. More importantly look at the signature of one of the methods that extends string with new functionality:

    public static string Reverse(this string stringToReverse)

    The use of the this keyword coupled with the type argument to the method indicates that this method is a behaviour that now will belong to all string instances.

    Ok, so as cool as that is, take a look at the following code that demonstrates some of the new LINQ features in C# 3.0.


    1 using System;
    2 using System.Collections.Generic;
    3 using System.Text;
    4 using NUnit.Framework;
    5 using System.Query;
    6
    7 namespace LinqMadness.Test
    8 {
    9 [TestFixture]
    10 public class CollectionTest
    11 {
    12 [Test]
    13 public void ShouldBeAbleToFindAllOddNumbersInList()
    14 {
    15 List<int> numbers = new List<int>();
    16 numbers.Add(1);
    17 numbers.Add(2);
    18 numbers.Add(3);
    19 numbers.Add(4);
    20 numbers.Add(5);
    21
    22 Assert.AreEqual(3,numbers.FindAll(i => (i % 2) != 0).Count);
    23 Assert.AreEqual(1,numbers.Min());
    24 }
    25
    26 [Test]
    27 public void ShouldBeAbleToCreateCustomType()
    28 {
    29 IList<Customer> customers = new List<Customer>(){newCustomer("JP","555-4444",23,"SomeAddress","Canada"),
    30 new Customer("Aaron","555-4444",23,"SomeAddress","Canada")};
    31
    32 foreach (Customer customer in customers)
    33 {
    34 var customerDTO = new{customer.CustomerName, customer.Phone};
    35 Assert.AreEqual(customer.CustomerName,customerDTO.CustomerName);
    36 Assert.AreEqual(customer.Phone,customerDTO.Phone);
    37 }
    38 }
    39
    40 [Test]
    41 public void ShouldBeAbleToUseQuerySyntax()
    42 {
    43 IList<Customer> customers = new List<Customer>(){new Customer("JP","555-4444",27,"SomeAddress","Canada"),
    44 new Customer("APerson1","555-4444",27,"SomeAddress","Canada"),
    45 new Customer("APerson2","555-4444",8,"SomeAddress","Canada"),
    46 new Customer("APerson3","555-4444",6,"SomeAddress","Canada"),
    47 new Customer("APerson4","555-4444",3,"SomeAddress","Canada"),
    48 new Customer("APerson5","555-4444",1,"SomeAddress","Canada")};
    49
    50
    51 IEnumerable<Customer> customersOver8 = from c in customers
    52 where c.Age > 8
    53 select c;
    54
    55 IEnumerable<Customer> customersBeginningWithA = from c in customers
    56 where c.CustomerName.StartsWith("A")
    57 select c;
    58
    59
    60 IEnumerable<Customer> customersWithOddNameLength = from c in customers
    61 where c.CustomerName.Length % 2 != 0
    62 select c;
    63
    64 Assert.AreEqual(2,new List<Customer>(customersOver8).Count);
    65 Assert.AreEqual(2,new List<Customer>(customersBeginningWithA).Count);
    66 Assert.AreEqual(1,new List<Customer>(customersWithOddNameLength).Count);
    67
    68 }
    69
    70 [Test]
    71 public void ShouldBeAbleToMultiplyUsingFold()
    72 {
    73 List<int> numbers = new List<int>{1,2,3,4,5,6,7};
    74 int product = numbers.Fold((start,current)=> start * current);
    75 Assert.AreEqual(5040,product);
    76 }
    77
    78 [Test]
    79 public void ShouldBeAbleToSum()
    80 {
    81 List<int> numbers = new List<int>{1,2,3,4,5,6,7};
    82 int sum = numbers.Sum();
    83 Assert.AreEqual(28,sum);
    84 }
    85
    86 [Test]
    87 public void ShouldBeAbleToSeeIfListsAreEqual()
    88 {
    89 Assert.IsTrue(new List<int>(){1,2,3}.EqualAll(new List<int>(){1,2,3}));
    90 Assert.IsFalse(new List<int>(){1,2,3}.EqualAll(new List<int>(){1,2,4}));
    91 }
    92
    93 [Test]
    94 public void ShouldBeAbleToGetDistinct()
    95 {
    96 Assert.AreEqual(4,new List<int>(new int[]{1,2,2,3,3,4}.Distinct()).Count);
    97 }
    98
    99
    100 [Test]
    101 public void ShouldBeAbleToUnionTwoSets()
    102 {
    103 List<int> firstSet = new List<int>(){1, 2, 3, 2, 2, 2, 4, 5};
    104 List<int> secondSet = new List<int>(){4, 5, 2, 2, 3, 4, 6, 7};
    105
    106 Assert.AreEqual(7,new List<int>(firstSet.Union(secondSet)).Count);
    107 }
    108
    109
    110 [Test]
    111 public void ShouldBeAbleToIntersectTwoSets()
    112 {
    113 List<int> firstSet = new List<int>(){1,2,3,3,4,5,6,7};
    114 List<int> secondSet = new List<int>(){4,8,9};
    115
    116 Assert.AreEqual(1,new List<int>(firstSet.Intersect(secondSet)).Count);
    117 }
    118
    119 [Test]
    120 public void ShouldBeAbleToOutputSquares()
    121 {
    122 int numberToSquare = 0;
    123 foreach (int square in Sequence.Range(1,30).Select(i => i * i))
    124 {
    125 numberToSquare++;
    126 Assert.AreEqual(numberToSquare * numberToSquare,square);
    127 }
    128 }
    129
    130 private class Customer
    131 {
    132 private string customerName;
    133 private string phone;
    134 private int age;
    135 private string address;
    136 private string country;
    137
    138
    139 public Customer(string customerName, string phone, int age, string address,string country)
    140 {
    141 this.customerName = customerName;
    142 this.phone = phone;
    143 this.age = age;
    144 this.address = address;
    145 this.country = country;
    146 }
    147
    148
    149 public string CustomerName
    150 {
    151 get { return customerName; }
    152 }
    153
    154 public string Phone
    155 {
    156 get { return phone; }
    157 }
    158
    159 public int Age
    160 {
    161 get { return age; }
    162 }
    163
    164 public string Address
    165 {
    166 get { return address; }
    167 }
    168
    169
    170 public string Country
    171 {
    172 get { return country; }
    173 }
    174 }
    175 }
    176 }



    I'll let you wrap your head around that one over the weekend and will dive more into the details of how it all works in a later post. If you want to be able to run the code, you will need to download and install the Linq technical preview.
    Comments [1] | | #