The Best of Code Syndication

I was recently asked about who I learn from, so I threw together this list of goodplaces to get new ideas. Most of these are the RSS Links, not the web sites. I useGoogle Reader to make sure I keep up.

Top 3

.NET

General

Security

Funny

Podcasts

StructureMap: IRepository and Test Data Injection

I Love StructureMap! It’s wonderful. What a way to compose your code together easily,precisely, and consolidatedly (!!). When I put a sentence like that together, I wonderif I even know what I’m talking about. The problem with StructureMap, IoC, and dependencyinjection really seems to be that the jargon for the patterns is so manifestlytrue that once you learn what the hell you are doing, you are completelyunable to stop talking about it in shorthand. And that shorthand makes absolutelyno sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Onceyou do it, you’ll get it. Then you’ll be there and not be able toexplain to other people why you’re so right. It’s like being Tom Cruise and needingto explain scientology.

Anyways.

I learned two things today. The first is how to hook all of my concrete generic repositorytypes together with their interfaces. I had been adding a line of configuration foreach repository. Now my test code looks like this:

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(ListRepository<>));

And my production code:

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(LlblRepository<>));

That’s easy!

The other thing I learned is that I can happily and easily inject data into my objectregistry for testing purposes. I have an in-memory repository implementation built.All it needs is data.

public class MemoryDataSource{private Dictionary<Type, IQueryable> data;public MemoryDataSource(Dictionary<Type, IQueryable>data){this.data = data;}public IQueryable GetQueryable(Type type){return this.data[type];}}public class ListRepository<T>: IRepository<T>{private MemoryDataSource source;public ListRepository(MemoryDataSource source){this.source = source;}public IQueryable<T> GetSource(){return ((IQueryable<T>)source.GetQueryable(typeof(T)));}public void SaveEntity(Tentity){return;}}

Now all I need to do is build a Dictionary<> keyed on the entity object typeand fill it up with data. Once I’ve done that, I just pass it into the StructureMapregistry like this:

ObjectFactory.Inject<Dictionary<Type, IQueryable>>(dataSource);

Now I can have ObjectFactory construct my object under test and it’s got just thedata I need it to have.

Windows Forms Eventing: Generic Pub/Sub

In my lastpost, I covered how you can implement a publish/subscribe system for sending eventsbetween components of your Windows Forms application. Using this model, it is easyto create separate components that don’t rely on each other’s implementation detailsin order to provide a consistent experience for the user. A button on the toolbarcan be disabled by an action on the data entry screen…without hard references betweenthe two.

However, the implementation from last time required a new aggregator and set of interfacesfor each message type that needed to be passed around. Let’s fix that with generics.

Listener Interface

First we replace the IEventReciever interface from last time with a generic IListenerinterface that uses a generic type for the message object.

public interface IListener<T>{void Handle(T message);}
All your subscribers now implement an IListener<Message> for each messagetype they can handle. (This is great because one class can listen for multiple typesof messages!)

Event Aggregator Interface

Similarly, the Event Aggregator needs a generics reset. Notice that the Add and Removemethods now accept any old object.

public interface IEventAggregator{void SendMessage<T>(T message);void AddListener(object listener);void RemoveListener(object listener);}

Event Aggregator

public class EventAggregator: IEventAggregator{private readonly List<object>listeners = new List<object>();#region IEventAggregator Memberspublic void SendMessage<T>(Tmessage){listeners.CallOnEach<IListener<T>>(x => { x.Handle(message); });}public void AddListener(object listener){if (listeners.Contains(listener)) return;listeners.Add(listener);}public void RemoveListener(object listener){listeners.Remove(listener);}#endregion}

Not much new here….except for that CallOnEach method. Where did that come from?

Extension Methods

We need to add a few utility methods to the IEnumerables so that we can send our messages:

public static void CallOnEach<T>(this IEnumerableenumerable, Action<T> action) where T : class{foreach (object o in enumerable){o.CallOn(action);}}public static void CallOn<T>(this object target,Action<T> action) where T : class{var subject = target as T;if (subject != null){action(subject);}}

Put those in a likely static class somewhere.

Are we there yet?

This Event Aggregator is getting powerful. We should kill it before it develops languageskills.

With the code we have so far, we can easily create a new message in the system withoutmodifying the aggregator code. I like adding the methods as child classes of theirreceivers (when they are receiver-specific).

There is, however, still a problem. In the type of application that needs this eventingsystem, you are likely going to need to do some background threading to keep the UIresponsive. The Event Aggregator we have doesn’t do anything to keep itself or therest of the application synchronized.

What happens when a background thread sends a message that the receiver needs to acton by talking to the UI thread? Do you write a bunch of Invoke() code everywhere?

As it turns out, there is a better way. And my next post will show you how to upgradeyour EventAggregator to be the thread master!

Windows Forms Eventing: Adding Pub/Sub

In my lastpost, I described the creeping problem I’ve been having with wiring my large WindowsForms application up with EventHandler delegates. In short, the design becomes brittle—it’shard to write and hard to change. Luckily, the solution is an easy one: Publish/Subscribe.

The Event Aggregator is a singleton. You can either manage this yourself, or you canhave your Inversion of Control container do it for you. When an Event Receiver iscreated, it registers itself with the Event Aggregator, which stores a reference tothe receiver. When a Event Sender sends a message to the Event Aggregator, the aggregatorloops through all the registered receivers and calls a method on them to handle theevent. This is facilitated by having the receivers implementing an interface. Here’sa simple implementation:

public class EventMessage{public string MessageText{ get; set; }}public interface IEventReceiver{void Handle(EventMessage message);}public interface IEventAggregator{void SendMessage(EventMessage message);void AddReceiver(IEventReceiver receiver);void RemoveReceiver(IEventReceiver receiver);}public class EventAggregator: IEventAggregator{private readonly List<IEventReceiver>receivers = new List<IEventReceiver>();#region IEventAggregator Memberspublic void SendMessage(EventMessagemessage){receivers.ForEach(r => r.Handle(message));}public void AddReceiver(IEventReceiverreceiver){if (receivers.Contains(receiver)) return;receivers.Add(receiver);}public void RemoveReceiver(IEventReceiverreceiver){receivers.Remove(receiver);}#endregion}public class EventReceiver: IEventReceiver{public EventReceiver(IEventAggregator aggregator){aggregator.AddReceiver(this);}#region IEventReceiver Memberspublic void Handle(EventMessagemessage){Console.WriteLine(message.MessageText);}#endregion}public class EventSender{private IEventAggregator aggregator;public EventSender(IEventAggregator aggregator){this.aggregator = aggregator;}public void SendErrorMessage(string message){aggregator.SendMessage(new EventMessage { MessageText= message });}}

This is a big improvement over manual event wiring through an application. No longerdo the targets of a message need to know (have references to) the senders of the messagein order to make the connection. You can add a new target (receiver) without changingthe code of the sender. You can add a new sender without changing the code of thereceivers. And you don’t have to manually map things out in some sort of registryclass. This is simple easy and it will work.

It’s always something with you, isn’t it?

Ok. I like it. I’m happy. But how many of these things am I going to have floatingaround? It seems like a lot of code to write to hand one type of event between somecomponents. I’m going to have to hire some Indian outsourcing company to write allof these singleton aggregators.

This sounds like a job for generics! My next post will rewrite the Event Aggregatorso that a single aggregator can handle every message your application has.

Windows Forms Eventing: The Problem

Anxiety. This is a feeling I’ve been learning to recognize as a SIGN when I’m coding.The feeling you get when the camera gets really close on the face of the pretty girlas she walks around the empty, and silent, house. Is she going to turn around suddenlyand be given flowers? Or is the disemboweling only moments away. You don’t know, butyou’re cringing either way.

I’ve felt this in the past about data access layers. This is the feeling I’ve beenaccumulating around my Windows Forms application lately. I don’t want to code. I’mafraid to code. It’s going to be painful. I’m not sure what’s going to go wrong. Butsomething will, and I’ll be sucked into the unproductive death pit.

Having spent a bit of time feeling around the problem, I’m pretty sure what I don’tlike is having to deal with events. Let’s take a look at the reason why:

Windows forms makes things easy.

Click click click! I have a button and I have an event linked to it. Amazingly productive.My app will be running in no time.

Event Handlers are teh awesome.

It’s so easy to link an action to an event handler. Well. It’s pretty easy. It’s veryeasy within one class. Not so bad if you’ve got a reference to the object that containsthe event handler. A little bit of encapsulation makes it harder. Chained event handlerscan fix that though……

All is happy with one form per task.

This form is easy. Add a few buttons and it’s great. If you’re prepared to make yourapplication out of a bunch of forms that the user will work with one-by-one, there’sno problem.

However….sovereign apps don’t look like that.

If the user is going to be in one application all day long, it will have to provideeasy access to a number of different types of functionality. The application can’tconsolidate all of the interface elements required for a single task into a singleplace. Rather there’s a spaghetti monster of functionality, reaching it’s noodleyappendages everywhere.

Events flying every which way, and everything needs a hard reference to everythingelse.

Can you actually wire all this up with EventHandler references? Sure. Of course youcan. However, you end with a lot of tightly coupled code that is a real mess to createand to maintain.

Hope. The eternal struggle.

A application shell is a complicated beast. But problems have solutions. In my nextpost, I’ll show how you can integrate all these separate components without stranglingyourself in wiring.

Learn a Language Each Year

There’s a piece of advice that floats around,apparently from the PragmaticProgrammer, which goes like this:

Learn One New Language Each Year

I made a good start at Ruby last year, but got derailed by new exciting things overin the .NET world. This year is definitely the one.

I’ve got two reasons:

First, I’m really excited about programming phone systems with Adhearsion.

Second, I’ve realized that all the cool kids over at Microsoft spent the last 3 yearsgetting excited about Ruby. Not only are they developing their own Ruby runtime, butthe dynamicfeatures of C# 4.0 coming in VS2010 are obviously being designed to keep developersfrom jumping ship. We need to learn to think like Ruby coders toadapt to the new problems coming down the line.

One more thing…

Ruby is becoming a first-class citizen for Macintosh GUI application development.If you can write cross-platform libraries that work on the first-class frameworkson Windows, Linux, and the Mac…soon life will be nothing but champagne and swimsuitmodels!

NameValue, now with Distinct() support

One of the more useful little classes in my utility box is NameValue. It’s so veryeasy to fill with useful data from a Linq query, and once filled so easy to move betweenlayers, in a way that a projection simply can’t be used. The simple little NameValueclass bind just fine to a drop down menu, and will bring you tea after you finishwith that stupid girl that didn’t like your pony/monkey chimera.

I recently had to add equality checks and an override for == and != in order to makemerging two lists of name value pairs together possible. Now .Distinct() works ona List<NameValue>! There’s some goodmaterial out there for how to make a quality equality implementation.

[Serializable] public class NameValue{ public object Name{ get { return _Name;} set {_Name = value;} } protected virtual object _Name{ get; set;} public object Value{ get { return _Value;} set {_Value = value;} } protected virtual object _Value{ get; set;} public override bool Equals(object obj){ if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; // safebecause of the GetType check NameValuenv = (NameValue)obj; // usethis pattern to compare reference members if (!Object.Equals(this.Value,nv.Value)) return false; if (!Object.Equals(this.Name,nv.Name)) return false; return true;} public override int GetHashCode(){ return Name.GetHashCode() ^ Value.GetHashCode();} public static bool operator ==(NameValuen1, NameValue n2) { return n1.Equals(n2);} public static bool operator !=(NameValuen1, NameValue n2) { return !n1.Equals(n2);} }