# Wednesday, August 19, 2009

I’m really liking Ruby on Rails for numerous reasons, and chief among these reasons is the ability to make a change to Ruby code and then refresh the browser to see the changes.  In other words I really like to avoid paying taxes, and in this case the compilation tax we all pay when using a static language.

For a couple of years now, since I started using MonoRail back in 2007 I’ve always felt that productivity could be improved by writing not only views in a dynamic language, but the controllers too (maybe the entire app). There’s just something refreshing about making a change in server side code and immediately see the changes without waiting 30 seconds for a complete recompile of the entire application.

Yesterday I was heavily doing some TDD on a very low level componenent in our application and wasted about 10 minutes waiting for Visual Studio to recompile the project I was working on… and then every other project that depends on that one. It takes a lot of focus to keep the TDD rhythm going when you’re forced to wait 1 minute between runs.  I just have one word for this, painful.

I can only imagine the benefits of doing TDD with a dynamic language since you have a whole lot more compile and test cycles with TDD than traditional programming techniques. The emergence of TDD over the past few years along with general acceptance of the practice will only further push teams towards dynamic languages. Sure you lose static type safety, but that’s why we have lots of good unit tests; and at the controller level that’s not a bad thing because you’re often dealing with key value pairs (think web form post or json DTOs) and a dynamic language is just a much more natural fit.

I’m not completely sold that unit testing at the controller level always makes sense, it often involves too many collaborators and whole lot of mocking. With automocking this isn’t so bad, but sometimes you have complex Ajax interactions in the middle and testing at a higher level via a web test sometimes makes more sense.

I’m hoping Microsoft seriously starts supporting dynamic languages (the DLR) and makes it a first class citizen rather than pushing it to the side in favor of more C# language sugar. I was very disappointed to see that Visual Studio 2010 has no support what so ever for Python or Ruby (unless I completely missed it somehow). Actually, I was shocked! The future belongs to dynamic languages and Microsoft is almost completely ignoring them. If they would support them officially along with ASP.NET MVC, the .NET world would be a whole lot better off.  Without dynamic languages the ASP.NET MVC 2 gets a B in my grade book (version 1 gets a C). Maybe its time to switch platforms?

.NET | IronPython | MonoRail | RoR
Wednesday, August 19, 2009 3:47:59 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, February 10, 2009
I think this should be pretty obvious to the next person to look at the code.
public class CrappyTextComparer : ITextCompareReportGenerator { ...

public class BeyondCompare : ITextCompareReportGenerator { ...


Tuesday, February 10, 2009 5:46:15 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, December 09, 2008

First of all let me say that I love IoC containers.  I love them not because they are trendy, or that they help testability, or that they allow me to use AOP. No, the real reason I love IoC containers is because they let me be lazy.

When I'm designing a class I don't need to worry about how I get can get a dependency.  The container allows me to worry about that later, by separating construction from logic.  Think about that for a second. Every time we use the new keyword we're explicitly creating a dependency between implementations.  Sometimes this isn't a big deal, but if we have a dependency that itself has 10 other dependencies this can get out of hand real quick.

Containers are smart, they know which implementations fulfill which contracts.  Somewhere on application startup we just tell the container what contracts and what implementations we have and it figures out the dependencies for us. If we have a FooService that requires an IBarRepository implementation, the container will automatically new up a class that implements IBarRepository and give it to FooService on creation.

Things get a bit less academic and a bit more troublesome when we try to implement a container with ASP.NET.  Normally we would want the container to new up our page instance and provide any dependencies it my have, but with ASP.NET we don't get the chance to have the container create the page instances with all of its required dependencies.  We could create our own page handler factory to do this, but that's a lot of work to do right.

Sprint.NET has its own page handler factory which works very well, but the last I checked, Spring.NET configuration is very verbose and requires that each page that needs the container to construct it be registered with the container. It works, but I prefer convention over configuration.

My favorite .NET container is Windsor because it allows me to do more with less work (configuration), but unfortunately there's no built in way to use Windsor in a truly IoC way with ASP.NET.  The only supported way is to get a reference to the container and ask the container to resolve an instance of something, which directly makes your page dependant upon the container, and generally just adds noise where its not needed; you would see calls like this all over:

IFooService service = Container.Resolve<IFooService>();

Rather than explicitly asking the container for a service instance, I would much rather have the container inject any required dependencies into my page instance when it gets constructed.  The problem is how do we do this with Windsor?

Windsor AspNetModule

The approach I've taken is to create an http module that will inject dependencies into a page just after instantiation using setter injection.  This means that the container will inject any dependencies that my page may have using public property setters.  Constructor injection would be better, but IMO its not worth the effort of having to create my own page handler factory, here we can rely on the tried and true ASP.NET infrastructure.  Perhaps someday I'll change my mind, but for now this is acceptable.

Since I plan on using this container with a large amount of legacy code that doesn't use dependency injection I want to make the use of the container somewhat explicit.  I don't want to waste cycles scanning over a page that doesn't need any dependencies injected.  To enforce this, I make the pages that require injection declare so using a class level attribute.  Here's a succinct example with one dependency:

[UsesInjection]
public partial class CustomerDetail : Page
{
    public ICustomerRepository CustomerRepository { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        customerGrid.DataSource = CustomerRepository.GetAll();
        customerGrid.DataBind();
    }
}

When the module sees the current handler with the UsesInjection attribute it scans the class for public setter properties and tries to resolve any dependencies by type. If an instance is registered with that type in the container, the module tries to set the property. Here an ICustomerRepository instance gets injected. All of this happens before the page lifecycle begins, so its safe to use these dependencies on page init or page load.

If more explicit control is required, we can change the module's behavior by changing the class level UsesInjection attribute.

[UsesInjection(For.ExplicitProperties)]
public partial class CustomerDetail : Page
{
    private ICustomerRepository customerRepository;

    [RequiredDependency]
    public ICustomerRepository CustomerRepository
    {
        get { return customerRepository; }
        set { customerRepository = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        customerGrid.DataSource = CustomerRepository.GetAll();
        customerGrid.DataBind();
    }
}

The For.ExplicitProperties does two things:

  1. Optimizes the scanning process to only consider explicitly tagged properties (the default behavior considers all public settable properties).
  2. An exception will be thrown if a dependency couldn't be found in the container to inject. This makes is pretty evident if you forget to register a dependency with the container.

With the page level code in place we then need to setup our container and register our components. This is easily accomplished by implementing Castle.Windsor.IContainerAccessor in our global.asax and creating a static container with the registered components our web application needs to run.  Here we register to use an in memory customer repository implementation.

public class Global : System.Web.HttpApplication, IContainerAccessor
{
    private readonly IWindsorContainer container = new WindsorContainer();

    public Global()
    {
        container.Register(
            Component.For<ICustomerRepository>()
                .ImplementedBy<InMemoryCustomerRepository>());
    }

    public IWindsorContainer Container
    {
        get { return container; }
    }
}

We do this in the global.asax because we share the container between all requests, and thus only want one instance of it. Also, the IContainerAcessor is used as a service locator which is required by the AspNetWindsor http module to find your container instance which it will use to resolve dependencies.

The very last thing we need to do is register the AspNetWindsor http module in our web.config, just like any other module.

<add name="WindsorModule" type="Sneal.AspNetWindsorIntegration.AspNetDependencyBuilderModule, Sneal.AspNetWindsorIntegration"/>

From here on out, all ASP.NET requests get intercepted by this module and "enriched" by the container as long as they are tagged with the UsesInjection page level attribute.

The code is available under the Apache 2 license in my SVN repository here on Google Code.  A compiled binary is also available for download.

.NET | IoC
Tuesday, December 09, 2008 7:26:26 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, October 31, 2008

I had a situation where I needed to temporarily modify some read-only files on disk that were under source control (TFS).  Basically what I wanted to do was:

  1. If the file is read-only, make it writable.
  2. Modify the file.
  3. Set it back to read-only if it was originally read-only.

You could just put an if then for steps 1 and 3, but that's ugly IMO.  Here's what the originally looked like before I refactored it:

bool isReadOnly = IsFileReadonly(webConfigPath);
FileAttributes originalFileAttributes = File.GetAttributes(webConfigPath);

if (isReadOnly)
{
	File.SetAttributes(file, FileAttributes.Normal);
}

File.Copy(backupWebConfigPath, webConfigPath, true);

if (isReadOnly)
{
	File.SetAttributes(webConfigPath, originalFileAttributes);
}

So here's my refactored solution using a DisposableAction which wraps a delegate that is invoked on dispose.  Inside the using statement the file is ensured to be writable, but at the end of the using statement its original attributes are set back on the file.  All the if statements in the code above get replaced with the following concise using statement:

using (FileAsWritable(webConfigPath))
{
	File.Copy(backupWebConfigPath, webConfigPath, true);
}

I think that's much cleaner, what do you think?  The rest of the supporting code if you're interested:

private static DisposableAction FileAsWritable(string file)
{
	if (!IsFileReadOnly(file))
	{
		return new DisposableAction(/* no-op */);
	}

	FileAttributes originalFileAttributes = File.GetAttributes(file);
	File.SetAttributes(file, FileAttributes.Normal);
	return new DisposableAction(() => File.SetAttributes(file, originalFileAttributes));
}
namespace Sneal.JsUnitUtils.Utils
{
    /// <summary>
    /// Wraps a delegate all that is called on Dispose, used for wrapping
    /// an action from a method call.
    /// </summary>
    public class DisposableAction : IDisposable
    {
        private Action action;

        public DisposableAction() {}

        public DisposableAction(Action action)
        {
            this.action = action;
        }

        public void Dispose()
        {
            if (action != null)
            {
                action();
            }
        }
    }

    public delegate void Action();
}
Friday, October 31, 2008 5:39:47 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, April 07, 2008

It seems like we've all done this a hundred times before.  I know I have.  What I really want is a strongly typed argument object passed in from the command line, but all we get is a bunch of strings to parse through.  Yuck, I hate parsing strings.

There are a few existing command line parsing libraries in .NET.  I thought about using one of them, but I either ran into licensing issues, old .NET 1.1 code, or the library was just too big and over complicated for what I wanted.

Needing this functionality yet again, I decided to create a re-usable library that allows me to create my command line arguments via property attributes.  To create a new argument class I just apply a SwitchAttribute to each property I want settable from the command line.

    public class Options
    {
        private int port;
 
        [Switch("Port", "Sets the IP Address port of the server.")]
        public string Port
        {
            get { return port; }
            set { port = value; }
        }
    }

 

Then to use this options class from my console application, I only need to:

    private static int Main(string[] args)
    {
        CommandLineParser parser = new CommandLineParser(args);
        Options options = parser.BuildOptions(new Options());
 
        if (options.Port != 0)
        {
            // ...
        }
    }

 

As you can see, this is nothing fancy, but it makes building new console apps a little easier, and more importantly it makes adding or changing command line arguments much more maintainable since I only need to modify a single property forgoing any string parsing.  I can also get a nicely formatted list of what command line arguments are available along with their descriptions.

    foreach (string line in CommandLineParser.GetUsageLines(new Options()))
        System.Console.WriteLine(line);

 

Outputs:

/Port    Sets the IP sddress port of the server.
/Server   Sets the name of IP address of the server.
...

 

If you interested in using the library, its available in my Google code SVN repository under the Apache 2.0 license.

Monday, April 07, 2008 6:11:50 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, March 20, 2008

You might immediately suspect a C# class is breaking the single responsibility principle when you discover upon opening it that the entire first page is nothing but using statements.  38 in all, and that's after using Re# to remove the unused ones.

Can you guess what kind of class this is?

If you guessed a code behind to a winform dialog then you guessed right.

.NET | WTF
Thursday, March 20, 2008 10:27:40 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, March 10, 2008

I realized that in almost every project I work on I end up defining a small preconditions assertion library.  I got tired of doing that, so I created a very small argument preconditions library.  That's all this library does - preconditions, that way I can add this to any project without any other baggage to go along with it.

I wanted the precondition library to be readable and short.  This is what I came up with:

Throw.If(regexExpression).IsEmpty();
Throw.If(instance).IsNull();

 

I think it intention revealing and short to write (especially with intellisense) than traditional precondition checks.  Another nice thing is that is type safe/smart, so only string arguments get string related precondition checks - like IsEmpty().

I checked it into my SVN repository on Google code.

Monday, March 10, 2008 4:02:31 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, February 19, 2008

I'm just finishing up building my first deployed WCF service, and over the past couple of months I've learned a lot about WCF - what works and what doesn't from a practical standpoint.  Unfortunately there are still a few areas in which I'm fuzzy.

I was originally treating my WCF proxies like ASP.NET 2.0 web service proxies.  Create a proxy and then let the GC handle it.  This was really useful because I was just injecting the service instance into each of my MonoRail controllers using Windsor.  Testing was nice and easy, and things looked good.

Until last week... I discovered a nasty bug in my web application.  The bug was, that under load, the WCF service would stop responding and timeout.  Come to find out that it's not only recommended to close your client side proxies, but required (at least when using Net TCP binding).

This turned my beautiful code with its inverted dependencies into a mess.  I had to start asking the container on every call for a new proxy since it was getting closed after every remote call.

IMyService svc = IoC.Resolve<IMyService>();
svc.SomeRemoteCall();
svc.close();

 

I had to do it this way because the remote calls were wrapped in a local service helper object that didn't have any idea about the unit of work, i.e. where the best place to put the Close() call.

 

When I have some time this week I plan on building a WCF proxy helper that will create a proxy unit of work on a per HTTP request basis.  When the HTTP request comes in, the proxy is created, and when the HTTP request finishes the helper will call Close() on the proxy.  This should allow me to remove the ugly static IoC dependency and use Windsor to inject the proxy instance.

Tuesday, February 19, 2008 6:59:24 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, January 23, 2008

Over the past few months on the RhinoMocks group I have seen several good ideas for enhancements to the library.  One of the ideas was to add a DoNotExpect.Call helper, which would do the same thing as the LastCall.Repeat.Never() syntax, just in a much more concise way.

This past weekend I added the DoNotExpect.Call() syntax to RhinoMocks, and Ayende has already applied the patch to the RhinoMocks trunk.  Here's how you use the new syntax:

IService svc = mocks.DynamicMock<IService>();

DoNotExpect.Call(svc.Load("Sneal"));

DoNotExpect.Call(delegate { svc.Save("Sneal"); });

 

There are two overloads for the method, one takes an object, and the other a delegate.  For methods that return a value you can use the simpler one without the delegate, however for void methods you need to use the delegate syntax (since something has to be passed in, even if it is technically ignored).

I'm excited about the syntax since I know I will use it quite often on my controller tests that use a lot of dynamically mocked objects.  The syntax I think is also easier to understand, especially for RhinoMocks newbies who have used NMock2 before.

Hopefully I'll have time to add some other enhancements to RhinoMocks in the near future.  It feels good to give back to the software ecosystem every once in a while.

Wednesday, January 23, 2008 6:16:24 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Saturday, January 12, 2008

I like to re-use code between projects, whether for personal use or professionally, so I created an Apache 2.0 licensed code repository.  Right now I just have my application configuration build tools committed (which I'll post about later).

The project home page is: http://code.google.com/p/sneal/

The project SVN URL is: http://sneal.googlecode.com/svn/trunk/

Saturday, January 12, 2008 8:01:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, January 09, 2008

We've all written a few console apps in our time, but how often do we spend anytime creating a help command line switch that spits out how to use the app?  Hopefully you answered, "everytime."  There's nothing more annoying than a console app that doesn't display a man page if you forget to supply required parameters.

It's so easy to add syntax help, especially if you drop the Console.WriteLines in favor of an embedded text file resource.  This way you can edit your command line usage as plain text which is so much easier to write and maintain.  This may seem obvious, but often time we forget because, "it's just a quickie console app."  So the next time your find yourself writing a console utility, remember to use an embedded text resource as your help (or man) page.

EmbeddedResource

Other than actually creating the text file and marking it as an embedded resource, this all the code required (don't forget to prefix your text file with the default assembly namespace):

private static void Usage()
{
    using (
        Stream s =
            Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "Sneal.Build.ConfigPoke.Console.usage.txt"))
    {
        using (StreamReader reader = new StreamReader(s))
        {
            System.Console.WriteLine(reader.ReadToEnd());
        }
    }
}
Wednesday, January 09, 2008 6:51:36 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, November 11, 2007

Here's a good reason not to use untyped datasets.  I was tasked with hiding a radio button on a webform depending on the SkuType of the product.  Unfortunately I have no idea if the web application, let alone the web service it uses for data access, returns the SkuType already.  The web service just returns a bunch of untyped datasets as raw strings.  To actually figure out what each web service call is returning I have to look at each sproc's SELECT statement.

If I had some hint in the code of what the expectations of the form of data, I could at least grep for SkuType.  As it is now I may be adding it to an existing sproc, thus unknowingly duplicating logic.  I guess my only alternative is to export out all sprocs to a script and then grep the script for SkuType.

Sunday, November 11, 2007 10:17:25 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, November 01, 2007

In my previous post I assumed that I would need to explicitly load my child objects through my service and provide a finer grained service interface to support that model.  After digging through Udi Dahan's blog posts again I found a very relevant post about using a fetching strategy to specify how deep you want the object model to be for any specific request.  By being able to specify a fetching strategy in the consumer code I can return the proper size object graph without making my service interface chatty.

This does leak some of the service logic into the client code, but really I'm OK with that.  The alternative is to explicitly call each service method which I think is harder to maintain and makes the object model pretty difficult to use. 

After using Mule ESB at my last job I've found it kind of hard to go to plain old web services.  I really like the messaging paradigm and separation of concerns an ESB provides.  Now if I could just find the SVN repository for NServiceBus.

Thursday, November 01, 2007 5:43:20 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 18, 2007

It seems I keep running into situations where I want to mock or stub a class that is responsible for saving something out to disk.  The problem is that using a StreamWriter (or similar) is the lifetime of the writer object is shorter than the containing class, which makes it impossible to mock effectively.

Often the way around this is to implement an interface with three method calls: Open, Write, Close - so you can reuse the writer instance for multiple files thus changing the lifetime of the writer to the same as the containing class thus allowing you to mock the writer.

I've never liked this solution, it always has felt like a workaround for testability.  Instead, how about splitting the two parameters (contents and file path) into separate fluent method calls and having the Write auto-close the file like this example:

keyWriter.Write(exportKeys).To(destinationFolder);

 

...

 

public interface IExportKeyWriter

{

    IExportKeyWriter Write(ImageExportKeys keys);

    void To(string destinationFolder);

}

 

I like it because its very readable and more importantly its mockable.  I can inject a single instance of the IExportKeyWriter into my class under test.  When Write is called, the object is queued for writing to disk, and when To is called the destination file is opened, written to (using the queued object), and finally closed.

The only Problem I can think of is that it may not be obvious that you need to call the To method to have the file actually written out.

I'm hoping for some feedback on this, so I ask dear reader, what do you think?

Thursday, October 18, 2007 1:29:09 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, October 16, 2007

The following code snippet causes a stack overflow exception.  Can you spot it?  I almost didn't catch the case difference.  See it now?  I'm surprised the compiler didn't complain - at all, however ReSharper found the recursive call and squiggled it.  Yet another reason to get Re#.

 

public string CreatedDate

{

    get { return createdDate; }

    set { CreatedData = value; }

}

Tuesday, October 16, 2007 7:33:42 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, October 14, 2007

I needed the ability to kill a process and any of its child processes, but System.Process.Kill() does not kill any child processes. 

I tried using the JobObjectWrapper library, but unfortunately it doesn't work when running from an existing job, which is exactly the scenario I needed since Visual Studio 2005 on Windows Vista is already running under a job.

The solution I opted for was to use the WindowsXP Pro/Windows Vista taskkill.exe utility since it supports kill a task tree.

/// <summary>

/// Will kill a process and all its child processes.  This class requires

/// taskkill.exe present in the WINDIR\System32 directory.

/// </summary>

public class TaskKill

{

    private readonly int pid;

    private readonly string imageName;

 

    public TaskKill(string imageName)

    {

        this.imageName = imageName;

    }

 

    public TaskKill(int pid)

    {

        this.pid = pid;

    }

 

    /// <summary>

    /// Kills the process associated with this TaskKill instance.

    /// </summary>

    public void KillAssociatedProcess()

    {

        if (!string.IsNullOrEmpty(imageName))

            KillProcessByName();

        else

            KillProcessById();

    }

 

    protected void KillProcessById()

    {

        string killArgs = string.Format("/F /PID {0} /T", pid);

        ExecuteKill(killArgs);

    }

 

    protected void KillProcessByName()

    {

        string killArgs = string.Format("/F /IM {0} /T", imageName);

        ExecuteKill(killArgs);

    }

 

    protected string GetTaskKillExePath()

    {

        string taskKillPath = Path.Combine(Environment.SystemDirectory, "taskkill.exe");

        if (!File.Exists(taskKillPath))

            throw new FileNotFoundException(

                "Cannot find taskkill.exe in the Windows Sytem32 directory.  Are you running WindowsXP Home which doesn't include this utility?");

 

        return taskKillPath;

    }

 

    private void ExecuteKill(string processShellArgs)

    {

        ProcessStartInfo info = new ProcessStartInfo(GetTaskKillExePath(), processShellArgs);

        info.CreateNoWindow = true;

 

        Process process = new Process();

        process.StartInfo = info;

        process.Start();

        process.WaitForExit(5000);

    }

}

 

The code that uses the TaskKill class looks like this:

[Test]

public void Test1()

{

    ProcessStartInfo info = new ProcessStartInfo("notepad.exe");

    Process process = new Process();

    process.StartInfo = info;

    process.Start();

 

    Assert.That(!process.HasExited, "Process exited early");

 

    TaskKill taskKill = new TaskKill(process.Id);

    taskKill.KillAssociatedProcess();

 

    Assert.That(process.HasExited, "TaskKill failed to kill the process");

}

Sunday, October 14, 2007 6:07:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, July 29, 2007

By now most of us have figured out how to create sophisticated build scripts using NAnt, NAnt is the de-facto standard among .NET OSS projects and for good reason.  NAnt is the best build system on the .NET platform.  So with that out of the way, why would I be writing a series on MSBuild? 

Here's the biggest problem with NAnt as I see it, NAnt doesn't work in the de-facto .NET IDE, Visual Studio.  In Java, Ant build scripts work right there in your IDE.  As good as NAnt is, there's still the context switch cost of switching between Visual Studio and the command prompt.  Aw but I have hot keys you say.  OK, but some newbie dev on your team certainly doesn't, and in general most .NET developers are most comfortable within the realms of Visual Studio rather than the command line.  Like it or not, most .NET developers don't want to build through a command line before they can build through Visual Studio.

The other advantage MSBuild has is that csproj files work natively in the build engine.  If the C# project works in Visual Studio, then you know it will work on the command line with MSBuild.  There's no need to maintain two separate build scripts or any other silliness.  I have also found MSBuild to be really good at resolving dependant nested builds.  So without further ado, here's the rundown of posts I hope to hit in this series:

  1. The basics, project structure.
  2. Configuration file management.
  3. Building the database.
  4. Unit testing.
  5. Code documentation with Doxygen.
  6. Preparing your build artifacts for deployment.
  7. Integrating with CruiseControl.NET.
Sunday, July 29, 2007 5:56:21 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, July 27, 2007
It seems like most of the libraries I use in .NET output log statements via log4net, which is great.  The one thing that often occurs though is information overload, especially when I set my root logger to DEBUG.  Since I follow the logger per class convention, and I name all my loggers based off of type its super easy to allow DEBUG messages for my code, while turning other packages to INFO.

    <root>
      <level value="INFO" />
      <appender-ref ref="ConsoleAppender" />
    </root>
    <logger name="GalleryPlayer">
      <level value="DEBUG"/>
      <appender-ref ref="ConsoleAppender" />
    </logger>

The above lets NHibernate (or whatever else) log at the INFO level, while my code under the GalleryPlayer namespace logs at the DEBUG level.

Friday, July 27, 2007 5:29:09 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, July 26, 2007
This is a note to myself to take a look at Coco-R.

Coco is a compiler compiler (I guess that's where coco comes from). You have probably heard of tools like lex and YACC - Coco-R is a modern version of these tools. What's really great about it is that there are ports to several languages including C#. This is very convenient because additional processing you may want to do during parsing can be written in the same language tool itself is written in - C#.

Thursday, July 26, 2007 5:17:12 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, July 01, 2007
I needed to remove about 60 subdirectories named "_thumbs" from my pictures directory.  Of course manually doing this through Explorer wasn't something I was up for.  I tried to do it through the command line, but RD doesn't support multiple directories as inputs.  I wanted to do this:

dir /AD /B /S *_thumbs* | rd /s

but that didn't work, so I had to write my own RD command that is capable of piping input through it - which was still faster than doing it through Explorer.

dir /AD /B /S *_thumbs* | consoleapplication1

using System;
using System.IO;
using log4net;

namespace ConsoleApplication1
{
    class Program
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {
            string input;
            do
            {
                input = Console.ReadLine();

                if (input != null)
                    DeleteDir(input);

            } while (input != null);
        }

        private static void DeleteDir(string input)
        {
            if (Directory.Exists(input))
            {
                Logger.InfoFormat("Deleting directory {0}", input);
                Directory.Delete(input, true);
            }
            else
                Logger.WarnFormat("Directory {0} does not exist", input);
        }
    }
}


Sunday, July 01, 2007 4:06:27 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [2]  | 
# Wednesday, June 13, 2007
Here's a really interesting way to conduct unit tests using in memory collections with LINQ: http://iancooper.spaces.live.com/blog/cns%21844BD2811F9ABE9C%21397.entry

I'll need this in the future me thinks...

Wednesday, June 13, 2007 5:08:28 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, June 05, 2007
I was so used to using the Java Seralizable interface for arguments, that I kind of miss it in a way in .NET.  In fact I missed being able to easily tell if an object was serializable, but someone pointed this out to me today:

[Serializable]
public class User
{
...
}


if (typeof(new User()).IsSerializable)
   Console.WriteLine("The User type is serializable");



Tuesday, June 05, 2007 6:08:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, May 18, 2007
I moved my little demo application (aka FoodBankTracker) that I use for demoing tech over to Visual Studio 2007 / .NET 3.5 today without much hassle.  The only real hassle I had was with log4net version/strong key mismatches between MonoRail RC2 and NHibernate 1.2 GA, but that's entirely another story.  The main reason I wanted to move it over to the new platform was to really try out the new language integrated queries (LINQ).  I ended up using the LINQ -> NHibernate criteria adapter being maintained by Ayende for several reasons:
  1. My NHibernate mapping files are complete.
  2. I like the unit of work NHibernate provides.
  3. Its always good to have some abstraction between the domain and the database layer.
  4. I'm familiar with NHibernate and already have infrastructure in place for it.
I grabbed the latest code from subversion for the LINQ -> NHibernate adapter and was up and running in no time.  The only change I had to make was to upgrade the NHibernate version from 1.2 beta3 to 1.2GA.  The hardest part was figuring out that I needed to add an assembly reference to System.Core for .NET 3.5 in my project.  Anyway, here's the one test I have working with LINQ and for comparison I'm also showing the original test without LINQ which does the same thing.

Friday, May 18, 2007 6:56:17 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, May 17, 2007
My little demo/test application that I monkey around with from time to time got a major revamp today.  Nothing fun or exciting, just a lot of infrastructure cleanup that I've been needing to do for some time.  I was hoping this would only take me an hour, but in reality it took me 3 times longer than that.  All I needed to do was:
  1. Upgrade NHibernate from 1.2 beta3 to NHibernate 1.2 GA.
  2. Separate out my shared core library into a separate folder/solution structure.
  3. Stop using GAC'd Castle and NUnit assemblies and use a local libs folder to facilitate building on a clean box.
Nothing fancy, but I ran into some serious issues with log4net.  You would think that because most open source projects use log4net, integration of multiple open source products that use log4net would be a breeze right?  Well, Castle RC2 uses log4net 1.2.9.0 while the latest NHibernate release uses log4net 1.2.10.0.  That seems fine, just add an assembly binding redirect to have castle using the newer log4net version right?  Well that's fine until you realize that the log4net team unexplicablly changed their signed key between those releases, which means you can't use a binding redirect.  Oops, I doubt the log4net team intended that to happen.

To get around this version mismatch I ended having to grab the latest code from the Castle subversion repository which included log4net 1.2.10.0 and build my own assemblies that would play nicely with  NHibernate.

The moral of this story is don't change your keys between versions if they're binary compatiable/incremental updates.  Especially for something so commonly shared as log4net.

.NET | WTF
Thursday, May 17, 2007 10:22:46 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, May 15, 2007
Anyone who's programmed in VB for a while will find this article interesting: http://www.codinghorror.com/blog/archives/000860.html

I didn't realize (or maybe truly understand) VB.NET had a background compiler in Visual Studio 2005 like Eclipse does for Java.  When I was programming in Java/Eclipse the background compiler literally saved me 20 minutes or more a day, its hard to believe C# doesn't have this even in Visual Studio "Orcas". 

The one thing I really from miss from VB is the with statement.  The with statement is very fluent and readable. In C# we could have something like the using statement:

Person user = new Person();
with (user)
{
   .FirstName = "John",
   .LastName = "Doe",
   .Age = 18,
   .PhoneNumber = 5555555,
}

The one thing we will have in .NET 3.5 is property initializers which are pretty close to the with statement, but the one difference is that the with statement would work anywhere.  Property initializers only work on construction of the object and really only save you from having to declare a bunch of overridden constructors.  Property initializers look like this:

Person user = new Person()
{
   FirstName = "John",
   LastName = "Doe",
   Age = 18,
   PhoneNumber = 5555555
}

Now what happens if I need to reuse an instance and assign different values?  Well, hopefully you won't need to, and in likely hood its very unlikely you would.  When I was programming in VB I generally only used the with statement to initialize an object.  What do you think?

Tuesday, May 15, 2007 5:11:50 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, April 26, 2007
I converted my main .NET solution I'm working on from Visual Studio 2005 to Visual Studio Orcas without any problems.  I did the conversion so that I could play around with LINQ, and more specifically the LINQ to NHibernate adapter, and as such I chose to run everything under .NET 3.5.

I thought for sure I would get at least one conversion error or compiler error, but no.  My solution even included NHibernate and Iesi.Collections.  Better yet and possibly even more suprising is that I can still run and debug the web project which is using MonoRail RC2.


Thursday, April 26, 2007 3:57:26 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, April 24, 2007
I was going to use the NHibernate facility provided by Castle Windsor until I found out it didn't support using class mapping attributes.  I ended up rolling my own implementation but added a couple new features to my implementation:

  • Automatic context aware session container (web context or thread local).
  • Ability to use NHibernate mapping attributes instead of hbm.xml files.
  • Can use the built-in .NET 2.0 connectionStrings element to specify an NHibernate connection string.
I think the first two items are pretty obvious, but the last feature I added because most standard .NET applications make use of these elements - for better or worse.  I think its a good idea to be consistent if possible.  Additionally this would allow any standard .NET administration tool to examine and edit the connection string for the application.

I also wanted the ability to use a custom configuration section so that I could add additional elements and attributes as needed.  The configuration section handler produces a SessionFactoryConfiguration instance, which itself it a subclass of NHibernate.Cfg.Configuration.  The configuration section looks like this:

  <sessionManager>
    <settings>
      <setting name="hibernate.dialect">NHibernate.Dialect.MsSql2000Dialect</setting>
      <setting name="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</setting>
      <setting name="dotnet.connection_string">Laptop</setting>
      <setting name="hibernate.connection.provider">
         NHibernate.Connection.DriverConnectionProvider
      </setting>
    </settings>
    <resources>
      <resource assembly="Sneal.Northwind.Core" useAttributes="true"/>
    </resources>
  </sessionManager>

Notice the setting dotnet.connection_string.  This is the custom hook I added to my custom configuration handler that resolves Laptop to the .NET connection string named Laptop:

  <connectionStrings>
    <add name="Laptop" connectionString="Database=Northwind; Data Source=.\sqldev2000;" />
  </connectionStrings>

Then I just wire up my SessionManager instance to my Repository instance using an IoC container; currently Windsor.  I have an HttpModule which handles my Unit of Work currently, but unfortunately its tied to Windsor and my current application, so now I'm off to decouple it for reuse.
 

Tuesday, April 24, 2007 5:26:12 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, April 22, 2007
Adding to my previous post, I thought I would also add an example that uses the new LINQ query expression syntax.  The example is pretty much the same as the last, except that I added one additional person to the list and added an aggregate.

public static void DotNet35WithQueryExpresion()
{
    IList<Person> people = new List<Person>()
    {
        new Person() { Age = 28, FirstName = "Shawn", LastName = "Neal" },
        new Person() { Age = 16, FirstName = "Isabella", LastName = "Neal" },
        new Person() { Age = 15, FirstName = "Joe", LastName = "Velope" },
        new Person() { Age = 43, FirstName = "John", LastName = "Smoe" }
    };

    IEnumerable<Person> teens = from p in people where p.Age < 20 && p.Age > 12 select p;
    Console.WriteLine("The following people are teenagers:");
    teens.WriteAll();

    int sumOfAges = teens.Sum(p => p.Age);
    Console.WriteLine("Sum of all ages: {0}", sumOfAges);
}

Looks like I just wrote some statically checked SQL straight into my c# doesn't it?  Seeing how Ayende has declared that queries are a business concern (and I agree) and we now have LINQ, we can finally place our queries where they belong, in our domain/service layer or even our presentation layer.  You could put your queries there before, but the legions of Microsoft followers would cry out, "This is not the MS way!"  It should be much easier to convince the Microsoft drones that still insist on putting business logic in the database, i.e. stored procedures, that queries in fact belong in the application under unit test.  Yes, queries should be unit tested just like the rest of your application!  Remember that queries are business logic.

I'm still not sure if there is a LINQ query expression that I can apply in this scenario that would replace the lambda expression in the Sum function.  Any idea?

Saturday, April 21, 2007 11:20:16 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, April 21, 2007
I finally downloaded and installed Visual Studio "Orcas" beta 1 so that I could start playing around with the new functionality built-in to .NET 3.5.  I wanted to build a sample that compared an implementation between .NET 1.1, .NET 2.0, and .NET 3.5, here's the contrived example that I came up with based on a series of postings by Scott Guthrie.

Each example is making use of a simple POCO, note that in .NET 3.5 the private variables and public properties could be replaced by automatic properties.

public class Person
{
    private string firstName;
    private string lastName;
    private int age;

    public Person() { }

    public Person(string firstName, string lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public override string ToString()
    {
        return String.Format("{0} {1} - {2}", FirstName, LastName, Age);
    }

    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}


The .NET 1.1 implementation is pretty terse, and requires the most work on the part of the developer.  Although I think it reads horribly, pretty much any developer (even Mort) can understand exactly what the code is doing.

public static void DotNet1()
{
    ArrayList people = new ArrayList();
    people.Add(new Person("Shawn", "Neal", 28));
    people.Add(new Person("Isabella", "Neal", 16));
    people.Add(new Person("John", "Smoe", 43));

    ArrayList teens = new ArrayList();
    foreach (Person person in people)
    {
        if (person.Age < 20 && person.Age > 12)
            teens.Add(person);
    }

    Console.WriteLine("The following people are teenagers:");
    foreach (Person o in teens)
        Console.WriteLine(o.ToString());
}

In .NET 2.0 things become easier for the developer with anonymous delegates and the new generic List implementation.  The only problem is that the syntax doesn't flow well and Mort might not get it, but at least the nasty foreach statement is gone.

public static void DotNet2()
{
    List<Person> people = new List<Person>();
    people.Add(new Person("Shawn", "Neal", 28));
    people.Add(new Person("Isabella", "Neal", 16));
    people.Add(new Person("John", "Smoe", 43));

    List<Person> teens = people.FindAll(delegate(Person p) { return p.Age < 20 && p.Age > 12; });
    Console.WriteLine("The following people are teenagers:");
    foreach (Person o in teens)
        Console.WriteLine(o.ToString());
}

Things in .NET 3.5 become a whole lot cleaner and elegant.  The people.Add() statements are replaced by much cleaner object initializers.  I also used the object initializer syntax for each person instance, even though I provided an overloaded ctor; in .NET 3.5 I could actually forgoe the overloaded ctor.  The most interesting part is that the List.FindAll has been replaced by a LINQ Where extension method with a lambda expression argument - compare that to the .NET 1.1 implemetation!  The final bit is that I added my own WriteAll() extension method just for fun.

public static void DotNet35()
{
    IList<Person> people = new List<Person>()
    {
        new Person() { Age = 28, FirstName = "Shawn", LastName = "Neal" },
        new Person() { Age = 16, FirstName = "Isabella", LastName = "Neal" },
        new Person() { Age = 43, FirstName = "John", LastName = "Smoe" }
    };

    IEnumerable<Person> teens = people.Where<Person>(p => p.Age < 20 && p.Age > 12);
    Console.WriteLine("The following people are teenagers:");
    teens.WriteAll();
}

public static class MyExtension
{
    public static void WriteAll(this IEnumerable enumerable)
    {
        foreach (object o in enumerable)
            Console.WriteLine(o.ToString());
    }
}

I'm now thinking of using .NET 3.5 on my current pet project - LINQ and extension methods are absolutely fantastic!


Saturday, April 21, 2007 4:40:08 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, April 18, 2007
I came across a cross cutting infrastructure requirement today that would have been best solved by using AOP.  Since the application I was using already uses Spring.NET I immediately thought about implementing a method interceptor using Spring.NET's AOP facilities, I even found an interceptor already coded on the web that was exactly what I needed.  Of course there was one problem, .NET defaults all public methods to non-virtual and the class I was trying to apply AOP to was a wsdl.exe generated class with non-virtual methods.  This meant that Spring couldn't generate an AOP proxy at runtime for the method I wanted to add a pointcut to.  Argh!

I think defaulting every public member in .NET to virtual would have been a better decision than defaulting to non-virtual.  Java doesn't have a virtual keyword, every public method in Java is virtual by default.  Isn't that the whole point of OOP and inheritence?  At a whim, I should be able to subclass and override ANY public method.  Yeah, I may implement things incorrectly in my subclass, but the onus is on me.  Not marking methods virtual in .NET is basically saying you don't trust the next developer.  This is especially annoying since dynamic subclassing has become so common ala DynamicProxy.  Want to use NHibernate with lazy loading?  Well you can't unless you mark everything explitly virtual.  All this means to me is extra cutting and pasting; of course I'm going to make everything virtual.  My point is that virtual should be the default, it should be extra work to make it non-virtual - just like sealing a class.

Some of you may say, but virtual methods are slower than non virtual methods because of the method lookup.  True, virtual methods are slower, but...  And this is a big one, all method calls in c# are virtual method calls, regardless if they are marked virtual or not.  If I'm already paying the price of having virtual methods, then why can't we just treat them as such in code?!

Wednesday, April 18, 2007 10:49:28 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, April 15, 2007
I just wrote my first Mono c# program, talk about easy.  The hardest part was figuring out how to invoke the mono c# compiler, and no its not csc, but mcs.  Mono can be installed from the Ubuntu "Add Applications" applet, but its actually easier and more direct to install it from the shell:

sudo bash
apt-get install mono mono-gmcs


Once Mono is installed you may want to install a text editor or MonoDevelop.  I just installed a text editor, called Cream, which actually picked up the syntax highlighting which surprised me.  Anyway I preceded to put together helloworld.cs in my home directory:

using System;

namespace SNeal
{
    public class HelloWorld
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World, from Ubuntu!");
        }
    }
}

Then from the shell again:

mcs helloworld.cs

Which produced helloworld.exe which can then be run (very similar to Java in this respect) by typing:

mono helloworld.exe


That's all there is to it!  Further things I plan to try out on Ubuntu with Mono: Generics, ASP.NET, NUnit, MonoDevelop, and Eclipse (which is my favorite IDE).

Sunday, April 15, 2007 6:41:21 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, March 19, 2007
For no real good reason I decided to implement another reusable IComparer, this time using .NET 2.0 and generics.  My focus this time was on:
  • Better API using generics.
  • SQL compliant ordering clause.
  • Multi-property sort ordering.

GenericComparer<Address> comparer = new GenericComparer<Address>()
   .OrderBy("FirstName, LastName DESC");

As you might guess this IComparer will sort a collection of Address objects by FirstName and then by LastName descending.  The code could still use some cleaning up and I plan on replacing all of the reflection calls using lightweight code generation, but nonetheless it does pass my current set of tests.

public class GenericComparer<T> : IComparer<T>
{
    Type declaringClassType = typeof(T);
    IList<PropertyOrderBy> properties = new List<PropertyOrderBy>();

    /// <summary>
    /// Default ctor instantiates a new GenericComparer instance.
    /// </summary>
    public GenericComparer() { }

    public GenericComparer<T> OrderBy(string sqlOrderBy)
    {
        string[] parts = sqlOrderBy.Split(',');
        foreach (string part in parts)
        {
            string[] orderbyParts = part.Trim().Split(' ');
            string fieldName = orderbyParts[0].Trim();
            string direction = string.Empty;

            if (orderbyParts.Length > 1)
                direction = orderbyParts[1].Trim();

            properties.Add(new PropertyOrderBy(fieldName, direction));
        }

        return this;
    }

    private IComparable GetPropertyValue(object instance, string propertyName)
    {
        // This won't work if the property is overloaded by type
        PropertyInfo info = declaringClassType.GetProperty(propertyName);
        object val = info.GetValue(instance, null);

        IComparable retVal = val as IComparable;
        if (retVal == null)
        {
            throw new ApplicationException(
             propertyName +
             " Type must implement IComparable to be able to use a PropertyComparer.");
        }

        return retVal;
    }

    #region IComparer<T> Members

    public int Compare(T lhsObj, T rhsObj)
    {
        int result = 0;

        foreach (PropertyOrderBy orderBy in properties)
        {
            IComparable lhs = GetPropertyValue(lhsObj, orderBy.PropertyName);
            IComparable rhs = GetPropertyValue(rhsObj, orderBy.PropertyName);

            if (orderBy.SortDirection == "DESC")
                result = rhs.CompareTo(lhs);
            else
                result = lhs.CompareTo(rhs);

            if (result != 0)
                return result;
        }

        return result;
    }

    #endregion    

    private class PropertyOrderBy
    {
        public string PropertyName;
        public string SortDirection = "ASC";

        public PropertyOrderBy(string propertyName, string direction)
        {
            direction = direction.ToUpper();
            if (direction != "ASC" && direction != "DESC" && direction != string.Empty)
                throw new ArgumentOutOfRangeException("direction", "Unknown order by direction: " + direction + ", expected either ASC or DESC.");

            if (direction != string.Empty)
                this.SortDirection = direction;

            this.PropertyName = propertyName;
        }
    }
}

Monday, March 19, 2007 6:37:10 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, March 14, 2007

Now that I’m finally back in ASP.NET user land, I can finally scratch an itch of mine to use WatiN on a real project.  I’m thoroughly impressed with the product, even though the documentation is fairly light; the thing is the API is so straight forward you don’t need a bunch of documentation which allows you to ramp up and use it very quickly.  How nice is that?

The one problem I had was that Session state and general page state was being shared between each of my tests initially which would cause some tests to break because they expected the page to be in one state, but another test had changed the state to something else.  I had originally scoped my IE instance at the fixture level, which caused some tests to break because of the order they were being run by NUnit.  I ended up having to change my IE scope from fixture level, to test level which was quite a bit slower.  Here’s one of my tests:

[Test]
public void SearchResultsAreDisplayedOnSearchClick()
{
   using (IE ie = CreateIE())
   {
      ie.Link(Find.ById(new Regex(@"m_btnSearch\b"))).Click();
      string borrowerName = GetResultTable(ie).TableRows[1].TableCells[1].Text;

      Assert.AreEqual("George Washington", borrowerName,
          "Search results did not display as expected.");
   }
}

private Table GetResultTable(IE ie)
{
   return ie.Table(Find.ById(new Regex(@"m_resultsGrid\b")));
}

private IE CreateIE()
{
   IE ie = new IE(SearchUrl);
   ie.Refresh();
   return ie;
}

What I need to do is to make my tests less granular, less like a unit test and more like a functional integration test.  I would rather not do that, but I think for more complicated testing scenarios I will have to do this anyway.  I should stop trying to fight what should be natural here.  Basically I need to combine what are now several tests into a single test.  An end user would likely perform several actions on the page before moving on to anther page, and so should my WatiN tests.  After all, these aren’t unit tests – those of course are already all green.

Wednesday, March 14, 2007 6:21:41 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Tuesday, March 13, 2007
I ended up modifying my reusable IComparer class to work on any data type that implements IComparable since our data grid now has a decimal data type for one the columns.  I'm now betting that the users will want/need to be able to sort ascending and descending, not just ascending.  Also case insensitive comparisons will probably be required (although my original implementation did have this).

Perhaps its time I Googled a more mature implementation up, CodeProject must have one already.

Tuesday, March 13, 2007 6:58:13 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, March 10, 2007
I needed to implement sorting in one of our applications that contained a grid with multiple properties.  Normally in .NET 1.1 most people would throw the data into a DataSet and be on their way, but I already had a domain model with some nice POCOs, so I though why bother to load a dataset just to support sorting on a few elements?  I started to write a an IComparer but then I realized I would have to do it 6 more times for each property.  No thanks.

I decided to implement a super easy string property comparer that would get the property it needed to compare using reflection.

/// <summary>
/// Generic and reusable IComparer for string based properties.
/// </summary>
public class StringPropertyComparer : IComparer
{
    private string m_propertyName;
    private Type m_declaringClass;

    public StringPropertyComparer(Type declaringClass, string propertyName)
    {
        m_declaringClass = declaringClass;
        m_propertyName = propertyName;
    }

    private string getPropertyValue(object instance)
    {
        PropertyInfo info = m_declaringClass.GetProperty(m_propertyName, typeof(string));
        return (string) info.GetValue(instance, null);
    }

    public int Compare(object lhsObj, object rhsObj)
    {
        string lhs = getPropertyValue(lhsObj);
        string rhs = getPropertyValue(rhsObj);

        return ((new CaseInsensitiveComparer()).Compare(lhs, rhs));
    }
}

This could really be expanded to support multiple types besides strings, support asc and desc, and to support ordering by n+1 properties.  Perhaps some other day...  This works for now.


Saturday, March 10, 2007 12:27:41 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, March 07, 2007
How can you have an invalid enum?  Why would you want an invalid enum?  I know it seems almost contradictory to have an invalid enum, but I have run into the situation once or twice.  Usually its where there is a switch statement that does some particular action based off an enum and in that switch statement there is a default that throws an exception just in case another programmer would add a new enum value without updating the switch statement.  You may actually want to unit test and verify that an invalid enum would throw an exception.  Here's one way to achieve this, use an explicit cast:

enum DayOfWeek
{
    Monday,
    Tuesday
}

DayOfWeek badDayOfWeek = (DayOfWeek)(-1);

Trivial!  Yet its not something you may think of, because we've generally been trained to think that enums are ALWAYS supposed to be valid.

Better yet, get rid of your enums and your switch statements.

Wednesday, March 07, 2007 7:03:29 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, February 12, 2007
About a year ago, when .NET 2.0 first came out, I was toying with the idea of using the WWF for an internal ASP.NET application at work.  I finally decided against it last spring once it was decided .NET 3.0 would be required for WWF; .NET 3.0 wouldn't RTM for several months after the end of the project.  I haven't thought about WWF since then, that is until this weekend.  I've spent most of my free time this weekend immersed in WWF, and I must say that so far I'm really liking the technology much better.  I can finally see it being really useful in cases, especially in cases of long running workflow.

Originally I couldn't find much information on the WWF, I only had the Presenting Windows Workflow Foundation book, which I found not all that useful.  It was more of an overview rather than how to really implement anything - but it was better than nothing.  However I have found some articles recently posted by Scott Allen that are absolutely fantastic.

Monday, February 12, 2007 6:25:10 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, February 10, 2007
It's been several years since I've used Doxygen, but Ayende reminded me of its existance today.  I spent 2 minutes downloading it, setting it up, and then finally running it.  I forgot how fast Doxygen is, and the quality of the output is now very good on C#.  I will definately start using Doxygen again, its just so darned fast and simple.



Saturday, February 10, 2007 5:50:14 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, October 20, 2006
My ducked taped together photo site was causing me issues.  I finally fixed it...  I was getting a strange GDI+ exception, amongst others, when trying to use the site.  Apparently my NTFS permissions to the media folder got mucked up, so I ended up having to take ownership of all the files and then grant the NETWORK SERVICE account write permissions to the folder.

I think this happened before a long time ago.  I'm now thinking I don't like the thumbnails and xml files in each of the sub folders where the actual full size photos are stored.  It seems better to index these in a central location - heck maybe even use a database. 

Hmm...  Sounds like an excuse to play around with some new tech.

Friday, October 20, 2006 4:21:07 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, October 10, 2006

OK, you’ve finally built up your beautiful platform agnostic and persistent ignorant business domain layer.  It solves all of your business requirements and is elegant and maintainable – too bad the model doesn’t fit nicely into your user interface!

This is about the time a non-domain driven developer says, “ha, I told ya that domain model was a waste of time!  You should have modeled your objects after the user interface!”  Was it really a waste of time?  Of course not!  Well then how do we slap a UI on top of a domain model?  Chapter 11 of Jimmy Nilson’s Applying Domain-Driven Design and Patterns to the rescue.

Basically you have three options when hooking up a user interface to your domain model:

  1. The domain model hooks up directly to the UI, and it just happens to be a good fit.
  2. You wrap the domain model with a presentation specific object.
  3. You map data from the domain model to a presentation specific object.

Of interest here are options 2 and 3.  To keep the domain model clean and pure, it may make sense to create a presentation specific object that transforms a domain specific object into a user interface friendly one.  The example given in Jimmy’s book is the one where the domain model represents a name, first and last, as separate fields.  In the UI, the first and last names are placed together in a single textbox. 

Below I’ve provided an example of option #2, wrapping.  In this example ResourceWrapper in the presentation layer wraps a domain model Resource object.  One thing that makes the UI easier to work with is to flatten out object graphs like in this ResourceWrapper example, specifically the resource’s manager.

 

public class ResourceWrapper
{
    private Resource resource;

    public ResourceWrapper(Resource resource)
    {
        this.resource = resource;
    }

    public string Name
    {
        get { return resource.FirstName + " " + resource.LastName; }
        set
        {
            string[] names = value.Split(" ".ToCharArray(), 2);
            resource.FirstName = names[0];
            resource.LastName = names[1];
        }
    }

    public string ManagerName
    {
        get { return new ResourceWrapper(resource.Manager).Name; }
        set { new ResourceWrapper(resource.Manager).Name = value; }
    }

    public decimal Salary
    {
        get { return resource.Salary; }
        set { resource.Salary = value; }
    }

    public Resource GetDomainObject()
    {
        return resource;
    }
}

I have to write more code?  Yes, but you may be able to get around a lot of this by creating a generic object to object framework that sets properties via reflection and/or code generation.  In the end, wrapping or mapping domain objects sounds like a good idea when they just won’t fit nicely into the UI.

Tuesday, October 10, 2006 4:57:09 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, October 07, 2006
Ayende posted about some IL wierdness he experienced while working on DynamicProxy2, which prompted me to go do some reading about IL.
  • The CLR is completely stack based, no registers.
  • st commands store things from the stack to memory.
  • ld commands load items from memory onto the stack.
A decent overview of IL (from 2001?!) is: http://msdn.microsoft.com/msdnmag/issues/01/05/bugslayer/

Saturday, October 07, 2006 2:53:36 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  |