About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

code.google.com/p/jpboodhoo!!!
The Static Gateway Pattern
Screen Bound DTO Update (Getting the terminology right)
Nothin But .Net - New York , NY ( October 22nd - 26th, 2007 )
Refactoring to reveal intent
November MSDN Mini-Tour Content
Layering Schemes For Projects (One approach)
Who Said Being Passive Was A Bad Thing?
One Refactoring Missed
Applied Test Driven Development For Web Applications - Part 1 (Video)
Applied Test Driven Development For Web Applications Update
Coding to interfaces
Applied Test Driven Development For Web Applications - Part 1
Enhancing Images With The Decorator Pattern
Dealing with drop down lists with the MVP pattern
Answers To Some Good Questions
Recommended Reading
Webcast Links
Time Is Counting Down To Register For Nothin' But .Net 2.0!!

Archive

Blogroll

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

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

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

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

 Wednesday, November 28, 2007
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] | | # 
 Monday, October 15, 2007
Monday, October 15, 2007 5:50:32 AM (Mountain Standard Time, UTC-07:00) ( Patterns | Programming )

Now I am by no means claiming to be any sort of patterns naming authority, but after you see the same occurent pattern in your applications you often will try to formulate some sort of vocabulary among the team to express the concept that you see occurring over and over again. This is the very nature of how patterns popped up in the first place. This is a pet name that I have come up with for the “recurring” theme you will see demonstrated here. If you are not familiar with the Gateway pattern check out the definition here.

I am going to demonstrate this pattern with an example that most people should have in place at the beginning of a project. Logging.

One of the things about Logging, is that it should be simple. Let’s assume that to get things rolling I really only care about logging informational messages. Assume I have a Calculator class that wants to do some logging, here are some possible code fragments that demonstrate the calculator class taking advantage of logging capabilities:

    public class Calculator
    {
        private ILog log;

        public Calculator(ILog log)
        {
            this.log = log;
        }

        public int Add(int number1,int number2)
        {
            log.InformationalMessage("About to add two numbers");
            return number1 + number2;
        }
    }

In this scenario the calculator is constructed with a log which will take care of logging behaviour on its behalf. I don’t like this as Logging falls under that set of “cross-cutting” concerns, and I don’t want to have to provide all of the objects in my application (domain layer or not) with this extra dependency. Here is another option:

public class Calculator { private ILog log; public Calculator() { } public ILog Log { set { this.log = value; } } public int Add(int number1,int number2) { log.InformationalMessage("About to add two numbers");
return number1 + number2; } }

Again, this is not optimal as it clutters up my object with unecessary noise. From a simplicity perspective, is it simpe for me to specify that “all objects should have a field of type ILog if they want to consume logging functionality? I think that the simplest api would be something like this:

public class Calculator { public int Add(int number1,int number2) { Log.InformationalMessage("About to add two numbers");
return number1 + number2; } }

Right now someone somewhere is screaming about the fact that I just introduced, what looks like, a Singleton. From an API perspective, the line above imposes the least design restrictions on my classes that want to consume logging functionality. The only caveat is that any class that wants to leverage logging is now coupled to the Log class. IMHO this is only an issue if it decreases the ability for me to test or if it decreases the option for me to swap out logging implementations (ex. Log4Net, MS Logging etc).

By the looks of the code above, it would seem that I have pinned myself into a fairly rigid design. I am not going to focus on how I test drive this out, but taking the API above, how could I go about testing the Log class?

With the Static Gateway pattern, the Gateway (in this case the Log class) does not actually do any of the work. It just serves as the entry point to the functionality. If that is the case here is a cut at what the Log class could look like:

public class Log { private static ILogFactory logFactory; public static void InitializeLogFactory(ILogFactory logFactory) { Log.logFactory = logFactory; } public void InformationalMessage(string informationalMessage) { logFactory.Create().InformationalMessage(informationalMessage); } } public interface ILogFactory { ILog Create(); } public interface ILog { void InformationalMessage(string message); }

How could you go about testing this class (I am demonstrating test-after, though the end solution was driven out test first). Here are two tests that prove out the functionality of the log class:

 

[Test] public void Factory_should_be_leveraged_to_create_logger() { MockRepository mockery = new MockRepository(); ILogFactory mockLogFactory = mockery.DynamicMock<ILogFactory>(); ILog mockLog = mockery.DynamicMock<ILog>(); using (mockery.Record()) { Expect.Call(mockLogFactory.Create()).Return(mockLog); } Log.InitializeLogFactory(mockLogFactory); using (mockery.Playback()) { Log.InformationalMessage("blah"); } Log.InitializeLogFactory(null); } [Test] public void Informational_message_call_should_be_delegated_to_created_logger() { MockRepository mockery = new MockRepository(); ILogFactory mockLogFactory = mockery.DynamicMock<ILogFactory>(); ILog mockLog = mockery.DynamicMock<ILog>(); using (mockery.Record()) { SetupResult.For(mockLogFactory.Create()).Return(mockLog); mockLog.InformationalMessage("blah"); } Log.InitializeLogFactory(mockLogFactory); using (mockery.Playback()) { Log.InformationalMessage("blah"); } Log.InitializeLogFactory(null); }

As you can see, these are completely interaction based tests (hence the lack of assertions). I broke up the test for leveraging the factory to create the logger and the delegation to the actual logger into 2 separate tests. I am also using the SetupResult vs Expect in the second test to indicate that, it is not the behaviour I care about testing. It just needs to be there to focus on what I actually care about, the delegation of the Log class to the created ILog implementation (which is currently a mock itself).

The nice thing about this scenario is that neither the Log class, or the clients of the Log class are aware/tied to any one particular ILog implementation. As long as I can prove out the correct interaction between the Log class and it’s dependency, I should be able to swap in any implementation of ILogFactory and the Log class is none the wiser.

The only downside to the current implementation of the Log class is the need for the static field and static method to initialize that field. Outside of introducing other concepts too early, the initialization of the Log class with an ILogFactory implementation is something that can be done at application startup. It is very likely that is should be one of the first things that should happen, as many other objects in the system may rely on the functionality of the Log class.

The only problem with the current solution is that the Log class is coupled to any changes that may occur in the ILog interface. To ensure that the ILog interface can vary independently of the Log class, I am going to make a small change to the API. Instead of calling methods on Log directly. I am going to change Log, and ILogFactory to the following:

public class Log { private static ILogFactory logFactory; public static void InitializeLogFactory(ILogFactory logFactory) { Log.logFactory = logFactory; } public static ILog For(Type type) { return logFactory.CreateFor(type); } public static ILog For(object itemThatRequiresLoggingServices) { return For(itemThatRequiresLoggingServices.GetType()); } }

The nice thing about this change is that now the Log class does not need to have a mirroring method for every method that may exist on the ILog interface. The ILog interface is now free to change independently of the Log class. Which means I could easily add methods to log with a specific logging level, etc. The Log class is now strictly a “Static Gateway” to Logging functionality.

I'll finish up by making a call into this API from the Calculator class: 

public class Calculator { public int Add(int number1,int number2) { Log.For(this).InformationalMessage("About to add 2 numbers"); return number1 + number2; } }

At this point the Calculator class is completely oblivious to the fact that there is currently no concrete ILogFactory/ILog implementation. It just cares about leveraging the Logging gateways “Static” method to have it log on its behalf. When we actually swap in a real ILogFactory & ILog, neither the Calculator or Log class will have to change at all.

In completion here is a quick implementation of an ILogFactory/ILog pair that will output log messages to the console (I’ll leave it up to you to come up with a more testable implementation of the following 2 classes):

public class ConsoleLogFactory : ILogFactory { public ILog CreateFor(Type type) { return new ConsoleLogger(); } private class ConsoleLogger : ILog { public void InformationalMessage(string message) { System.Console.Out.WriteLine(message); } } }

If you were to run the application now (after initializing the Log class with this ILogFactory implementation), you would see messages output to the Console, whenever the Add method on Calcuator was invoked.

In my next post, I’ll demonstrate how to leverage the Static Gateway pattern with respect to an IOC gateway, that will allow me to remove the static field and initilization method on the Log class.

Comments [7] | | # 
 Friday, September 28, 2007
Friday, September 28, 2007 1:12:49 PM (Mountain Standard Time, UTC-07:00) ( Patterns | Programming )

I am going to be posting a small sample that demonstrates what I was talking about in my post describing using Screen Bound DTO’s Presentation Model.

In chatting with a couple of people, they correctly fixed my terminology to use lingo that most people have already got a cursory knowledge of. So with that said, the technique that I described with regards to objects that are designed specific to the screens that they are servicing is the concept of a Presentation Model. DTO’s are still in the picture with respect to the messaging that can occur between presenter and service (and vice versa). The presentation model is their to satisfy the needs of the UI, be if for databinding or other UI needs (such as coloring for rows in a grid, highlighting customers with bad credit etc).

Ok, now we are all on the same page.

 

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] | | # 
 Wednesday, June 13, 2007
Wednesday, June 13, 2007 11:19:35 AM (Mountain Standard Time, UTC-07:00) ( C Sharp | Patterns )

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

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

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

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

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

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

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

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

Became this:

public ISegmentConfiguration CreateUsing(SegmentConfigurationParameters parameters)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

To recap, the refactorings are as follows:

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

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

 

public interface ISegmentConfigurationSpecificationBasedFactory : ISegmentConfigurationParametersSpecification,ISegmentConfigurationFactory { }

With that interface in hand SegementConfigurationFactory can become:

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

Which now leaves the SegmentConfigurationFactory adhering to OCP.

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

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

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

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

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

Comments [3] | | # 
 Friday, 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] | | # 
 Tuesday, October 31, 2006
Tuesday, October 31, 2006 9:26:10 PM (Mountain Standard Time, UTC-07:00) ( Patterns )

I was recently asked the following question in an email:

Do you know where I can find information (blog or book) on how you are setting up your Domain Object (i.e. in your demo it was Northwind.Domain)?  Is that basically where you keep your rules (i.e. if it such and such customer then give them a 10% discount)?

I took this as a question as to how to go about setting up the layers in the application. Which caused me to go on the following tangent:

The layering of a project is something that definitely falls into a personal taste category. There are also lots of well known strategies/suggestions for layering an application. Another thing to note is that there is not necessarily a one-to-one relationship between physical/logical layer and a VS project. In the example applications that I have shown I have definitely used a solution that demonstrates one physical project per layer of concern. There are definitely many times on large projects where one logical/physical layer is composed of many physical VS.Net projects.

The domain layer is where your entities, value objects, business rules, validations, and a whole host of other objects go. This is the heart of the system, and is often the place where you can drive out solutions in a test first manner to ensure that you are able to solve a particular business problem in a clean and meaningful way. For the most part, the domain layer consists of plain old objects. Saying plain does not mean that they are necessarily simple. It means that the domain should be completely oblivious to any “services” that will be required to support it in the context of the running application (mapping being one of the most well known services).

A layering scheme that I have come to use a lot is the following:

· UI (User interface components, web forms,winforms, mobile screens, consoles)

· Presentation (View interfaces, presenters, formatters, mappers (oo mappers not OR mappers), globalization)

· DTO (Data transfer objects, used for passing information between the UI, presentation, and service layers). Again, depending on the project you may not need to introduce a separate set of objects to marshal data between the presentation and service layer. You may opt instead to pass your domain objects to the presentation layer directly.

· Service (Transaction control, authorization, domain object coordination), there are definitely times when you may not want to think about utilizing a service layer. For the amount of work involved in creating a simple façade ,around your application functionality, I almost always use one.

· Data Access (O/R mapping, this layer can get pretty big if you are not taking advantage of existing O/R mappers)

· Utility (Utility classes that can be consumed and used by any layer in the application, each class follows the single responsibility principle, and great care is made to ensure classes in this layer are not just catch-alls for functionality that was not able to be placed correctly on an object in another layer.

This is a very basic layering scheme. Depending on the needs of the application, there may be more levels of indirection that are required.

Comments [8] | | # 
 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] | | # 
 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] | | # 
 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] | | # 
 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 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] | | # 
 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] | | # 
 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] | | # 
 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] | | # 
 Friday, January 06, 2006
Friday, January 06, 2006 2:59:41 PM (Mountain Standard Time, UTC-07:00) ( C Sharp | Patterns )
Last year I had the opportunity to present several MSDN webchats related to application development with .Net. The following links will allow you to view the webchats on demand and at your leisure.

Enjoy!

Implementing the MVP pattern in Win forms Applications
Utilizing the Factory and Strategy patterns to alter program behavior
Change notification in the UI using the Observer pattern
Testing the UI Layer in Smart Client Applications (Using MVP Pattern)
Intro to TDD and Smart Clients

Comments [5] | | # 
Friday, January 06, 2006 8:29:11 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C Sharp | Patterns | Training | VS2005 )
For all who may be interested. On the week of February 6th - 10th I will be holding a .Net 2.0 Bootcamp in Calgary,AB.

The event will be held at CTC TrainCanada in Calgary.

It will be an intense week of getting up to speed on building enterprise level applications with the .Net 2.0 Framework. You can view the course outline here and if you are interested in attending you can register here.

Look forward to seeing you there.
Comments [0] | | #