Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

The Static Gateway Pattern
Start Flying With ReSharper (and windows in general) - Use the Alt-Key
Drop the temporary lists and leverage yield
England Generics Presentation source code
Running VMWare images on Windows and Macs
Directory Structure For Projects

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: 337
This Year: 62
This Month: 13
This Week: 3
Comments: 889

 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, October 12, 2007
Friday, October 12, 2007 8:52:36 AM (Mountain Standard Time, UTC-07:00) ( General | Programming )

I received this question a couple of days ago that I thought I would quickly take the time to respond to a question:

“At work over the past few weeks we’ve been watching your patterns talks on dnrTV.  We’ve found them really enlightening (we’re implementing some of them as I write this), but what has really amazed some of us is your use of ReSharper.  We have a printout of the default keymap for ReSharper, but we notice that you do some things using the keyboard that we would love to be able to do (and, in fact, didn’t even know were options in ReSharper).  One co-worker surmises that you have mapped your own keyboard shortcuts.  Is this the case, or are you just very knowledgeable of all of the shortcuts that ReSharper provides out of the box.  Either way, do you have any sort of keyboard mapping that you would be willing to share?  We’re always looking into ways to be better  - and what better way than to have a tool do all of the heavy lifting for you!!”

 

Here is the trick to getting really proficient with not just ReSharper, but also any and every program that windows throws at you. Start using the ALT key more!! With respect to the stuff that I am doing in ReSharper, let me confess that I have not mapped any extra keybinding other than the ones that come out of the box during the install.. Since 1.0 of ReSharper I have been leveraging , and will continue to use, the IntelliJ keyboard mappings. Before you can start leveraging the ALT key more effectively with ReSharper there is one thing you will have to do (you don’t have to, but it will save you an extra “R” in the keyboard sequences). If you are using VS2005 and you have both Refactor and ReSharper menu items (the Refactor menu is provided by the default install of VS2005, and will only show up if you are in a code file) you will need to remove the Refactor menu from your toolbar. If you want to get rid of it for good follow these steps:

 

  • Right click on the toolbar in VS and choose customize
  • Select the Commands tab
  • Click the Rearrange commands button
  • Ensure that the Menu Bar option is selected and choose the Refactor menu from the drop down list.
  • The Controls list should now be populated with all of the Refactor menu items.
  • Highlight the first item in the Controls list and hit ALT- D (delete).
  • Take care when deleting the last item as the list will automatically populate with the next set of controls from another menu item that you may not want to delete.
  • Click the close button on the dialog, and click the close button on the main dialog.
  • Voila, the Refactor menu item should be gone from your toolbar!!

Here are a couple of ReSharper key sequences that I use all of the time (I’ll leave it up to you to experiment):

  • ALT -> R -> N -> Enter – Create new class from file template template. This works because the first template in my list is the class template.
  • ALT -> R -> N -> I – Create new interface from file template.
  • ALT -> R -> N -> F – Create new TestFixture from file template
  • ALT -> R -> N -> M – Create new MockTestFixture from file template
  • ALT -> R -> W -> D – Bring up the TODO exlorer
  • ALT -> R -> O – Bring up ReSharper options
  •  

With respect to the TestFixture and MockTestFixture files templates, these are just one of many custom file templates that I use to help me get off the ground faster. I leverage ReSharper file templates a lot as it helps me start with code files that are much leaner than the studio counterparts.

 

Using the ALT key more will allow you to drop the mouse more than you think and start leveraging features directly from the keyboard.

 

Develop with Passion!!

 

 

Comments [2] | | # 
 Wednesday, October 10, 2007
Wednesday, October 10, 2007 8:14:51 AM (Mountain Standard Time, UTC-07:00) ( Programming )

I see lots of code bases throwing IList<T>, List<T> etc all over the place when half of the time all they really need is to return a set that can be either databound, or walked over and processed one at a time. For the scenarios where you don’t need to count the number of items or much of the other functionality that is exposed by the IList<T> interface, you can start to leverage the yield keyword more to tighten up the code.

Here is a common example, a service layer method call that returns a list of DTO’s that can be consumed by some sort of binding target. Assume that you are mapping domain objects into DTO’s to be consumed by the upper level layer (which could then be mapped into a presentation model). Let’s also assume that you have the following

  • Customer Domain Class
  • CustomerDTO Class
  • ICustomerDTOMapper interface (implementation knows how to map from domain to dto).
  • ICustomerRepository – repository interface to find customers
  • CustomerTask – service layer class

Here is the CustomerTask class with its appropriate dependencies injected, and the existing GetAllCustomers method using the temporary list:

 

public interface ICustomerDTOMapper { CustomerDTO MapFrom(Customer customer); } public interface ICustomerRepository { IEnumerable<Customer> All(); } public class CustomerTask { private ICustomerRepository customerRepository; private ICustomerDTOMapper customerDTOMapper; public CustomerTask(ICustomerRepository customerRepository,ICustomerDTOMapper customerDTOMapper) { this.customerRepository = customerRepository; this.customerDTOMapper = customerDTOMapper; } public IEnumerable<CustomerDTO> GetAllCustomers() { IList<Customer> results = new List<Customer>(); foreach (Customer customer in customerRepository.All()) { results.Add(customerDTOMapper.MapFrom(customer)); } return results; } }

With a  small change the code in the GetAllCustomers method can be changed to the  following:

public IEnumerable<CustomerDTO> GetAllCustomers() { foreach (Customer customer in customerRepository.All()) { yield return customerDTOMapper.MapFrom(customer); } }

This is a small change, but handy nontheless. Again, this is not new information, I just think that more people could start taking advantage of yielding in more situations where full blown lists are not called for.

Comments [5] | | # 
 Wednesday, October 03, 2007
Wednesday, October 03, 2007 9:21:38 PM (Mountain Standard Time, UTC-07:00) ( Presentations )

Back on the 17th of September, the good folks at the NxtGenUG in Oxford, England were kind enough to extend me an invitation to speak.

The presentation went well and I promised to make the code available as soon as I could. Looks like it took me a little bit longer than I planned!!

Thanks for giving me the opportunity to come and share. It was awesome to be back in England!!

You can download the source for the presentation here.

Comments [2] | | # 
Wednesday, October 03, 2007 10:22:25 AM (Mountain Standard Time, UTC-07:00) ( General )

As I said the other day, I finally bit the bullet and purchased an awesome MacBook pro!!

From day 1 (in the Mac world) I have been utilizing VMWare Fusion as my virtualization software of choice. This is a list of things that I should have done before I made the switch from my windows VM’s to VM Ware Fusion.

  • Make sure that when you create your images in VMWare Workstation, that you select the option to split the disk files into 2GB increments. This is imperative as ,if you are like me, and need to run the images on both Mac and Windows machines, then the only file system that you will be able to use effectively with both (without extra tools that are not officially supported) is the FAT32 files system.
  • To further emphasize point one, if you don’t check off the option (which I did not do when creating my original images), you will most likely fail to be able to copy the images to a FAT32 drive as the virtual disks will most likely be over the 4GB file size limit for a FAT32 file.
  • Don’t copy the original images onto a Mac partition which can allow for larger files sizes as once you copy it onto the Mac, you won’t be able to run the VMWare utility to split the original disk file back into 2GB increments, as this utility is not present in Fusion. Keep the images on an XP/Vista host and run the VMWare Workstation disk manager utility that can be used to convert the virtual disk file from a single large file to multiple files of a specified size. Once you have completed this step, you should be able to successfully copy the images onto a FAT32 partition, circumventing the 4GB file size limit.

…. As an aside, I made all sorts of mistakes when migrating my images to work with both Mac and Windows. Of course, this is ultimately how you learn the right way to do it!!

Just as a side note, I think I seriously messed things up when opening the images multiple times on both windows and Mac. It got to the point where I had to open up both the vmx file and the vmdk files to ensure that pathing issues were not present.

It just so happened that somewhere during the course of flipping constantly between a windows host and the mac host, the paths of some of the files got munged up. Once I edited the files manually to resolve the path issues, it was all good.

Just in case any of you newly acquainted with a Mac and Fusion experience this issue, you may need to check to see if there are pathing issues in either of the sets of files I mentioned.

 

Comments [3] | | # 
 Monday, October 01, 2007
Monday, October 01, 2007 10:55:04 PM (Mountain Standard Time, UTC-07:00) ( Agile | General )

That last part in the title is to indicate that for me, this is something that has changed several times over the past year with a change happening even within the last month.

Let me stress the fact that I am a big automated build junkie, and am not really even a fan of compiling from within studio. To that end I do the majority of my work using studio + ReSharper as the editor, and NAnt (currently) as the compile/test tool coupled with FinalBuilder as my deployment tool.

Here is a snapshot of a root directory of one of my current projects:

Let’s break each of these items down so that there is a bit of explanation behind each one. Don’t worry about the .svn folder or the folders with underscores in front of them.

The config dir

This directory contains all of the files related to the configuration of the application. Things that I typically put in this directory are:

  • app.config file template (if you are not sure of the concept of file templates check out my NAnt starter series).
  • NHibernate mapping files (typically placed in a folder called mapping)
  • Log4Net config file template
  • Boo file template to configure Windsor

The docs dir

This directory should be fairly self explanatory, as it contains documentation artifacts related to the project. These can be things like stories, diagrams etc.

The lib dir

This directory contains all of the third party libraries that will need to be deployed to the client/server machine. Keep in mind that 3rd party libraries could also be app specific versions of in house libraries that you share between projects.

The src dir

This directory contains all of the code related artifacts that belong to the project. This application usually consists of the following 2 root directories:

  • app – Contains all of the code that will be compilable units that get deployed to production.

 

  • test – Contains all of the code that is related to testing the code that will get deployed.

I often break the test directory down into different subdirectories to clearly identify the types of tests that are contained:

  • unit
  • integration
  • ui

The src directory is organized in this structure so that I can quickly choose to ignore/include files that I want when I am compiling for either test or deployment.

The tools dir

This directory contains all of the supporting third party libraries that are there to serve the purposes of build automation, testing etc. Libraries that you might expect to find in here are:

  • NAnt
  • MBUnit/NUnit
  • NCover
  • NCoverExplorer
  • RhinoMocks

These libraries are essential during the build process, but they do not need to be present on the deployment machine as they are there to support the needs of automating and testing the application.

The local.properties.xml file

This file is there to account for the differences in individual machine configurations without cluttering the build file with knowledge of each specific developers machine in a team environment. Machine specific settings are kept in this file that each developer maintains their own copy of, and the settings in the file get leveraged during the build process to carry out the build automation tasks on each developers machine.

You will also note, that in the above diagram, I place my solution file right at the root so that it is quickly accessible and can be opened right from the checkout unit.

As you can imagine this physical folder structure does not correlate to what you would see in studio, as unfortunately, studio comes up with its own way to view your world.

In a latter post I’ll talk about how I have abandoned the notion of multiple projects inside of studio, in place of trusting developers to follow correct layer separation. This can be done, because once you stop using Studio as your build engine, a world of possibilities open up to how you go about laying out the physical code in your code base.

Why

The purpose for having this structure that I have outlined above is to have a completely atomic unit for your project. The goal being that someone new to the team, with a fresh install of the .Net framework (not even studio), should be able to check out the above project, make the appropriate machine specific changes to the local.properties.xml file, and run build.bat to compile and test the application. One of the directories that you don’t see in the image above, that is usually present on other apps that I write is the sql directory. As you can imagine, this directory contains all of the sql artifacts related to the project. Again, if a new developer checks out for the first time and tries to build/test, if there are databases to be created, they will be created, and then the code will compile and test.

Again, once you introduce the concept of build automation whether it be with NAnt, Rake etc, it opens the door and your mind to different possibilities with regards to how you go about laying out your project. No longer is your deployment model constrained to how you build your x number of projects in studio. You could have one physical project with 15 different folders that convey different namespaces/layers of the application (which you would originally have been using separate projects for) and you could choose in your build script to compile folders 1 – 5 into one assembly 6 -8 into another assembly etc. It is completely up to you.

There are so many other things that you can do when you start using this type of structure.

Comments [13] | | #