16 November 2009
Writing an EventBroker
On a project I'm working on with my friend Michael, we need a web page to be build from independent modules - independent in the sense that they have no direct dependency on any other module and that they may operate autonomously. A lose coupling strategy for the various UI elements you could call it.
We need this kind of flexibility because the users of the system must be able to pick and choose any module, or any number of modules, for any given page, dynamically - that is, without the need for a developer to wire everything up in the code behind. They should be able to select the modules they want and the modules should function autonomous. The modules should also be able to send messages to other modules when needed, without knowledge of each other.
The way I went about achieving this was by writing an EventBroker. An EventBroker can be considered an implementation of the Publisher/Subscriber pattern or a sub-pattern or derivative thereof.
It is obvious, that to achieve loosely coupled modules that knows nothing of the other modules, yet are able to send messages to each other, we must move the coupling or change its direction to an intermediate component. This is the role of the EventBroker.
An example is in place. I have two modules. When the UpdateContent method in the first module is executed, I want the second module to be notified and do something about it.
I use well named interfaces to express the type of message send.
The SubscriberModule subscribe to messages of type UpdateContentEvent and assigns a messagehandler, UpdateContentHandler, to handle the message when or if it occur.
The PublisherModule first builds some event arguments, then publishes the event, UpdateContentEvent, and supplies a reference to itself as well as the arguments.
That is basically it. The two modules know nothing of each other, but are able to send and receive messages from and to each other through the EventBroker.
Some considerations:
This EventBroker implementation is static and as such represent the strongest coupling one can have between components. In this case I find it acceptable and consider it part of the infrastructure of the system we are building. It is possible to change the implementation slightly and inject the EventBroker into the classes that use it, or hide it behind a factory, but at this point I'm satisfied with the coupling it represents.
The implementation only allow modules to send and receive messages in a synchronous manner. This is all I need at the moment, but at some point it may need to support asynchronous messaging. If this need emerge, I'll consider a true message bus instead.
The implementation allow for any number of publishers and subscribers. I've wrapped the event handling Action delegate in a WeakReference so that the EventBroker does not become a greedy memory-clutching hub.
In truth the EventBroker mediates messages, not events in the sense of .NET events. In this implementation I switch between the terms event and message. This can be cause for misunderstandings. In the next version I'll remedy that...
Lastly, the EventBroker is thread safe.
And here is the EventBroker code:
We need this kind of flexibility because the users of the system must be able to pick and choose any module, or any number of modules, for any given page, dynamically - that is, without the need for a developer to wire everything up in the code behind. They should be able to select the modules they want and the modules should function autonomous. The modules should also be able to send messages to other modules when needed, without knowledge of each other.
The way I went about achieving this was by writing an EventBroker. An EventBroker can be considered an implementation of the Publisher/Subscriber pattern or a sub-pattern or derivative thereof.
It is obvious, that to achieve loosely coupled modules that knows nothing of the other modules, yet are able to send messages to each other, we must move the coupling or change its direction to an intermediate component. This is the role of the EventBroker.
An example is in place. I have two modules. When the UpdateContent method in the first module is executed, I want the second module to be notified and do something about it.
I use well named interfaces to express the type of message send.
public interface UpdateContentEvent {}
The SubscriberModule subscribe to messages of type UpdateContentEvent and assigns a messagehandler, UpdateContentHandler, to handle the message when or if it occur.
public class SubscriberModule
{ public SubscriberModule() { EventBroker.Subscribe<UpdateContentEvent>(UpdateContentHandler);
}
private void UpdateContentHandler(object sender, EventArgs e)
{ var args = e as UpdateContentEventArgs;
if(args != null)
{ string content = args.Content; // perform some update with content }
}
}
The PublisherModule first builds some event arguments, then publishes the event, UpdateContentEvent, and supplies a reference to itself as well as the arguments.
public class PublisherModule
{ public void DoUpdateContent()
{ EventArgs args = new UpdateContentEventArgs {Content = "Some content to be updated"};
EventBroker.Publish<UpdateContentEvent>(this, args);
}
}
That is basically it. The two modules know nothing of each other, but are able to send and receive messages from and to each other through the EventBroker.
Some considerations:
This EventBroker implementation is static and as such represent the strongest coupling one can have between components. In this case I find it acceptable and consider it part of the infrastructure of the system we are building. It is possible to change the implementation slightly and inject the EventBroker into the classes that use it, or hide it behind a factory, but at this point I'm satisfied with the coupling it represents.
The implementation only allow modules to send and receive messages in a synchronous manner. This is all I need at the moment, but at some point it may need to support asynchronous messaging. If this need emerge, I'll consider a true message bus instead.
The implementation allow for any number of publishers and subscribers. I've wrapped the event handling Action delegate in a WeakReference so that the EventBroker does not become a greedy memory-clutching hub.
In truth the EventBroker mediates messages, not events in the sense of .NET events. In this implementation I switch between the terms event and message. This can be cause for misunderstandings. In the next version I'll remedy that...
Lastly, the EventBroker is thread safe.
And here is the EventBroker code:
public static class EventBroker
{ static readonly IList<KeyValuePair<Type, WeakReference>> eventsSubscribedTo = new List<KeyValuePair<Type, WeakReference>>();
public static void Subscribe<TEventType>(Action<object, EventArgs> eventHandler)
{ lock (eventsSubscribedTo) eventsSubscribedTo.Add(new KeyValuePair<Type, WeakReference>(typeof(TEventType), new WeakReference(eventHandler)));
}
public static void Publish<TEventType>(object sender, EventArgs e)
{ lock (eventsSubscribedTo) { RemoveGarbageCollectedEventHandlers();
for (int i = 0; i < eventsSubscribedTo.Count; i++)
{ if (eventsSubscribedTo[i].Key == typeof(TEventType))
{ var eventHandler = eventsSubscribedTo[i].Value.Target as Action<object, EventArgs>;
if(eventHandler != null)
eventHandler(sender, e);
}
}
}
}
private static void RemoveGarbageCollectedEventHandlers()
{ for (int i = 0; i < eventsSubscribedTo.Count; i++)
{ KeyValuePair<Type, WeakReference> pair = eventsSubscribedTo[i];
WeakReference value = pair.Value;
var eventHandler = value.Target as Action<object, EventArgs>;
if (eventHandler == null)
eventsSubscribedTo.Remove(pair);
}
}
public static void Unsubscribe<TEventType>(Action<object, EventArgs> eventHandler)
{ lock (eventsSubscribedTo) for (int i = 0; i < eventsSubscribedTo.Count; i++)
{ KeyValuePair<Type, WeakReference> pair = eventsSubscribedTo[i];
Type eventType = pair.Key;
WeakReference weakReference = pair.Value;
var handler = weakReference.Target as Action<object, EventArgs>;
if (eventType == typeof(TEventType) && handler == eventHandler)
eventsSubscribedTo.Remove(pair);
}
}
public static void Clear()
{ lock (eventsSubscribedTo) eventsSubscribedTo.Clear();
}
}
Please feel free to suggest improvement or errors I have not detected.
Labels: Advanced Programming, C#
01 March 2009
Preface to my "Writing your own compiler" blog series
Before I start spraying out blog posts about writing your own compiler, I want to say a few things about my motivation and reasons to do so.
Compiler theory is the bread and butter of any undergraduate, graduate or mezzanine level computer science student. It is the theoretical and technical foundation used to write compilers of all sorts, but it is also a wide collection of models, theories, techniques and algorithms that can be applied to many other problems encountered in software development.
I was a CS student in the late 90ties and wrote a small compiler used in neural network pattern matching. It was terribly exiting to solve complex problems applying theory to concrete problems, but at the time I did not entirely realize the wider usefulness of the things I was taught. And so for several years after, while I still found compiler theory interesting, I did not use it much, as it did not lend itself easily to the kind of problems I worked with.
But as fate would have it, in the last few years I have found reason to reignite my interest in compiler theory, and now with more experience under my belt, I certainly recognize the wider applicability of compiler theory and techniques in many areas of software development. So during the last year or so, I have spend many late nights reaquainting myself with old friends like the lexical-, syntax- and the semantic analyzer as well as intermediate code generation and machine independent optimization. It has been a trip down my academic memory lane and it has been an exiting one.
So the goal with the coming series - "How to write your own compiler" - is two fold:
Writing about any subject requires you to reflect about that which you write. This is a great technique to learn more intimately the subject you write about. So in writing about compilers I hope to learn more about them than I did before.
As I progress in the series, I will explore other areas where the theory in question would be usefull. Hopefully this will persuade others to gain an interest in compiler theory.
Compiler theory is the bread and butter of any undergraduate, graduate or mezzanine level computer science student. It is the theoretical and technical foundation used to write compilers of all sorts, but it is also a wide collection of models, theories, techniques and algorithms that can be applied to many other problems encountered in software development.
I was a CS student in the late 90ties and wrote a small compiler used in neural network pattern matching. It was terribly exiting to solve complex problems applying theory to concrete problems, but at the time I did not entirely realize the wider usefulness of the things I was taught. And so for several years after, while I still found compiler theory interesting, I did not use it much, as it did not lend itself easily to the kind of problems I worked with.
But as fate would have it, in the last few years I have found reason to reignite my interest in compiler theory, and now with more experience under my belt, I certainly recognize the wider applicability of compiler theory and techniques in many areas of software development. So during the last year or so, I have spend many late nights reaquainting myself with old friends like the lexical-, syntax- and the semantic analyzer as well as intermediate code generation and machine independent optimization. It has been a trip down my academic memory lane and it has been an exiting one.
So the goal with the coming series - "How to write your own compiler" - is two fold:
Writing about any subject requires you to reflect about that which you write. This is a great technique to learn more intimately the subject you write about. So in writing about compilers I hope to learn more about them than I did before.
As I progress in the series, I will explore other areas where the theory in question would be usefull. Hopefully this will persuade others to gain an interest in compiler theory.
Labels: Advanced Programming, Compilers
09 September 2008
Lightweight Specification using lambda
Using the Specification pattern kan be somewhat cumbersome as the number of specifications increase. You will most certainly want to create so many generic specifications (ie. NonEmptyStringSpecification etc.) as you can and keep the number of specialized specifications to a minimum.
But even then, sometimes you just need to create a quick and dirty specification here and now, not wanting to create a whole class for it. You can ofcause just use a Predicate, but if you want to stay in the world of interfaces, you can use this code:
And if you have a Customer class such as this one:
You can use it like this:
And if you really insist, we could extend it to use the Composite Specification pattern - but I'll leave that as an exercise for you ;)
But even then, sometimes you just need to create a quick and dirty specification here and now, not wanting to create a whole class for it. You can ofcause just use a Predicate, but if you want to stay in the world of interfaces, you can use this code:
8 public interface ISpecification<T>
9 {10 bool IsSatisfiedBy(T candidate);
11 } 12 13 public abstract class AbstractSpecification<T> : ISpecification<T>
14 {15 protected readonly Predicate<T> predicate;
16 17 protected AbstractSpecification(Predicate<T> predicate)
18 {19 this.predicate = predicate;
20 } 21 22 public abstract bool IsSatisfiedBy(T candidate);
23 } 24 25 public class Specification<T> : AbstractSpecification<T>
26 {27 public Specification(Predicate<T> predicate) : base(predicate)
28 { 29 } 30 31 public override bool IsSatisfiedBy(T candidate)
32 {33 return predicate.Invoke(candidate);
34 } 35 }And if you have a Customer class such as this one:
25 public class Customer
26 {27 public string Name { get; set; }
28 public string Address { get; set; }
29 public string Zip { get; set; }
30 public string City { get; set; }
31 public string Phone { get; set; }
32 public string Email { get; set; }
33 public string ContactPerson { get; set; }
34 }You can use it like this:
49 class Program
50 {51 static void Main(string[] args)
52 {53 var customers = new List<Customer>()
54 {55 new Customer() { Name = "Birds and bees", Email = "info@birdsandbees.dk" },
56 new Customer() { Name = "Honey and sugar" },
57 new Customer() { Email = "info@lasttreeonearth.org" }
58 }; 59 60 // A valid customer must have a name and an email
61 var validCustomerSpecification = new Specification<Customer>(c => !string.IsNullOrEmpty(c.Name) && !string.IsNullOrEmpty(c.Email));
62 63 foreach (var customer in customers)
64 {65 if (validCustomerSpecification.IsSatisfiedBy(customer))
66 {67 Console.WriteLine("The valid customers are: " + customer.Name + " (" + customer.Email + ")");
68 }69 else
70 {71 Console.WriteLine("The invalid customers are: " + customer.Name + "( " + customer.Email + ")");
72 } 73 } 74 75 76 Console.ReadKey();
77 } 78 }And if you really insist, we could extend it to use the Composite Specification pattern - but I'll leave that as an exercise for you ;)
Labels: Advanced Programming, C#, Learning
08 September 2008
Composite Specification Pattern
I'm a bit pressed for time, so I'll just dumb the Composite Specification Pattern code here for now and comment it later.
7 public interface ISpecification<T>
8 {9 bool IsSatisfiedBy(T candidate);
10 ISpecification<T> And(ISpecification<T> other);
11 ISpecification<T> Or(ISpecification<T> other);
12 ISpecification<T> Not();
13 } 14 15 public class CompositeSpecification<T> : ISpecification<T>
16 {17 public virtual bool IsSatisfiedBy(T candidate)
18 {19 throw new NotImplementedException();
20 } 21 22 public ISpecification<T> And(ISpecification<T> other)
23 {24 return new AndSpecification<T>(this, other);
25 } 26 27 public ISpecification<T> Or(ISpecification<T> other)
28 {29 return new OrSpecification<T>(this, other);
30 } 31 32 public ISpecification<T> Not()
33 {34 return new NotSpecification<T>(this);
35 } 36 } 37 38 public class AndSpecification<T> : CompositeSpecification<T>
39 {40 private ISpecification<T> one;
41 private ISpecification<T> other;
42 43 public AndSpecification(ISpecification<T> one, ISpecification<T> other)
44 {45 this.one = one;
46 this.other = other;
47 } 48 49 public override bool IsSatisfiedBy(T candidate)
50 {51 return one.IsSatisfiedBy(candidate) && other.IsSatisfiedBy(candidate);
52 } 53 } 54 55 public class OrSpecification<T> : CompositeSpecification<T>
56 {57 private ISpecification<T> one;
58 private ISpecification<T> other;
59 60 public OrSpecification(ISpecification<T> one, ISpecification<T> other)
61 {62 this.one = one;
63 this.other = other;
64 } 65 66 public override bool IsSatisfiedBy(T candidate)
67 {68 return one.IsSatisfiedBy(candidate) || other.IsSatisfiedBy(candidate);
69 } 70 } 71 72 public class NotSpecification<T> : CompositeSpecification<T>
73 {74 private ISpecification<T> wrapped;
75 76 public NotSpecification(ISpecification<T> one)
77 { 78 wrapped = one; 79 } 80 81 public override bool IsSatisfiedBy(T candidate)
82 {83 return !wrapped.IsSatisfiedBy(candidate);
84 } 85 }Labels: Advanced Programming, C#, Patterns
07 September 2008
Specification pattern
Recently I introduced the Strategy pattern to a colleague. He caught on right away and within hours he had refactored a few monster classes to use the Strategy pattern, thereby improving the readability, the maintainability, the seperation of concern and the coherency of his code.
Now this week I'll introduce the Specification pattern to said colleague and see where it takes him :)
In short, the Specification pattern is a pattern for expressing a rule with which you want to test an object. The real power of a Specification is that it separates two distinct concerns; testing objects and the objects themselves.
So here is an example. I'll let the code speak for itself:
And here is how you could put it to use:
This is a very simple example. I'll follow up with a more realistic example and extend the Specification pattern shown here to the much more powerful Composite Specification pattern.
Now this week I'll introduce the Specification pattern to said colleague and see where it takes him :)
In short, the Specification pattern is a pattern for expressing a rule with which you want to test an object. The real power of a Specification is that it separates two distinct concerns; testing objects and the objects themselves.
So here is an example. I'll let the code speak for itself:
8 // The interface that all specifications must implement
9 public interface ISpecification<T>
10 {11 bool IsSatisfiedBy(T entity);
12 } 13 14 // In this example I'll be using two products of different type,
15 // that implement the same interface
16 public interface IProduct
17 {18 string Name { get; set; }
19 decimal Price { get; set; }
20 } 21 22 // The Bicycle class
23 public class Bicycle : IProduct
24 {25 public string Name { get; set; }
26 public decimal Price { get; set; }
27 } 28 29 // The MotorCycle class
30 public class MotorCycle : IProduct
31 {32 public string Name { get; set; }
33 public decimal Price { get; set; }
34 } 35 36 // The BicycleSpecification implements the ISpecification interface
37 // It checks if the type of entity equals the type of the Bicycle class
38 public class BicycleSpecification : ISpecification<IProduct>
39 {40 public bool IsSatisfiedBy(IProduct entity)
41 {42 return entity.GetType() == typeof(Bicycle);
43 } 44 } 45 46 // The MotorcycleSpecification implements the ISpecification interface
47 // It checks if the type of entity equals the type of the MotorCycle class
48 public class MotorcycleSpecification : ISpecification<IProduct>
49 {50 public bool IsSatisfiedBy(IProduct entity)
51 {52 return entity.GetType() == typeof(MotorCycle);
53 } 54 }And here is how you could put it to use:
8 class Program
9 {10 static void Main(string[] args)
11 {12 // Bicycles
13 Bicycle cycle1 = new Bicycle() { Price = 1000, Name = "cycle1" };
14 Bicycle cycle2 = new Bicycle() { Price = 2000, Name = "cycle2" };
15 Bicycle cycle3 = new Bicycle() { Price = 3000, Name = "cycle3" };
16 17 // MotorCycles
18 MotorCycle motorCycle1 = new MotorCycle() { Price = 40000, Name = "motorCycle1" };
19 MotorCycle motorCycle2 = new MotorCycle() { Price = 60000, Name = "motorCycle2" };
20 MotorCycle motorCycle3 = new MotorCycle() { Price = 80000, Name = "motorCycle3" };
21 22 // We add them to a List
23 List<IProduct> allProducts = new List<IProduct>();
24 allProducts.Add(cycle1); 25 allProducts.Add(cycle2); 26 allProducts.Add(cycle3); 27 allProducts.Add(motorCycle1); 28 allProducts.Add(motorCycle2); 29 allProducts.Add(motorCycle3); 30 31 // Instanciating a BicycleSpecification
32 BicycleSpecification cycleSpecification = new BicycleSpecification();
33 // Instanciating a MotorcycleSpecification
34 MotorcycleSpecification motorCycleSpecification = new MotorcycleSpecification();
35 36 // Lets iterate through our List
37 // For each cycle found in the List, we apply the BicycleSpecification to see
38 // if the current cycle satisfies it. If it does, we write its name and price out
39 foreach (var cycle in allProducts)
40 {41 if (cycleSpecification.IsSatisfiedBy(cycle))
42 {43 Console.WriteLine("Price of " + cycle.Name + " is $" + cycle.Price.ToString());
44 } 45 } 46 47 Console.WriteLine();
48 Console.WriteLine();
49 50 // Lets iterate through our List again
51 // For each cycle found in the List, we apply the MotorcycleSpecification to see
52 // if the current cycle satisfies it. If it does, we write its name and price out
53 foreach (var motorCycle in allProducts)
54 {55 if (motorCycleSpecification.IsSatisfiedBy(motorCycle))
56 {57 Console.WriteLine("Price of " + motorCycle.Name + " is $" + motorCycle.Price.ToString());
58 } 59 } 60 61 Console.ReadKey();
62 } 63 }This is a very simple example. I'll follow up with a more realistic example and extend the Specification pattern shown here to the much more powerful Composite Specification pattern.
Labels: Advanced Programming, C#, Code, Learning
25 January 2008
Silent but not dead
During the last two months I have been busy working. First off I have finished my pedagogical examn (Pædagogikum) which went very well (A). Secondly I have finished two projects which has taken quite a bit of my time. But for the next few weeks I'll spend some time blogging about the things I have learned and worked with the past eight to ten weeks or so.
Here's a list so I will not forget what to write about:
Here's a list so I will not forget what to write about:
- SpreadsheetML (Microsoft Office 2003 Edition XML Schema References)
- Visual Studio Tools for Office
- Monads and monoids
- Visitor pattern and Double Dispatch
- Dependency Injection with Windsor
Labels: Advanced Programming, DI, Excel, Learning, Patterns, Tools, Visual Studio 2008
Subscribe to Posts [Atom]


