Monday, March 26, 2007

I've got a little project on at the moment which I chose to use ActiveRecord for... this is for a "legacy" database where there are existing nightly data warehousing scripts written against it... The cost of changing the database structure and tables is potentially quite high (it has run on effects to other systems, potentially effects SLA's when the nightly scripts fail.. and a small project ends up having a big impact)

At any rate, I'm just consuming the existing database as-is... which includes a single character status columns i.e. "A" for active, "P" for pending etc... after poking around with a few solutions I ended up creating an NHibernate custom type... first off, this was surprisingly easy... but it annoyed me a little that I had to create a different custom type for each set of enumerated values, and that this information was no longer declarative, compared to the rest of the ActiveRecord implementation...

So I took a few minutes to re-write it as generic solution to the problem today... which at least solves the declarative problem... first off, here's a property with the custom type applied - nothing amazing here, but notice the type is generic... with the type of status field itself qualifying the generic custom type...

 [Property("dBlrStatus", "App.Model.MappedEnumerationHibernateType`1[[App.Model.Status, App.Model]], App.Model")]

 public virtual Status Status

 {

    get { return _status; }

    set { _status = value; }

 }


We then declare the mappings on the enumeration itself...

 public enum Status

 {

    [MapToCharacters('A', 'a', '+')]

    Active,

 

    [MapToCharacters('I', 'i', '-')]

    [Default]

    InActive

 }


I think this is a good fit for ActiveRecord... If anyone wants the code at some point just leave a comment and I'll package it up and post it... it's pretty elementary stuff, though it might save some time if you wanted to re-implement it yourself...

posted @ Monday, March 26, 2007 5:35:27 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |
 Tuesday, March 20, 2007

Well as the more observant reader of Alex Jame's Blog might have noticed, I'm talking at the the Architect Camp 2007 this year... which should be...interesting - I haven't done any public speaking for a while now, but Alex James assures me I'll be fine ... be it on his head! ;o) ...

So I'm planning to talk about IoC (Inversion of Control) - one of my little pet loves... Some of the subjects I'm considering include:

  • Coupling
    • How do we couple (Message, data, content etc.)
    • Metrics for the architect (Instability vs. Abstractness etc.)
  • Dependency Injection
    • Constructor dependencies
    • Parameter dependencies
    • Law of Demeter
  • Inversion of Control
    • Why bother?
      • Added flexibility and opportunity
      • Lowering the cost of change
    • ServiceLocators
      • Why they suck
    • Inversion of control containers
      • What's available (Castle, Spring, StructureMap etc.)
      • Autowiring
      • Services
      • Lifestyle vs Lifecycle
      • Configuration
      • AOP
      • Patterns
        • Decorators
        • Facilities
        • Arrays (simple contributor patterns etc.)


But that's only a small brain dump... we will see what actually gets in there.

 

For anyone who's thinking of attending this event, anything in particular you would like to have covered in a little more depth... or have you had any exposure to IoC at all?

posted @ Tuesday, March 20, 2007 10:27:35 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |

Well first off... where has this month gone??... it's been 2 weeks since I last blogged... I thought it was only a week!

At any rate, one of the things I've been working on lately is mocking out COM interfaces (using RhinoMocks of course) ... and I have to admit that my eyes start crossing after a while, at about the point where the mock repositories setup code begins dominating the test case... which happens all too often... here's a smaller example of what I'm talking about:

MockRepository repository = new MockRepository();

TaggedValue oneTaggedValue = repository.DynamicMock<TaggedValue>();
Expect.Call(oneTaggedValue.Value = "").Constraints(Is.Equal("ExpectedValue"));
Expect.Call(textAlignTaggedValue.Update()).Return(true);

TaggedValue anotherTaggedValue = repository.DynamicMock<TaggedValue>();
Expect.Call(anotherTaggedValue.Value = "").Constraints(Is.Equal("AnotherExpectedValue"));
Expect.Call(textAlignTaggedValue.Update()).Return(true);

Collection taggedValuesCollection = repository.DynamicMock<Collection>();

Expect.Call(taggedValuesCollection.GetByName("")).Constraints(Is.Equal("OneTaggedValue"))
    .Return(oneTaggedValue).Repeat.Any();

Expect.Call(taggedValuesCollection.GetByName("")).Constraints(Is.Equal("AnotherTaggedValue"))
    .Return(anotherTaggedValue).Repeat.Any();

Element destinationElement = repository.DynamicMock<Element>();
Expect.Call(destinationElement.TaggedValues).Return(taggedValuesCollection).Repeat.Any();

repository.ReplayAll();

So in this case we have an "Element", which has a collection of "TaggedValues", and we have two tagged values "OneTaggedValue" and "AnotherTaggedValue", and for each we are updating their values, and then invoking "Update()" on them to flush the changes...

To help solidify that, here's an example of what we're expecting to happen to our element (Element, Collection and TaggedValue are all interfaces from a COM interop assembly, in case you were wondering):

Element element;
...
TaggedValue oneTaggedValue = (TaggedValue)element.TaggedValues.GetByName("OneTaggedValue");
oneTaggedValue.Value = "ExpectedValue";
oneTaggedValue.Update(); TaggedValue anotherTaggedValue = (TaggedValue)element.TaggedValues.GetByName("AnotherTaggedValue"); anotherTaggedValue.Value = "AnotherExpectedValue";
anotherTaggedValue.Update();

Now normally in this case I take unit tests once I've got "green" and refactor the mocking code out a bit... so in the above case I'd probably end up with something like:

MockRepository repository = new MockRepository();
            
Collection taggedValuesCollection = repository.DynamicMock<Collection>();
AddTaggedValueSetter(repository, taggedValuesCollection, "OneTaggedValue", "ExpectedValue");
AddTaggedValueSetter(repository, taggedValuesCollection, "AnotherTaggedValue", "AnotherExpectedValue");

Element destinationElement = repository.DynamicMock<Element>();            
Expect.Call(destinationElement.TaggedValues).Return(taggedValuesCollection).Repeat.Any();

repository.ReplayAll();

Which works... generally quite well... but lately I've been moving away from that approach and instead have been refactoring the setup code into a fluent interface... which I've found to be a lot easier to maintain and extend (and tends to be a little more re-usable across multiple test fixtures...)


So for example, this is what the setup code for the above mock element is now:

MockRepository repository = new MockRepository();

Element element =
    Mock
    .Element()
    .HasTaggedValue("OneTaggedValue").ExpectSetValue("ExpectedValue")
    .HasTaggedValue("AnotherTaggedValue").ExpectSetValue("AnotherExpectedValue")
    .Complete(repository);

repository.ReplayAll();

I'm just skimming the surface of what I've been doing, but it might be food for thought for anyone working on similar projects... anyone else doing similar things?

posted @ Tuesday, March 20, 2007 9:23:38 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |
 Tuesday, March 06, 2007
Have you ever wanted to be able to do something like this in C#?

string propertyName = GetName(MyClass.MyProperty);

Well I have, in fact I've wanted the ability to do this since Version 1 of the .Net Framework, and now with C# 3.0 we finally can!

First off, check out the original blog post here - Symbols in C# 3.0 by Jafar Husain - it's a clever (and once I thought about, plainly obvious) use of extension methods and expression trees.

public static class SymbolExtensions

{

    public static string GetPropertySymbol<T,R>(this T obj, Expression<Func<T, R>> expr)

    {

        return ((System.Linq.Expressions.MemberExpression)

           (((System.Linq.Expressions.LambdaExpression)(expr)).Body)).Member.Name;

    }

}


Usage requires a lambda, but that's not to painful, here's example usage:

MyClass o;

//...

string propertyName = this.GetPropertySymbol(o => o.MyProperty)


The beauty of this is that refactoring is entirely painless, you don't need to spend time reviewing all the optional string replacements that resharper may have found in case you haven't mirrored a property or method name change correctly... it also looks like it could offer some nice usability improvements to some unit testing scenarios (nothing worse then unit tests that don't seamlessly refactor with your code).

I wonder what other ideas are floating around for expression trees at the moment (outside of the obvious querying concepts) ?

posted @ Tuesday, March 06, 2007 2:18:22 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |
 Saturday, March 03, 2007

Dumping events

I'm often surprised (or is it dismayed) when questions pop up in news groups surrounding things like event orders for winforms or webforms applications... this isn't rocket science... we're given all the tools to make this easy to figure out!

Lets do a winforms 2.0 app as an example... first off, the earliest point at which can easily get involved is the constructor...  lets have a look:

public partial class Form1 : Form

{

    public Form1()

    {

        AttachToAllEvents();

        InitializeComponent();           

    }


So I'm going to attach to all the events before the forms components are initialized... now lets have a look at the "AttachToAllEvents" method.

private void AttachToAllEvents()

{           

    Type type = GetType();                      

 

    foreach (EventInfo info in type.GetEvents())

    {

        string eventName = info.Name;

 

        EventHandlerWrapper wrapper = new EventHandlerWrapper(new EventHandler(

            delegate

            {

                Console.WriteLine("{0}: EventName: {1}, IsVisible: {2}, IsHandleCreated: {3}, HasChildren: {4}, IsDisposed: {5}",

                                       DateTime.Now, eventName, this.Visible, this.IsHandleCreated, this.HasChildren,

                                       this.IsDisposed);                                                                       

            }));

 

        wrapper.Attach(this, info);               

    }

}


Only magic there is we're using a class called "EventHandlerWrapper" - what's that... well, it's used to create a strongly typed delegate for attaching to an event.

The reason we need this at all is because EventInfo.AddEventHandler(...) is fussy about the kind of delegate you supply, so if you pass in an "EventHandler" for a "CancelEventHandler" event, it'll throw an exception complaining about it's inability to cast between them... there might be an easier way to do this, but I haven't come across it so far.

public class EventHandlerWrapper

{

    private EventHandler _handler;

    private static readonly MethodInfo _methodInfo;

 

    static EventHandlerWrapper()

    {

        _methodInfo = typeof(EventHandlerWrapper).GetMethod("InvokeHandler", BindingFlags.NonPublic | BindingFlags.Instance);

    }

 

    public EventHandlerWrapper(EventHandler handler)

    {

        if (handler == null) throw new ArgumentNullException("handler");

        _handler = handler;

    }

 

    public void Attach(object target, EventInfo info)

    {

        Delegate wrappedHandler = Delegate.CreateDelegate(info.EventHandlerType, this, _methodInfo);

        info.AddEventHandler(target, wrappedHandler);       

    }

 

    private void InvokeHandler(object sender, EventArgs args)

    {

        _handler(sender, args);

    }

}


With a little brain power I'm sure I could've done this without the separate wrapper class, but this is probably a little easier to read at any rate.

Results..?

So.. onto the results - once we run the code and see exactly what order events are happening in, we can then make a pretty table that may not render in most browsers because I cut 'n pasted it from Excel 2007 ;o)

EventName  IsVisible  IsHandleCreated  HasChildren  IsDisposed
Resize  False  False  False  False
SizeChanged  False  False  False  False
ClientSizeChanged  False  False  False  False
ClientSizeChanged  False  False  False  False
ControlAdded  False  False  True  False
ControlAdded  False  False  True  False
StyleChanged  False  False  True  False
TextChanged  False  False  True  False
Move  False  True  True  False
LocationChanged  False  True  True  False
HandleCreated  False  True  True  False
Invalidated  False  True  True  False
StyleChanged  False  True  True  False
ChangeUICues  True  True  True  False
Invalidated  True  True  True  False
BindingContextChanged  True  True  True  False
Load  True  True  True  False
Layout  True  True  True  False
VisibleChanged  True  True  True  False
Activated  True  True  True  False
Shown  True  True  True  False
Paint  True  True  True  False
Paint  True  True  True  False
Paint  True  True  True  False
MouseCaptureChanged  True  True  True  False
Closing  True  True  True  False
FormClosing  True  True  True  False
Closed  True  True  True  False
FormClosed  True  True  True  False
Deactivate  True  True  True  False
HandleDestroyed  True  True  True  False
Disposed  False  False  False  False

The main thing to keep in mind when doing something like this is to avoid making assumptions - we may not be the first or last to attach to the events (depending on the complexity of the form) - and events can trigger other events... which could explain the ordering of some of this data i.e. changes in visibility and handle creation... if anything we are viewing the order of consequences, as opposed to the true order in which the events are invoked (to get that we'd need to override all the OnXXXX methods of the form class... which would be a good job for dynamic proxy :)
posted @ Saturday, March 03, 2007 12:54:32 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |
 Thursday, March 01, 2007
I've been using tortoise SVN for a couple of years now... but I'd never seen this dialog before when renaming files with similar name patterns... probably old news to some people, but it pleased me no end, very helpful!




It's these kinds of features that I like about an explorer based SCM client... I find IDE integrated source control just bugs me now days (like Team System which I use for codeplex).
posted @ Wednesday, February 28, 2007 11:38:48 PM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |
 Wednesday, February 28, 2007
In the last post about WiX shortcuts I detailed how to make an unisntall link... it was actually slightly wrong ;o) ... well at least if your product Id wasn't surrounded with braces... so here's the offending line fixed for product Guid's that aren't surrounded with braces (which is generally what you should be using in a WiX file)

<CustomAction Id="SetUninstallArgs" Property="UNINSTALLARGS" Value="/x {$(var.PRODUCTGUID)}" />


As you were...

posted @ Wednesday, February 28, 2007 6:48:27 AM (New Zealand Daylight Time, UTC+13:00)    Comments [0] | Trackback |

(Long) Shortcuts

Shortcuts are a basic concept in installers... and doing them with WiX is easy... once you know how... I just spent the last 10 minutes trying to get an Icon assigned to an advertised shortcut, here's how you do it...

<Component Id="StandAloneApplication" Guid="C8D5DB05-2D68-40e8-88D1-EF5BEA18DBE1">

  <File Id="SomeCompanySomeProductHostApp"

        Name="SomeCompany.SomeProduct.HostApp.exe"

        DiskId="1"

        Source="..\..\build\SomeCompany.SomeProduct.HostApp.exe"

        Vital="yes">

 

    <Shortcut Advertise="yes"

              Id="SomeCompanySomeProductHostAppShortcut"

              Directory="ProgramMenuDir"

              Name="My Product"

              WorkingDirectory="INSTALLDIR"

              Description="SomeProduct Application"

              Icon="HostAppShortcutIcon.exe">

 

      <Icon Id="HostAppShortcutIcon.exe"

            SourceFile="..\..\build\SomeCompany.SomeProduct.HostApp.exe" />

 

    </Shortcut>

  </File>

</Component>


The oddity is the way the Icon must be named with an ".exe" extension for it to work....  For non-advertised shortcuts you can get away with just leaving the icon out altogether.

Now something else my client wanted that I had to wrestle with a bit... how to create an uninstall shortcut for your product in the program menu's directory... here's how I achieved it, by creating a shortcut to msiexec.exe - I'm damn sure there must be easier way though, this is very clunky, but at least it works for now - if anyone knows an easier way then drop me a comment...

Personally I think uninstall links in the program menu are a waste of time... but in this case I wasn't the target audience I guess :P

Note: The "$(var.PRODUCTGUID)" refers to a constant being passed to WiX from my continuous integration build (I have a custom msbuild task for generating a single unique productId guid per revision in SVN)...

First off I define a couple of custom actions...

<CustomAction Id="SetUninstallArgs" Property="UNINSTALLARGS" Value="/x $(var.PRODUCTGUID)" />

<CustomAction Id="SetUninstallCmd" Property="UNINSTALLCMD" Value="MSIEXEC.EXE" />

I then evaluate them as part of the "InstallExecuteSequence" ... this doesn't actually have to be run before "FindRelatedProducts"... you can evaluate them quite late in the installation process.

<InstallExecuteSequence>

  <Custom Action="SetUninstallArgs" Before="FindRelatedProducts" />

  <Custom Action="SetUninstallCmd" Before="FindRelatedProducts" />


And then we can create our shortcut...

<Component Id="Uninstaller" Guid="0454D0FC-190C-42c9-9506-DBA17DECBCB2"

  <RegistryKey Action="createAndRemoveOnUninstall" Root="HKCU" Key="Software\MyProduct\Uninstaller">

    <RegistryValue Value="" Type="string" KeyPath="yes" />

  </RegistryKey>

  <Shortcut Id="InvokeRemove" Name="Uninstall" Target="[UNINSTALLCMD]" Arguments="[UNINSTALLARGS]" WorkingDirectory="SystemDir" Directory="ProgramMenuDir" Description="Uninstall" />

</Component>


You might be wondering why I place a dummy registry entry in there... well it's because otherwise you end up with an ICE 38 error - which seems daft to me, but then I don't really know enough about the windows installer architecture to dispute ICE's errors ;o) (ICE stands for Internal Consistency Evaluator(s) - which is used to validate the installer produced by WiX - have a look here for more info).

At any rate... I like the way WiX works... I would never go back to a gui-based setup project tool again, they might be fine for small projects, but once your project grows it just starts to suck hard... why? well... 4 reasons off the top of my head:
  • You can't diff between versions easily... just what did you coworker change in the setup last checkin?
  • Lack of global search and replace...
  • Generally a little more difficult to fit into CI builds.
  • Some of the products require you to use regasm or CLR code to register assemblies for com interop.
I just wish there was a decent cookbook... WiX has been going for over 2 years now, and It still seems a little hard to find decent information, I mostly rely on the official stuff... and of course examining how some open source projects have build their installers.
I might post a little bit on upgrades next time, that's the other task that took me a little time to get sorted, might proove useful to someone starting out with WiX... who could say.

BTW - I haven't forgotten about my LINQ series... It's just on the back burner at the moment.
posted @ Wednesday, February 28, 2007 4:35:54 AM (New Zealand Daylight Time, UTC+13:00)    Comments [4] | Trackback |
 Friday, February 23, 2007

Changes in the wind...


I'm looking at expanding my operation (Dev Defined Limited) - after having come to the conclusion that I can't support my current client base, and certainly can't offer them enough business continuity should I be put out of action - short of taking key man insurance out on myself ;o) - I need to start growing.

At any rate I've decided to do a few things:
  1. Start engaging old clients (and finding new clients) to queue up more work beyond my capacity.
  2. Taking on additional staff to both do that work, and transfer knowledge about existing clients and solutions.
Which brings me to the point of this post, I'm going to be looking for a couple of additional development staff (both senior).

So if you're a flexible senior developer, with a strong .Net background who wants to help build a development shop up, and is looking for opportunities to stretch their legs and play with some new and interesting technologies (instead of just reading about them on blog