Posterous theme by Cory Watilo

Filed under: C#

The Best of Code Syndication

I was recently asked about who I learn from, so I threw together this list of good places to get new ideas. Most of these are the RSS Links, not the web sites. I use Google 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 wonder if I even know what I’m talking about. The problem with StructureMap, IoC, and dependency injection really seems to be that the jargon for the patterns is so manifestly true that once you learn what the hell you are doing, you are completely unable to stop talking about it in shorthand. And that shorthand makes absolutely no sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Once you do it, you’ll get it. Then you’ll be there and not be able to explain to other people why you’re so right. It’s like being Tom Cruise and needing to explain scientology.

Anyways.

I learned two things today. The first is how to hook all of my concrete generic repository types together with their interfaces. I had been adding a line of configuration for each 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 object registry 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(T
entity)
{
return;
}
}

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

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

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

Windows Forms Eventing: Generic Pub/Sub

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

However, the implementation from last time required a new aggregator and set of interfaces for 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 IListener interface 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 message type they can handle. (This is great because one class can listen for multiple types of messages!)

Event Aggregator Interface

Similarly, the Event Aggregator needs a generics reset. Notice that the Add and Remove methods 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 Members

public void SendMessage<T>(T
message)
{
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 IEnumerable
enumerable, 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 language skills.

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

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

What happens when a background thread sends a message that the receiver needs to act on 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 upgrade your EventAggregator to be the thread master!

Windows Forms Eventing: Adding Pub/Sub

In my last post, I described the creeping problem I’ve been having with wiring my large Windows Forms application up with EventHandler delegates. In short, the design becomes brittle—it’s hard 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 can have your Inversion of Control container do it for you. When an Event Receiver is created, it registers itself with the Event Aggregator, which stores a reference to the receiver. When a Event Sender sends a message to the Event Aggregator, the aggregator loops through all the registered receivers and calls a method on them to handle the event. This is facilitated by having the receivers implementing an interface. Here’s a 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 Members
public void SendMessage(EventMessage
message)
{
receivers.ForEach(r => r.Handle(message));
}

public void AddReceiver(IEventReceiver
receiver)
{
if (receivers.Contains(receiver)) return;
receivers.Add(receiver);
}

public void RemoveReceiver(IEventReceiver
receiver)
{
receivers.Remove(receiver);
}
#endregion

}

public class EventReceiver
: IEventReceiver
{
public EventReceiver(IEventAggregator aggregator)
{
aggregator.AddReceiver(this);
}

#region IEventReceiver Members
public void Handle(EventMessage
message)
{
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 longer do the targets of a message need to know (have references to) the senders of the message in order to make the connection. You can add a new target (receiver) without changing the code of the sender. You can add a new sender without changing the code of the receivers. And you don’t have to manually map things out in some sort of registry class. 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 floating around? It seems like a lot of code to write to hand one type of event between some components. I’m going to have to hire some Indian outsourcing company to write all of these singleton aggregators.

This sounds like a job for generics! My next post will rewrite the Event Aggregator so 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 girl as she walks around the empty, and silent, house. Is she going to turn around suddenly and be given flowers? Or is the disemboweling only moments away. You don’t know, but you’re cringing either way.

I’ve felt this in the past about data access layers. This is the feeling I’ve been accumulating around my Windows Forms application lately. I don’t want to code. I’m afraid to code. It’s going to be painful. I’m not sure what’s going to go wrong. But something 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’t like 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 very easy within one class. Not so bad if you’ve got a reference to the object that contains the event handler. A little bit of encapsulation makes it harder. Chained event handlers can 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 your application out of a bunch of forms that the user will work with one-by-one, there’s no 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 provide easy access to a number of different types of functionality. The application can’t consolidate all of the interface elements required for a single task into a single place. Rather there’s a spaghetti monster of functionality, reaching it’s noodley appendages everywhere.

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

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

Hope. The eternal struggle.

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

Learn a Language Each Year

There’s a piece of advice that floats around, apparently from the Pragmatic Programmer, 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 over in 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 years getting excited about Ruby. Not only are they developing their own Ruby runtime, but the dynamic features of C# 4.0 coming in VS2010 are obviously being designed to keep developers from jumping ship. We need to learn to think like Ruby coders to adapt 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 frameworks on Windows, Linux, and the Mac…soon life will be nothing but champagne and swimsuit models!

NameValue, now with Distinct() support

One of the more useful little classes in my utility box is NameValue. It's so very easy to fill with useful data from a Linq query, and once filled so easy to move between layers, in a way that a projection simply can't be used. The simple little NameValue class bind just fine to a drop down menu, and will bring you tea after you finish with 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 make merging two lists of name value pairs together possible. Now .Distinct() works on a List<NameValue>! There's some good material 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; // safe because of the GetType check NameValue nv = (NameValue)obj; // use this 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 ==(NameValue n1, NameValue n2) { return n1.Equals(n2); } public static bool operator !=(NameValue n1, NameValue n2) { return !n1.Equals(n2); } }