About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Setting The Record Straight - My Thoughts On The MVP Variants (for web applications)
code.google.com/p/jpboodhoo!!!
ReSharper Templates
Huge Code Drop Coming!!!!!!!
Leveraging the EventHandler delegate more effectively
DateTime Formatting with single custom format specifiers
Nothin But .Net - New York , NY ( October 22nd - 26th, 2007 )
Raising events (from a mock) using Rhino Mocks
Victoria Code Camp Source And Slides
And the timer sucks because....
What a waste of timer
ReSharper 2.5 -EAP Released
November MSDN Mini-Tour Content
TDD Live
Take Advantage of the ?? operator
Applied TDD Source Code Update
Refactoring Ahoy!!
Screencast - Applied Test Driven Development For Web Applications (Part 3)
Who Said Being Passive Was A Bad Thing?
And If you want a more robust timer.....
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
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
Automating Your Builds With NAnt - Part 2
Automating Your Builds With NAnt - Part 1
Recommended Reading
Tools Used For DNRTv TDD Episode
TDD On DNRTv
Generic Range
Visual Studio Article Code Download
Anonymous Methods As Event Handlers
Time Is Counting Down To Register For Nothin' But .Net 2.0!!
I'm Published!!
Using TransactionScope in .Net 2.0 To Test Your Mapping Layer

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

Total Posts: 519
This Year: 28
This Month: 0
This Week: 0
Comments: 1589

 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 [12] | | # 
 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 [8] | | # 
 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 [4] | | # 
 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 [0] | | # 
 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] | | # 
 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] | | # 
 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] | | # 
 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] | | # 
 Tuesday, December 05, 2006
Tuesday, December 05, 2006 9:35:21 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Tools )

If you like to play with the latest and greatest that JetBrains has to offer, then head here to download the EAP version of ReSharper 2.5. If you have already been using the EAP version, then there is not much I can say about it that you have not already seen.

If, on the other hand, you have not been using the 2.5 release then you are in for a few surprises. Along with tightening up the user interface (which looks really nice now), there are a number of new features that ReSharper users will welcome with open arms.

Instead of me duplicating information, check out the RoadMap for the product here.

Develop with pleasure!!

Comments [1] | | # 
 Friday, November 17, 2006
Friday, November 17, 2006 12:46:16 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Patterns | Presentations )

Lots of people ask why I don't usually post my powerpoints and code that I deliver at presentations that I give. For the most part, because of my dynamic and on the fly presentation style, I often show up with no code and build out scenarios on the fly. The resulting code often only makes sense to look at in the context of being an attendee of the presentation.

The same can be equally said for my powerpoints. When I actually have slides prepared, they are used as mere launchpads into either conversation or demonstrations of a new concept.

That aside, I have had a lot of requests for the content from my first mini tour I conducted as part of the MSDN Canada Speakers bureau. I spoke in Regina, Winnipeg, and Saskatoon on three consecutive nights. The code that resulted from each session was quite different, so I decide to post the code that came out of the last session.

The presentation was focused on introducing people to the concept of design patterns. While meant to be a 100 level talk, I definitely threw one 400-500 level example into the mix to spice things up.

Here are the links to the content:

 

 

Feel free to use the slide deck and accompanying source code if you want to deliver your own presentations built on the material. If you do so, I would definitely appreciate being recognized for the work.

If you have any questions I will definitely try to get them answered.

Comments [4] | | # 
 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 [6] | | # 
 Wednesday, October 11, 2006
Wednesday, October 11, 2006 10:26:00 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Presentations )

Thanks to the notification of Steve Nickerson, I have updated the original zip file that I released containing the source. This gets rid of a compile error that was present in the original source (I messed stuff up when I was prepping for deploying the zip)!! Download the latest code from here (the original link has been updated also).

 

Thanks Steve.

Comments [4] | | # 
 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 [14] | | # 
 Sunday, October 08, 2006
Sunday, October 08, 2006 4:00:00 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Patterns )

I have had a couple of questions over the last couple of weeks as to which flavour of Model-View-Presenter I am partial to. In regards to the recent split of the pattern that Martin Fowler has established, I am a big proponent of the Passive View variant of the pattern. The Passive View approach allows me to push even more code down into the presenter, as it is now directly responsible for responding to events on the view. In the example that I have given in the past, I show how the view is responsible for invoking a method on the presenter whenever something needs to be done. In practice, I expose events on the interface for the view, that the view is responsible for raising. For example, when the a save button is clicked on the view, I can have the view raise a save event. The Save event is handled by an event handler on the presenter, which can then invoke the appropriate functionality within itself. This frees the view from needing to know which method to call on the presenter when something needs to be done.

With regards to the different flavours of MVP, they all have pros and cons. You will also find that many people were already using the Passive View approach, before it even received its own name!!

Comments [4] | | # 
 Friday, September 22, 2006
Friday, September 22, 2006 7:56:07 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 )

In my last post I created a simple class that wrapped around the Stopwatch class in the Framework. If you require a more robust implementation for your needs, check out the timer that Vance Morrison has created. His implementation allows for collecting stats from individual iterations as well as some other interesting features.

Comments [0] | | # 
 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, 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 [6] | | # 
 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 [2] | | # 
 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 [7] | | # 
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 [8] | | # 
     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 [1] | | # 
     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] | | # 
     Wednesday, April 05, 2006
    Wednesday, April 05, 2006 2:41:19 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Tools )

    In the previous post we covered off solution structure and physical directory structure. It’s time to move on to talk about the actual build process. What does it mean to build? A “build” means different things to different people. For me building consists of the following crucial steps:

    • Cleaning up the results of a previous (if any) build process.
    • Creating a build area (folder)
    • Rebuilding databases (optional)
    • Compiling all project/solution related files
    • Compiling all test related projects
    • Running unit tests

    Of course there are other activities that can occur in a build process, but the ones listed above are key. Notice that the “Rebuilding databases” step is optional, as there are lots of applications that do not require the use of database engines. I’ll break the process down step by step, so you can follow along if you desire. Before we can begin putting the steps in motion we are going to make use of a tool that will allow us to automate this process. Having some form of an automated build process is the key to enhancing your productivity as a developer. Getting back to a point I keep stressing, “A Developer should be able to do a fresh checkout and be able to hit the ground running.”.  As a developer, I would much rather do a fresh checkout and run some command at the command prompt to assert that my world is set up ok. As opposed to:

    • Checking Out
    • Opening the Solution file
    • Waiting for studio to load up
    • Building the solution
    • etc,etc,etc

    In order to automate your build process you can take advantage of NAnt. NAnt is the open source, more mature, equivalent to MSBuild. Let me say that I think it is great that MS has introduced an automated build tool into the mix, and I am sure that eventually I will be able to retire NAnt and utilize it. In its current implementation, I definitely feel that NAnt is more feature rich out of the box, and a little easier to work with.

    Setting Up The Build File

    A NAnt build file, just like an MSBuild file, is nothing more than an xmldocument that is interpreted and executed by the NAnt runtime. Most of my build files start with the following basic skeleton:

    <?xml version="1.0"?>
    <project name="DotNetRocks" default="all">

        <property name="debug" value="true" />

        <target name=”all”/>

    </project>

    That’s it. This is the start of your build file. All these couple of lines of XML are telling NAnt is that this build file represents the project named “DotNetRocks” and that there is a global property called “debug” that has its value set to true. Most important is the “default” attribute. This attribute tells NAnt that the default target to execute is the “all” target. What is a target? More on that later. Think of properties defined at the top of the build file as variables that can be accessed (using the ${propertyName} syntax) during the build process.

    So far this build file does not do much of anything, let’s take care of the first item on the build to-do list.

    Cleaning up the results of a previous (if any) build process

    Now of course, there are currently no unwanted artifacts to clean up, as I have not even completed a successful build yet. Don’t worry about that. The first thing you need to decide is where you want all of your build artifacts to go. When I say build artifacts, I am talking about dll’s, exe’s etc that result from compiling your projects. The following screenshot shows how I will augment my directory structure to support the build process:

    BuildDirectory

    There is one important thing you should realize about the “build” directory. It is created by the build process and is a completely transient directory. It exists solely for facilitating the placement of files and artifacts related to building and testing the project. As a side note, this directory would also not be under source control. Which means you would have to make sure that it is “ignored” from checkins/commits. The main executable unit for NAnt files is the <target> element. You can think of <targets> as subroutines that can be invoked to perform a series of tasks. Let’s change our build file to clean/recreate the build directory:

    <?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>

    </project>

    Notice that the target element has attributes such as “description” that can be used to provide descriptive information about the targets contained in the build file. What about the nested element? The <delete> element is one of many NAnt tasks that can be composed within targets to provide the functionality contained within a target. Here I am using a conditional to tell NAnt to delete the build directory if it already exists. Within a NAnt build file, unless explicitly stated, all directory references are relative to the location of the build file itself. Which means when I tell NAnt to delete the ‘build’ directory, it will attempt to delete a subfolder named build in the folder where the build file itself is contained. I am not going to dive in depth into the ins and outs of each of the NAnt tasks, as the task documentation provides lots of good information that you can use. As long as you can read/write xml, you should be set!!

    Creating a build area

    Ok, I’ve ensured that a build directory does not exist, so now I want to create one that will be used in the build process. I do this by adding the following to the build file:

    <?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>

    Again, here I am making use of the mkdir task provided by NAnt to create a subdirectory named build in the directory where the build file is located. Ok, I now have a NAnt file with three targets that know nothing about each other. Of course, all this XML means nothing if I can’t actually run something that will make use of it. Let me take a quick time-out to talk about utilizing NAnt to execute targets in the build file.

    Running NAnt

    The advantage of having everything related to your build process in one directory (the trunk) means that performing build tasks becomes much simpler. Remember back to where NAnt would actually live in my proposed directory layout:

    ToolsDirectory

    Remember, NAnt is just an executable with a bunch of supporting dll’s. To run it I have to run the exe file. Because I typically run NAnt from the command line on my local machine, it would be a bit of a pain to have to open up the command prompt and execute NAnt for my build file using the following command line:

    Tools\nant\bin\NAnt.exe -buildfile:dotnetrocks.build all

    The arguments tell NAnt that the build file to run is the dotnetrocks.build file and that the all target should be executed. Again, this would be a pain to have to type every time, so let’s make use of a good old trusted pal. The bat file!! Create a file called build.bat that will live in the same directory as your build file. The contents of the bat file are as follows:

    @echo off
    cls
    Tools\nant\bin\NAnt.exe -buildfile:dotnetrocks.build %*

    The most important aspect of this bat file is that it allows us to execute it and pass in extra arguments to be interpreted by the build file (using the %*). So, if I wanted to execute the clean target that exists in my build file, I would just have to open up a command prompt and navigate to the directory my build file is located (use Command Prompt Here for convenience) and run the command – build clean, which would result in the following console output:

    NAnt 0.85 (Build 0.85.2139.0; nightly; 11/9/2005)
    Copyright (C) 2001-2005 Gerry Shaw
    http://nant.sourceforge.net

    Buildfile: http://www.jpboodhoo.com/dotnetrocks.build
    Target framework: Microsoft .NET Framework 2.0
    Target(s) specified: clean

         [echo] Loading local.properties.xml

    clean:


    BUILD SUCCEEDED

    Total time: 0.2 seconds.


    D:\Development\dotnetrocks\2006\testDrivenDevelopment>

    With this setup in place I can quickly execute any of the targets in my build file with ease. Ok, I am quickly seeing that all of this information is probably going to be too much for this one blog post, so I will span this over a couple of more entries. Tomorrow we’ll pick up the process by compiling the application and linking targets!!

     

    TODO
    Comments [11] | | # 
     Monday, April 03, 2006
    Monday, April 03, 2006 12:28:09 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | Tools )

    After a couple of discussions with Ben Scheirman . I decided that I should post some information about automating your build process using NAnt. This is the first in a 3 part post that describes my recommendations for all things related to automating your build process. I should note that this is a process that I use even if I am working on a project for myself, where no other developers are involved. Having an automated build process can streamline your development efforts dramatically. I am making the assumption that you already have a source control repository in place. Let’s take a look at a common directory structure that I use for projects:

     

    FolderStructure

     

    This may or may not be a structure that you are familiar with. The first thing to notice is the location of the solution file (DotNetRocks.sln) with respect to all of the projects under the solution. The solution file lives right in the root of the (trunk) directory. I’ll explain as necessary the purpose of each of the folders. The first and most important thing I want to stress about this proposed build structure is this: After a fresh checkout a developer should be able to do all project related tasks with solely the contents of the combined folders.

    This means, that a new developer coming onto to the team should be able to boot up their computer, do a fresh checkout, and be able to build the project without any problems. We’ll dive further into how this can be accomplished by talking about some of the core directories that are crucial to the build process.

    The lib Folder

    Take a look at the following screenshot that shows the contents of this particular lib folder:

    LibFolder

    Each subdirectory in the lib folder will be named after a third party library that also needs to go along with the deployed application. This could be things like a logging library (log4Net), Infragistics etc. The point is, without the files contained in these folders, the application could not be compiled or deployed. Typically, the majority of files that live in these folders are dll’s or exe’s. One key point about this folder. All project references to third party software from within the solution are made to point into folders in this directory.

    The tools Folder

    Take a look at a screenshot for the tools folder:

    ToolsFolder

    Each subdirectory in the tools folder contains utilities, libraries etc, that are essential to the building and testing of the application. A key distinction between this and the lib folder is that files in the tools folder do not get deployed with the production application. They are only necessary to facilitate the build process itself. The NAnt folder contains all of the NAnt assemblies including the NAntContrib assemblies. I will talk more about NAnt later, as it is a great tool to facilitate automating your build process. A common folder that is seen in tools directories everywhere is the nunit folder. This folder, obviously, contains all of the dll’s and exe for NUnit, which is used to write and run automated unit tests for the application.

    The src Folder

    The source folder obviously holds the most important artifacts for the application (the source code files). There is a slight twist to this source directory as you will see from the following screenshot:

    SrcFolder

    All projects for the solution are stored under the respective directory. Any project that is part of the build for distribution will live under the app directory. All projects related to testing live under the test folder.

     

    This would be a good place to actually talk about the solution and project hierarchy itself.

     

    VS Solution Setup

    The following screenshot shows what a typical solution would look like mapped to the above directory structure:

    SolutionLayout

    As you can see, studio flattens out the actual physical structure that the projects are mapped to. Any project with a .Test extension would live under the src\test directory. Other projects would live under the src\app directory. All references to third party libraries would point to either folders under the tools/lib folder, depending on the type of reference. Notice that almost every “app” project in this solution has an accompanying “Test” project. This is an optimal setup to allow for quick building/segragation of the test and app portions of the application. In this scenario, the only project that does not have a Test project is the Web.UI project. This is the project where all of the .aspx,.ascx files etc live. As such, and this is a topic for a later discussion, code that lives in that layer is kept to a minimum as it is difficult to test without running the application or using WATIR or alternatives.

    Next up we’ll talk about building this application using NAnt.


    TODO
    Comments [13] | | # 
     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] | | # 
     Monday, March 20, 2006
    Monday, March 20, 2006 9:45:35 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 )

    As promised, here is a list of links to tools that I mentioned or used on the TDD episode of DNRTv I participated in last week:

    • ReSharper 2.0 – a kick butt plugin for C# developers. I can no longer use studio without it!! (Remember, it is still in beta)
    • NMock2 – A mock object framework for .Net
    • NMock2 Quick Reference – Great quick reference for getting you up to speed on some of the functionality in NMock2
    • NUnit – One of the most populate unit testing frameworks for .Net.
    • NAnt – Automated build tool
    • CruiseControl .Net – Continuous Integration Build Server
    • Watir – Ruby web application testing framework
    Comments [3] | | # 
     Thursday, March 16, 2006
    Thursday, March 16, 2006 11:47:03 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 )
    Thanks to the audio and video expertise of Carl Franklin, a new show has been posted on DNRTv where I try to give a more complete example of test driven development in action. It’s funny, when I went through the demo on my own machine, I was able to get through all of the code within one hour. Once we actually started to record the show we realized that we would need to break it up into 2 recordings. And even then I was only able to demonstrate the first part of the example!! It was a lot of fun and I hope that lots of people watch and give feedback as to what they see. You can watch the latest episode here, and I will also be giving a talk on DotNetRocks next week, related to the episode that we just shot.
    Comments [8] | | # 
     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] | | # 
     Friday, January 13, 2006
    Friday, January 13, 2006 10:44:47 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | VS2005 )

    The good folks at VSM are currently experiencing problems with their download servers. I have received many requests for the source code to the article that I published on different approaches to databinding.

    You can now download the code here and hopefully the servers at VSM will be available to download the code soon.

    Thanks.

    Comments [1] | | # 
     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 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] | | # 
     Tuesday, December 13, 2005
    Tuesday, December 13, 2005 8:34:35 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 )
    How many times have you found yourself writing code to cleanup changes that your mapping tests make to the database. Save yourself some time and make use of the new TransactionScope class in .Net 2.0.

    Take a look at the following code fragment to see a good pattern for use. The class makes use of the NUnit 2.2.3 testing framework.

    1 [TestFixture]
    2 public class SomeMapperTest
    3 {
    4 TransactionScope scope;
    5 6 [SetUp]
    7 public void SetUp()
    8 {
    9 scope = new TransactionScope();
    10 }
    11
    12 [Test]
    13 public void ShouldBeAbleToInsertDomainObjectToDatabase()
    14 {
    15 using(scope)
    16 {
    17 TestDatabaseGateway gateway = new TestDatabaseGateway();
    18 int existingRowsInTargetTable = gateway.GetRowCountFor("TargetTable");
    19 SomeDomainObject objectToPersist = new SomeDomainObject();
    20 SomeMapper mapper = new SomeMapper();
    21 mapper.Insert(objectToPersist);
    22 Assert.AreEqual(existingRowsInTargetTable+1,
    23 gateway.GetRowCountForTable(“TargetTable”));
    24 }
    25 }
    26 27 }
    Comments [2] | | #