About Me

Training

Nothin But .Net Developer Bootcamp

Navigation

Search

Categories

On this page

Calgary Code Camp Material
Calgary Code Camp - Huge Success
Enhancing Images With The Decorator Pattern
Automating Your Builds With NAnt - Part 7
SpeedFiler and Sql Prompt
One Small Request
ReSharper 2.0 Is Officially Here!
Validation In The Domain Layer - Take One
Calgary Code Camp - Topic
Site Issues (Apologies)
Source Code For Build Better Collections With Generics Article
NAnt Starter Series
TDD By Example - Money
Running all of the sql files in a directory
Automating Your Builds With NAnt - Part 6
Dealing with drop down lists with the MVP pattern
Code For Edmonton .Net User Group Meeting (April 27th)

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: 407
This Year: 132
This Month: 3
This Week: 0
Comments: 1082

 Wednesday, May 31, 2006
Wednesday, May 31, 2006 1:35:18 PM (Mountain Standard Time, UTC-07:00) ( Presentations )

I have uploaded the demo and slide deck for the presentation that I delivered at the Calgary Code Camp this past weekend. The presentation was all about 3 key principles:

  • Test Driven Development
  • Dependency Inversion principle (yes inversion not injection)
  • Dependency Injection

I am going to try to make time to re-record the session on my laptop so that I can put it up for others to view. If you have any questions about the slide deck or the demo, please do not hesitate to contact me.

The zip file is here.

Comments [1] | | # 
Wednesday, May 31, 2006 12:45:53 PM (Mountain Standard Time, UTC-07:00) ( Presentations )
This is a little late (better late than never). This past Saturday marked the hosting of Calgary's first ever .Net Code Camp. The turnout was amazing (especially for a Saturday), and lots of fun was had by all. I delivered a presentation titled : TDD, Dependency Injection and the Data Access Layer. I am going to be posting my code along with a video for all my remote readers who were unable to attend. The next code camp on the horizon is the Edmonton code camp. I have a couple of ideas in my head on presentation material, but it is a long way off so I’ve got lots of time to formulate/receive ideas. Thanks to everyone who provided feedback (positive and negative) on the presentation, it is always appreciated.
Comments [1] | | # 
 Friday, May 26, 2006
Friday, May 26, 2006 2:23:44 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C# | Patterns )

I have been thinking for a while about coming up with a series of posts that talk about real world applications of many of the design patterns that get thrown around. I have been meaning to post about the decorator pattern for quite some time. I was trying to come up with an example that would practically demonstrate the Decorator pattern and then it hit me. An image browser. Here is the sample app in action:

MainForm

OpenDialogViewingPlainImage

As you can see, it is pretty standard fare. When the button is clicked, a file dialog browser will pop-up and the user will have the option to choose a file to display. If they pick a file the file will be displayed. If they don’t pick a file nothing will happen. The code-behind for the form is pretty simple:

public partial class ImageBrowser : Form, IImageBrowserView { private OpenFileDialog openFileDialog; private ImageBrowserPresenter presenter; public ImageBrowser() { InitializeComponent(); presenter = new ImageBrowserPresenter(this); openFileDialog = new OpenFileDialog(); HookupEventHandlers(); } private void HookupEventHandlers() { this.retrieveImageButton.Click += delegate { presenter.DisplayImage(); }; } public bool WatermarkRequired { get { return watermarkCheckBox.Checked; } } public string ImagePath { get { openFileDialog.ShowDialog(); return openFileDialog.FileName; } } public void Display(Image image) { this.pictureBox.Image = image; } }

As you can see, I am using the model view presenter, and the presenter has the responsibility of pushing an image to the view that the view will display. This article is not about the MVP so try not to get too hung up on it if you have not seen it before. As you can see from the code, the main work will be performed inside the DisplayImage method of the presenter. The code for the presenter turns out to be very trivial: 

public class ImageBrowserPresenter { private IImageBrowserView view; public ImageBrowserPresenter(IImageBrowserView view) { this.view = view; } public void DisplayImage() { string pathOfImageToDisplay = view.ImagePath; if (IsValid(pathOfImageToDisplay)) { view.Display(Bitmap.FromFile(pathOfImageToDisplay)); } } private bool IsValid(string imagePath) { return !string.IsNullOrEmpty(imagePath); } }

So what is going on here. When the view tells the presenter to “DisplayImage”, the presenter turns back around to the view and asks it for the path of the image that it should display:

string pathOfImageToDisplay = view.ImagePath;
 
 

The view (form) responds to this request by popping up a file open dialog and returning the filename of the dialog to the presenter:

 

public string ImagePath { get { openFileDialog.ShowDialog(); return openFileDialog.FileName; } }

The code in the form is actually feature complete for this example. There will be no changes required to make to the code behind to support new functionality (for this scenario). A scenario that people often run into for commercial web sites it needing to apply a water mark to an image so that people cannot just download their images and use them as their own. This is our first perfect candidate for the decorator pattern. We want to “Decorate” an image with a watermark, that brands it as our own.

What is the Decorator Pattern

Simply (and the decorator is a very simple,elegant pattern) the Decorator pattern allows us to attach additional responsibilities/behaviours to an object without the need for subclassing. The following class diagram shows the structure of a typical decorator implementation:

Decorator(taken from DoFactory.com)

One of the principles of the decorator pattern ensures that to the client, a decorator looks no different that the object it is decorating. In this scenario we want to decorate Images. The base class for Images in the framework (Bitmaps and Metafiles) is the System.Drawing.Image class. Unfortunately I can’t inherit from this as the constructor for an Image is internal. I also can’t inherit from Bitmap as that class is sealed. How can I decorate when I can’t create a Decorator that implements the same interface as the object it is decorating. Adding a small layer of indirection will solve this problem:

 

public interface ICoreImage { Image Picture { get; } }

I now have an interface that can be implemented by a class that really just wraps an image:

 

public class CoreImage : ICoreImage { private Image image; public CoreImage(Image image) { this.image = image; } public Image Picture { get { return image; } } }

As the saying goes "Another layer of indirection will solve any problem!!, now I have an interface that can be readily implemented by any class. Now, I promised that no changes would affect the code-behind of the form in anyway. To make use of this new class, I just need to change the presenter a little:

public void DisplayImage() { string pathOfImageToDisplay = view.ImagePath; if (IsValid(pathOfImageToDisplay)) { view.Display(GetImageFrom(pathOfImageToDisplay).Picture); } } private ICoreImage GetImageFrom(string pathOfImageToDisplay) { return new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); }

All I have done is introduced a method into the presenter that will retrieve an ICoreImage from a filename. Once the DisplayImage method retrieves the ICoreImage, it invokes the Picture property to return image data to the view. The current model of the application looks as follows:

initialmodel

We now have to deal with a new requirement. When the user has the “Watermark” checkbox checked, the image should display with a watermark rendered on it. To accomplish this new requirement we can come up with a decorator that will add the watermark to the image it is decorating. In this scenario I am only going to utilize a text based watermark. Options for a Watermark are encapsulated in a class called WatermarkOptions:

public class WatermarkOptions { private const int DEFAULT_SIZE = 26; private static readonly Font DEFAULT_FONT = new Font("Consolas", DEFAULT_SIZE, FontStyle.Bold, GraphicsUnit.Point); private Color color; private Font font; private string watermarkText; private Brush brush; private StringFormat format; public WatermarkOptions():this(DEFAULT_FONT,"SAMPLE",new StringFormat(StringFormatFlags.FitBlackBox),new SolidBrush(Color.Red)) { } public WatermarkOptions(Font font, string watermarkText,StringFormat format,Brush brush) { this.font = font; this.watermarkText = watermarkText; this.format = format; this.brush = brush; } public Font Font { get { return font; } } public string WatermarkText { get { return watermarkText; } } public Brush Brush { get { return brush; } } public StringFormat Format { get { return format; } } }

As you can see, all this class contains is different settings for a watermark. Notice the use of the overloaded constructor, which allows people to construct a watermark and settle with defaults. To make use of this class we will create a “WatermarkDecorator”. The decorator (from the clients point of view) has to look the same as the object it is decorating. In our case, the client is the “DisplayImage” method of the presenter. Because we have the ICoreImage interface, I can utilize it to create the WatermarkDecorator:

public class WatermarkDecorator : ICoreImage { private const int BORDER = 4; private ICoreImage coreImageToWatermark; private readonly WatermarkOptions options; public WatermarkDecorator(ICoreImage coreImageToWatermark) : this(coreImageToWatermark, new WatermarkOptions()) { } public WatermarkDecorator(ICoreImage coreImageToWatermark, WatermarkOptions options) { this.coreImageToWatermark = coreImageToWatermark; this.options = options; } public Image Picture { get { return DecorateWithWatermark(coreImageToWatermark.Picture); } } private Image DecorateWithWatermark(Image picture) { using (Graphics graphics = Graphics.FromImage(picture)) { SizeF textSize = graphics.MeasureString(options.WatermarkText, options.Font, picture.Width - BORDER, options.Format); RectangleF textRectangle = new RectangleF(BORDER, BORDER, picture.Width, textSize.Height); graphics.DrawString(options.WatermarkText, options.Font, options.Brush, textRectangle, options.Format); graphics.Flush(); return picture; } } }

Now you can see the Decorator pattern in action. Decorators always need to know about the object they are adding behaviour/functionality to, a great way to accomplish this is through constructor injection. When constructed with only an image, the decorator makes use of the parameterless WatermarkOptions constructor, to create options with default settings. Remember, decorators are adding new functionality to existing objects at runtime, the magic of adding the watermark happens when the Picture property on the decorator gets invoked. Instead of just immediately delegating to the object being decorated, it invokes the “DecorateWithWatermark” method, passing in the image retrieved from the underlying “decorated” ICoreImage. The DecorateWithWatermark method contains the logic to apply a watermark to the image, making use of the WatermarkOptions that got passed in. I am not going to delve into the details of the graphics jargon, for the most part it is pretty simple.

Ok, so I have this decorator, how do I use it? Switching back to the method in the presenter that actually instantiates the CoreImage, I can apply the decorator quickly by performing a quick check as to whether the user wants Watermarks applied:

 

private ICoreImage GetImageFrom(string pathOfImageToDisplay) { ICoreImage image = new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); return (view.WatermarkRequired ? new WatermarkDecorator(image) : image); }

You will note that the DisplayImage method in the presenter did not need to change at all, why? Because all it cared about was when it called the GetImageFrom method, was that it received an ICoreImage implementation, it doesn't know or care if it is a decorator. If I run the application now any files that are opened while the checkbox is checked will have a watermark drawn over them:

imageshownwithwatermark

Our revised class diagram looks like so:

revisedmodel

To finish off, a decorator also doesn't care what it is decorating either, as long as the object that it is decorating implements the same interface as what it does. So if the customer came to you all of a sudden and said “Regardless of whether the image has a watermark or not, we want a border around all images”, you could satisfy that requirement with another discrete decorator:

 

public class BorderDecorator : ICoreImage { private const int PEN_WIDTH = 10; private ICoreImage imageToDecorate; public BorderDecorator(ICoreImage imageToDecorate) { this.imageToDecorate = imageToDecorate; } public Image Picture { get { return WrapWithBorder(imageToDecorate.Picture); } } private Image WrapWithBorder(Image picture) { using (Graphics graphics = Graphics.FromImage(picture)) { RectangleF border = new RectangleF(0, 0, picture.Size.Width, picture.Size.Height); Pen pen = new Pen(new SolidBrush(Color.Black), PEN_WIDTH); graphics.DrawRectangle(pen,border.X,border.Y,border.Width,border.Height); graphics.Flush(); } return picture; } }

To ensure that all images have borders, I can just apply the new decorator to the existing decorator!!:

 

private ICoreImage GetImageFrom(string pathOfImageToDisplay) { ICoreImage image = new CoreImage(Bitmap.FromFile(pathOfImageToDisplay)); return new BorderDecorator(view.WatermarkRequired ? new WatermarkDecorator(image) : image); }

With that change applied, if I run the application now, all images (watermarked or not) will have a border around them:

plainimagewithborder  watermarkedimagewithborder

Now of course. In this example I had the presenter explicitly wrap the objects with decorators, but think about the flexibility of introducing factories/composite decorators that would allow the code in the presenter to stay static also. But those are patterns for another day!!

If anyone wants the source for this entry, please contact me.

TODO
Comments [5] | | # 
 Thursday, May 25, 2006
Thursday, May 25, 2006 8:14:51 AM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C# | Tools )

It has been quite a bit of time since the last installment of the NAnt Starter Series. We left off being able to successfully compile and test the main libraries of our application, and we progressed to bringing the database into the fold and looked at ways to manage the database in a multiple developer environment. In this installment we are going to talk about compiling and distributing the web portion of the application. Specifically, we are going to write a NAnt target that will build and deploy our entire web application into a directory that can be immediately deployed to a remote server if need be. Take a look at the current solution structure that is set up:

SolutionStructure

As you can see from the diagram, in this example I am going to be using the web-site project model, as opposed to the newly available Web Application Project model. You will quickly see that the only file that exists in this project is the ViewCustomers.aspx file. I am not using any of the new directories like the App_Code, App_Data etc. My web project should be extremely simple, consisting of purely UI elements like:

– Web Pages

– User Controls

– JavaScript Libraries

– Styles and Templates

 

By limiting the amount of code that is placed in this project, I can write unit tests against the real objects that will actually get work done. These objects , of course, live in projects separate from the web application. You might be asking yourself “Where is the web.config file?”. That file is actually a template file that will have pre-processing done on it during the build process. The contents of that file before processing look as follows:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">       
 <appSettings>  
  <add key="DatabaseConnection" value="SqlServer"/>
 </appSettings>
 
 <connectionStrings>
  <add name="SqlServer"
   connectionString="@CONFIG_CONNECTION_STRING@" 
   providerName="System.Data.SqlClient"
  />
 </connectionStrings>
 <system.web>
  <compilation debug="true"/>
  <authentication mode="Windows"/>
   <authorization>
       <deny users="?" />
   </authorization>
  <customErrors mode="Off" />
  <sessionState mode="Off" />  
 </system.web> 
</configuration>

If you look at the connectionStrings element, you will notice that the SqlServer connectionString is set up as a replaceable token in the Web.config.template file. Again, this is to ensure that at deploy time, the connectionString will be replaced with the appropriate string based on the environment that is getting deployed to.

Ok, let’s turn our attention to the process of building and deploying the application. Take a look at a new target that will compile our web application from inside of NAnt:

 <target name="asp.compile" description="Compiles the webapp" depends="init, compile">
        <delete dir="build\dist" if="${directory::exists('build\dist')}" />
       
        <loadtasks assembly="tools\nant\NAnt.Contrib.Tasks.dll" />
 
 <delete>
     <fileset basedir="build\aspprecompile">
  <include name="**\*" />
     </fileset>
 </delete>
        <copy todir="build\aspprecompile">
            <fileset basedir="src\app\DotNetRocks.Web.UI">
                <include name="*" />
                <include name="images\**\*.*" />
                <include name="javascript\**\*.js" />
            </fileset>
        </copy>

        <copy todir="build\aspprecompile\bin">
            <fileset basedir="build">
                <include name="*.dll" />
            </fileset>
        </copy>

        <mkiisdir dirpath="build\aspprecompile" vdirname="aspprecompile" />
        <exec program="C:\WINDOWS\Microsoft.NET\Framework\${framework.version}\aspnet_compiler.exe"
  useruntimeengine="true">
            <arg value="-p" />
            <arg value="build\aspprecompile" />
            <arg value="-v" />
            <arg value="aspprecompile" />
            <arg value="build\dist" />
        </exec>
        <deliisdir vdirname="aspprecompile" />       
    </target>

Whoa, there is a lot going on here so let’s break it down piece by piece. We are making use of the “depends” attribute to ensure that the asp.compile target cannot be run until all of the supporting libraries have been compiled:

                         target name="asp.compile" description="Compiles the webapp" depends="init, compile"

Don’t worry about the deletes that are happening at the beginning of the target, they are just ensuring that cleanup happens from a prior build process. The first step to compiling the ASP application is copying all of the files that the ASP.Net precompiler will require for compilation into a transient build directory (I don’t want to affect my main web project directory in any way whatsoever):

<copy todir="build\aspprecompile">
            <fileset basedir="src\app\DotNetRocks.Web.UI">
                <include name="*" />
                <include name="images\**\*.*" />
                <include name="javascript\**\*.js" />
            </fileset>
</copy>

I continue by copying all of the assemblies that the web project uses into an appropriate bin directory under the aspprecompile directory. Again, I am just pulling from the build directory any dll’s that would have been created during the running of the compile target:

 <copy todir="build\aspprecompile\bin">
            <fileset basedir="build">
                <include name="*.dll" />
            </fileset>
 </copy>

If I were to stop the target there my build directory would look as follows:

BuildDirectory

The aspprecompile directory would look like this:

AspprecompileDirectory

And the aspprecompiles bin directory would look like this:

AspPrecompileBinDirectory

You will see that I am copying pretty much all of the files from the DotNetRocks.Web.UI directory into this transient precompile directory. That’s right every file, including code-behind files. Notice how at the beginning of the target I used the loadtasks task :

<loadtasks assembly="tools\nant\NAnt.Contrib.Tasks.dll" />

LoadTasks will load any custom NAnt tasks that are contained in the named assembly and make them available to you for use during the build process. The NAntContrib library, is an open source library that contains a plethora of tasks that you can make use of during your own build processes. The ones that I need specifically are the ones that let me manipulate IIS Virtual Directories. I create a new virtual directory called aspprecompile that will point to the build\aspprecompile directory:

 <mkiisdir dirpath="build\aspprecompile" vdirname="aspprecompile" />

All right the stage is set. The last time we compile a project we used the standard NAnt csc task that would compile a set of C# class files into a library. Even though there are cs files in the aspprecompile directory we cannot use the csc task to compile the web project. I need to take advantage of the ASP .Net precompiler to compile the web application for me. With .Net 2.0, you could actually deploy all of your *.cs files for the project into the web directory and the ASP.Net runtime would compile the cs files dynamically when the pages are requested. I am not a fan of this approach, I would rather just keep my source files out of the web directory completely. To allow you to do this, you have to take advantage of the ASP.Net precompiler. If you are not familiar with the ASP.Net precompiler you can read some more information about it here. I use the NAnt exec task to shell out to the asp.net precompiler to compile my site in place:

<exec program="C:\WINDOWS\Microsoft.NET\Framework\${framework.version}\aspnet_compiler.exe"
  useruntimeengine="true">
            <arg value="-p" />
            <arg value="build\aspprecompile" />
            <arg value="-v" />
            <arg value="aspprecompile" />
            <arg value="build\dist" />
        </exec>

 Notice I am using a modified method to pass parameters to the aspnet_compiler executable. The full commandline would expand to this:

aspnet_compiler.exe -p “build\aspprecompile” -v “aspprecompile” “build\dist”

The meaning of each of the arguments is a follows:

  • -p : Specifies the full network path or local disk path of the root directory that contains the application to be compiled. This option must be combined with the -v option.
  • -v : Specifies the virtual path of the application to be compiled
  • targetdir : This is not a named argument but if provided, specifies the directory to which the asp_compiler will place the final files for deployment

After running the target the build\aspprecompile directory looks no different that the before the compilation happened, but notice that a new directory has been added to the build directory:

DistDirectory

     The following screenshots show the contents of this directory:

    DistDirectoryContents   DistBinDirectoryContents

    Take a look at the interesting names that the aspnet_compiler generates for us!! Notice also, that although the aspprecompile directory contained a .cs file the the ViewCustomers.aspx page, the dist folder has no source files whatsoever!! The dist folder now contains everything that we would need to deploy to a production server. With the compilation safely taken care of I can go ahead and remove the temporary virtual directory I created for asp precompile purposes:

     <deliisdir vdirname="aspprecompile" />

    Again, the deliisdir task lives is a task that is defined in the NAntContrib library.

    To wrap it up, I can quickly add a target that will deploy the application to a local directory on my machine :

     

    <target name="deploy" depends="asp.compile">
            <deliisdir vdirname="DotNetRocks" failonerror="false" />
            <delete>
                <fileset basedir="deploy">
                    <include name="**/*" />               
                </fileset>
            </delete>
            <mkdir dir="deploy" />
            <copy todir="deploy">
                <fileset basedir="build\dist">
                    <include name="**\*" />               
                </fileset>
            </copy>
            <copy file="config\Web.Config" tofile="deploy\Web.config" /> 
            <mkiisdir dirpath="deploy" vdirname="DotNetRocks" authntlm="true" defaultdoc="Default.aspx" />
        </target> 

     

    I am not going to break this target down, as you have already seen all of the tasks that I am using. At the end of this target running I will be able to navigate to the ViewCustomers.aspx page by opening up my browser and typing in : http://localhost/DotNetRocks/ViewCustomers.aspx which brings me to:

    ViewCustomers

     

    TODO
    Comments [8] | | # 
    Wednesday, May 24, 2006 11:00:16 PM (Mountain Standard Time, UTC-07:00) ( Tools )

    I have been using SpeedFiler for the last couple of weeks and love the productivity it has provided with regards to managing my email. After reading the Igloo Coder mentioning SQL Prompt, I thought I would download it and give it a whirl. I won’t say no to intellisense for SQL!! It was shortly after this that I started noticing issues with SpeedFiler. I would go to file an item using the CTRL-SHIFT-V shortcut and the standard outlook Move-To dialog would pop up. The same applied for SpeedFilers “Go To Folder” command. I could however, successfully invoke these commands if I explicitly used the SpeedFiler menu items that activated the custom dialogs. I was emailing back and forth with the founder of SpeedFiler (that’s right, he truly stands behind his product) for a little while and he was offering lots of good tips to ensure that I was not messing anything up. It never even dawned on me that SQL Prompt could be the problem. Until, 20 minutes ago I realized that the only thing that differed between my machine configuration of today to yesterday was the installation of SQL Prompt. I fired up the options dialog of SQL Prompt :

    SqlPromptOptionsWindow

    By default, SQL Prompt runs “Enabled” in the tray. When I changed the status to “Off”, bang, speedfiler worked again like a charm. I mailed Itzy and let him know that this may be an issue to look into. But for now, I’ll know to turn SQL Prompt off, when I’m not doing any DB work.

    Comments [0] | | # 
     Wednesday, May 24, 2006
    Wednesday, May 24, 2006 10:34:31 AM (Mountain Standard Time, UTC-07:00) ( )

    To all the awesome readers of this blog, I am requesting your help with promoting some of these entries on DotNetKicks.com. All of my new posts (I am trying to revisit the old ones) will have a link to kick the story to dotnetkicks. If you are a member, please kick these stories so that a wider audience can view them. I have already kicked up each of the posts in the entire NAnt Starter Series, so please feel free to add your own kicks to these items, as well as the main starter series link also!!

    Thanks so much. And the front to back sampler, starts later on today!!

    Comments [1] | | # 
     Tuesday, May 23, 2006
    Tuesday, May 23, 2006 9:06:59 PM (Mountain Standard Time, UTC-07:00) ( Tools )

    Rs2banner

    Well, it is finally official (I am late with this post, as my blog has been having issues). ReSharper 2.0 is now unleashed for public “stable” consumption. What is ReSharper? In my opinion, one of the most kick-butt tools for code-centric .Net 2.0 developers. The list of features of this product is fantastic, for me the top of the list are :

    • Refactorings (too many to name)
    • Move type to new namespace
    • Code Generation features inline with TDD developers
    • Find Usages - Rocks
    • Go To Type – CTRL -N (start typing and list will filter to match types with name)
    • Go To File – CTRL – SHIFT – N (start typing and list will filter)
    • Integrated unit test runner
    • Live Templates (extremely easy template syntax for creating your own Live templates)
    • File Templates
    • NAnt and MSBuild intellisense

    I could go on and on, but the list of features that I use on a given day are too many to mention here. Download the trial and give it a whirl!!

    Comments [0] | | # 
     Friday, May 19, 2006
    Friday, May 19, 2006 1:45:19 PM (Mountain Standard Time, UTC-07:00) ( .Net 2.0 | C# )

    I have been receiving a lot of email's centered around the topic of validation in the domain layer. If you are a developer who is trying to utilize a rich domain layer in your applications, then you might have struggled with the whole issue of validation. Conceptually, most of us know how to perform validation using some predefined set of business rules. Unfortunately, the way the validation is implemented often leaves us with a solution where validation is scattered haphazardly throughout multiple layers in the application. Worse yet, is the case where validation is duplicated in multiple layers in the application, and changing a rule entails changing the code in multiple places. To demonstrate one solution to this issue I am going to focus on building a simple voting application. Some of the business rules are as follows:

    • Must be between the age of 18 – 75 to vote (yes there is an upper limit!!)
    • Must live in the country the candidate is running for

    Ok, so my rules about the voting process are a little weird to say the least, but hey, it’s just an example. As well as the rules for voting, upon submitting a vote the person voting has to supply all of the required voter information:

    • FirstName
    • LastName
    • Age
    • Address
    • Gender
    • CountryOfResidence

    Take a look at the class diagram for the initial domain model:

    InitialClassDiagram

    As you can see. This is a pretty simple domain. Let’s switch back to validating the simple properties for now. Let’s start with the strings (firstname,lastname,address). Remember, I am going to be performing all of my validation in the domain layer, so the buck stops here. I am not trusting anything that may have come from the UI. I am going to write a test to capture the validation I want to perform against the first name of a person:

     

    [Test]
    public void ShouldValidateUsingRule()
    {
    IBusinessRule
    <Person> firstNameRule = new BusinessRule<Person>(delegate(Person person)
    {
    return string.IsNullOrEmpty(person.FirstName);
    });

    Person personWithInvalidFirstName
    = new Person("", "", "", 0, null, null);
    Person personWithValidFirstName
    = new Person("JP", "", "", 0, null, null);

    Assert.IsTrue(firstNameRule.IsBrokenBy(personWithInvalidFirstName));
    Assert.IsFalse(firstNameRule.IsBrokenBy(personWithValidFirstName));


    }

    As you can see from this test. I am trying to encapsulate the simple business rule “A person must have a non-null firstname” into a full fledged BusinessRule object instance. You will notice the use of the Predicate delegate that I plan on passing into the constructor of the BusinessRule class. This is the method that will perform the validation against the person. The implementation of this class should prove to be fairly simplistic:

     

    public class BusinessRule<T> : IBusinessRule<T> { Predicate<T> brokenPredicate;

    public BusinessRule(Predicate<T> brokenPredicate)
    {
    this.brokenPredicate = brokenPredicate;
    }

    public bool IsBrokenBy(T item)
    {
    return brokenPredicate(item);
    }
    }

    Notice how I am making use of generics so that I can use the BusinessRule to work with any type. When I instantiate the BusinessRule for a certain type it will also constrain the type for the Predicate. If you take a look at the IBusinessRule<T> interface. You will notice that there is not much to it:

     

    public interface IBusinessRule<T> { bool IsBrokenBy(T item);
    }
     
     
     

    I now want a way to encapsulate a set of rules that need to be checked against an entity. Let’s take a look at anothe