<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mind-driven development</title>
	<atom:link href="http://www.minddriven.de/index.php/feed" rel="self" type="application/rss+xml" />
	<link>http://www.minddriven.de</link>
	<description>Matthias Jauernig -- .NET technology, architecture and design</description>
	<lastBuildDate>Mon, 30 Aug 2010 03:00:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Now on Twitter!</title>
		<link>http://www.minddriven.de/index.php/general/now-on-twitter</link>
		<comments>http://www.minddriven.de/index.php/general/now-on-twitter#comments</comments>
		<pubDate>Mon, 30 Aug 2010 03:00:44 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1046</guid>
		<description><![CDATA[Just a short announcement for today: Finally I found my way to Twitter, where you can find or reference me with @JauMatt. For a long time I didn&#8217;t see any value in Twitter. But I think I&#8217;ve been mistaken. I&#8217;m using Twitter for nearly 3 weeks now, with my new iPhone acting as initial trigger [...]]]></description>
			<content:encoded><![CDATA[<p>Just a short announcement for today: Finally I found my way to <strong>Twitter</strong>, where you can find or reference me with <a href="http://twitter.com/jaumatt">@JauMatt</a>.</p>
<p><a href="http://twitter.com/jaumatt"><img class="alignnone size-full wp-image-1047" style="border: 1px solid black;" title="Me on Twitter" src="http://www.minddriven.de/wp-content/uploads/2010/08/Twitter.png" alt="" width="435" height="156" /></a></p>
<p>For a long time I didn&#8217;t see any value in Twitter. But I think I&#8217;ve been mistaken. I&#8217;m using Twitter for nearly 3 weeks now, with my new iPhone acting as initial trigger <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>I love the simplicity of the Twitter concept. It&#8217;s great to keep in touch with people and to come into discussion on various tweets.<br />
I love it to share just some few thoughts, short comments, tipps and links, for which a fully fledged blog post would be way to big.</p>
<p><a href="http://twitter.com/jaumatt">Follow me</a> on Twitter to keep in touch and you&#8217;ll get:</p>
<ul>
<li>Links that I find useful,</li>
<li>My thoughts on current topics,</li>
<li>News about what I&#8217;m working on,</li>
<li>Sometimes a little personal stuff <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
</ul>
<p>See you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/general/now-on-twitter/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple message-based Event Aggregator/Broker</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/event-broker-implementation</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/event-broker-implementation#comments</comments>
		<pubDate>Sun, 29 Aug 2010 12:32:38 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[event aggregator]]></category>
		<category><![CDATA[event broker]]></category>
		<category><![CDATA[indirection]]></category>
		<category><![CDATA[message-based]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1023</guid>
		<description><![CDATA[This blog post is more about implementation than in-depth description or background information. It&#8217;s covering an implementation of a simple Event Broker/Aggregator that I&#8217;ve developed and used in a non-trivial Silverlight project and which I found quite useful. A word of warning: It&#8217;s not fully fledged and not suited for all scenarios&#8230; and it&#8217;s not [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post is more about implementation than in-depth description  or background information. It&#8217;s covering an implementation of a simple <strong>Event  Broker/Aggregator</strong> that I&#8217;ve developed and used in a non-trivial  Silverlight project and which I found quite useful. A word of warning: It&#8217;s not fully fledged and not suited for all scenarios&#8230; and it&#8217;s not intended to be.</p>
<h3>(Little) background</h3>
<p><img class="alignright size-full wp-image-1032" style="margin-left: 10px;" title="Event broker linkage, Copyright: Matthias Jauernig" src="http://www.minddriven.de/wp-content/uploads/2010/08/IMG_4537.jpg" alt="Event broker linkage, Copyright: Matthias Jauernig" width="400" height="267" />The first time I&#8217;ve seen an implementation of the <strong>event  aggregator/broker pattern</strong> (I call it <em>event broker</em> in the  following) was in the <a href="http://compositewpf.codeplex.com/">Prism</a> framework. I like the idea  behind this pattern. It&#8217;s decoupling event publishers and subscribers.  It&#8217;s representing a kind of <a href="http://www.eaipatterns.com/ramblings/03_hubandspoke.html"><strong>Hub</strong></a>. Each time a publisher publishs  an event it gets into the hub and then it&#8217;s redirected to the  subscribers. The publishers/subscribers don&#8217;t have to know each other,  they just have to know the concrete event broker which is a mediator and mediates  between both parties. Thus the event broker is realizing a useful <strong>indirection  mechanism</strong>.</p>
<p>The event broker can be used in many scenarios and situations.  I&#8217;ve mainly used it in <strong>UI-related scenarios</strong>, but it&#8217;s not limited  to that. In the UI situation it helped me out e.g. at <em>view  synchronization</em> and <em>indirect communication</em>: between multiple  user controls/views, views and view models (both directions) or views  and controllers. They don&#8217;t have to know each other and thus can be  loosely coupled.</p>
<p>While I came across with the Prism event aggregator at first, after some investigation I didn&#8217;t like the implementation very much in view of the usage from a client&#8217;s perspective. You first have to get an event from the event aggregator and then you can subscribe to this event or publish the event with some event arguments. This is kind of duplicated work. When I know the type of the event arguments why do I have to know the event anymore (under the assumption that there&#8217;s a 1:1 relationship between both)? <a href="http://neverindoubtnet.blogspot.com/2009/07/simplify-prism-event-aggregator.html">Others</a> <a href="http://thejoyofcode.com/A_Suck_Less_Event_Aggregator_for_Prism.aspx">came</a> <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/07/21/braindump-on-the-event-aggregator-pattern.aspx">across</a> with this issue as well. A better approach in my opinion is a <strong>solely message-based event broker</strong>. A system that doesn&#8217;t distinguish between events and event arguments, but is based on messages people can subscribe to and publish.</p>
<h3>Implementation</h3>
<p>Let&#8217;s come to the bits&#8217;n'bytes of my implementatoin. My message-based event broker should be able to handle messages of type <code>IMessage</code>. This is just an empty interface for type-correctness in the other components:</p>
<pre class="brush:csharp">public interface IMessage { }</pre>
<p>Another important component is the <code>ISubscription&lt;TMessage&gt;</code> interface and its default implementation <code>Subscription&lt;TMessage&gt;</code>. A subscription is something the event broker stores internally when an action should be subscribed to a message. This subscription process results in an <code>ISubscription&lt;TMessage&gt;</code> object, which is returned to the caller. The caller will be able to unsubscribe from the event broker with this subscription object &#8211; there&#8217;s no need to reference the subscribed action, which is handy e.g. in situations where you want to use anonymous methods (via delegates or lambdas). Furthermore when the subscription disposes it&#8217;s unsubscribed from the event broker, which I found quite useful in some scenarios:</p>
<pre class="brush:csharp">public interface ISubscription&lt;TMessage&gt; : IDisposable
    where TMessage : IMessage
{
    Action&lt;TMessage&gt; Action { get; }
    IEventBroker EventBroker { get; }
}

public class Subscription&lt;TMessage&gt; : ISubscription&lt;TMessage&gt;
    where TMessage : IMessage
{
    public Action&lt;TMessage&gt; Action { get; private set; }
    public IEventBroker EventBroker { get; private set; }

    public Subscription(IEventBroker eventBroker, Action&lt;TMessage&gt; action)
    {
        if(eventBroker == null) throw new ArgumentNullException("eventBroker");
        if(action == null) throw new ArgumentNullException("action");

        EventBroker = eventBroker;
        Action = action;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(disposing)
            EventBroker.UnSubscribe(this);
    }
}</pre>
<p>Note the reference to <code>EventBroker</code> in the interface and its use in the implementation. That&#8217;s necessary due to the disposing functionality. Of course if you don&#8217;t want this behavior in your scenario you can adapt the implementation.</p>
<p>At the end the <code>IEventBroker</code> interface and its default implementation <code>EventBroker</code> handle the whole message publish/subscribe mechanism. Clients can <code>Subscribe()</code> to specific types of messages with custom actions that are stored in an <code>ISubscription&lt;TMessage&gt;</code> object. Those clients can <code>UnSubscribe()</code> if they&#8217;re owning the <code>ISubscription&lt;TMessage&gt;</code> object. Other clients can <code>Publish()</code> concrete messages, which gets the subscribers of the message notified:</p>
<pre class="brush:csharp">public interface IEventBroker
{
    void Publish&lt;TMessage&gt;(TMessage message)
        where TMessage : IMessage;

    ISubscription&lt;TMessage&gt; Subscribe&lt;TMessage&gt;(Action&lt;TMessage&gt; action)
        where TMessage : IMessage;

    void UnSubscribe&lt;TMessage&gt;(ISubscription&lt;TMessage&gt; subscription)
        where TMessage : IMessage;

    void ClearAllSubscriptions();
    void ClearAllSubscriptions(Type[] exceptMessages);
}

public class EventBroker : IEventBroker
{
    private readonly IDictionary&lt;Type, IList&gt; _subscriptions = new Dictionary&lt;Type, IList&gt;();

    public void Publish&lt;TMessage&gt;(TMessage message)
        where TMessage : IMessage
    {
        if(message == null) throw new ArgumentNullException("message");

        Type messageType = typeof(TMessage);
        if(_subscriptions.ContainsKey(messageType))
        {
            var subscriptionList = new List&lt;ISubscription&lt;TMessage&gt;&gt;(
                _subscriptions[messageType].Cast&lt;ISubscription&lt;TMessage&gt;&gt;());
            foreach(var subscription in subscriptionList)
                subscription.Action(message);
        }
    }

    public ISubscription&lt;TMessage&gt; Subscribe&lt;TMessage&gt;(Action&lt;TMessage&gt; action)
        where TMessage : IMessage
    {
        Type messageType = typeof(TMessage);
        var subscription = new Subscription&lt;TMessage&gt;(this, action);

        if(_subscriptions.ContainsKey(messageType))
            _subscriptions[messageType].Add(subscription);
        else
            _subscriptions.Add(messageType, new List&lt;ISubscription&lt;TMessage&gt;&gt;{subscription});

        return subscription;
    }

    public void UnSubscribe&lt;TMessage&gt;(ISubscription&lt;TMessage&gt; subscription)
        where TMessage : IMessage
    {
        Type messageType = typeof(TMessage);
        if (_subscriptions.ContainsKey(messageType))
            _subscriptions[messageType].Remove(subscription);
    }

    public void ClearAllSubscriptions()
    {
        ClearAllSubscriptions(null);
    }

    public void ClearAllSubscriptions(Type[] exceptMessages)
    {
        foreach (var messageSubscriptions in new Dictionary&lt;Type, IList&gt;(_subscriptions))
        {
            bool canDelete = true;
            if (exceptMessages != null)
                canDelete = !exceptMessages.Contains(messageSubscriptions.Key);

            if (canDelete)
                _subscriptions.Remove(messageSubscriptions);
        }
    }
}</pre>
<h3>Usage</h3>
<p>The usage of this event broker implementation is simple. Clients can subscribe to messages they&#8217;re interested in:</p>
<pre class="brush:csharp">// Option 1: Explicit action subscription
Action&lt;MyMessage&gt; someAction = message =&gt; { /*...*/ };
var subscription1 = eventBroker.Subscribe(someAction);

// Option 2: Subscription via lambda
var subscription2 = eventBroker.Subscribe&lt;MyMessage&gt;(message =&gt; { /*...*/ });</pre>
<p>The clients get an <code>ISubscription&lt;TMessage&gt;</code> in return, from which they&#8217;re able to unsubscribe:</p>
<pre class="brush:csharp">// Option 1: Unsubscribe by calling the event broker method
eventBroker.UnSubscribe(subscription);

// Option 2: Unsubscribe by calling Dispose() on the subscription object
subscription.Dispose();</pre>
<p>Other clients now are able to publish concrete messages and subscribers get informed about those messages:</p>
<pre class="brush:csharp">eventBroker.Publish(new MyMessage{ /*...*/ });</pre>
<p>How to get an instance of <code>IEventBroker</code>, you may ask? Well, that&#8217;s your decision! Implement a singleton for accessing an instance, use your favorite DI container, whatever&#8230;</p>
<h3>Conclusion</h3>
<p>That&#8217;s it. A simple message-based event broker implementation that can be used in a variety of situations. And which can be replaced by other  implementations as well. Perhaps you want to persist or log messages, enable detached subscribers, allow async event processing or even further functionality like load balancing&#8230; It&#8217;s up to you to provide your own implementation. And feel free to connect the <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">Latch Pattern</a> <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>While the presented <code>EventBroker</code> perfectly fitted <em>my</em> needs, it&#8217;s not intended to be universally applicable. For example I know that Prism uses <code>WeakReference</code>s to simplify garbage collection. I say it again: feel free to do that in your own implementation. Besides there are many more <em>syntactic</em> ways to implement event brokers. Paste your comments if you have further suggestions &#8211; you&#8217;re welcome!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1023"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1023" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/event-broker-implementation/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Property Memento pattern</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern#comments</comments>
		<pubDate>Wed, 11 Aug 2010 09:22:30 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[memento]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[property memento]]></category>
		<category><![CDATA[restore value]]></category>
		<category><![CDATA[state]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=975</guid>
		<description><![CDATA[This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime! Problem description It&#8217;s a common task in several scenarios: you want to store the value of an object&#8217;s property, then temporarily change it to perform some actions and at the end restore [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post shows the Property Memento as pattern for storing property values and later restoring from those. Constructive feedback is welcome everytime!</p>
<h3>Problem description</h3>
<p>It&#8217;s a common task in several scenarios: you want to store the value of an object&#8217;s property, then temporarily change it to perform some actions and at the end restore the original property value again. Especially with UI-related task you come into this situation quite often.</p>
<p>The last time I came across with this requirement is only some days/weeks ago and was a UI task as well. I created a generic detail view in WinForms, which was built up by Reflection from an object&#8217;s properties and optional metadata information. This form contained a control for the object&#8217;s values on the one side and a validation summary control for showing validation messages on the other side. The validation summary had to change its content and layout dynamically while performing validation.</p>
<p>Through the dynamic nature of the form unfortunately I couldn&#8217;t use the <code>AutoSize</code> feature and thus had to layout the control manually (calculating and setting control sizes etc.). But I <em>still</em> wanted to use some <code>AutoSize</code> functionality, at least for the validation summary. And here&#8217;s the deal: everytime the validation messages on the summary change, the control should <code>AutoSize</code> to fit its content. With the new size I recalculate the Height of the whole form. This task can be done by manually setting the <code>AutoSize</code> property temporarily. Additionally it&#8217;s necessary to temporarily set the <code>Anchor</code> property of the details control and the validation summary to complete the layouting process correctly.</p>
<p>Normally in the past I would have used a manual approach like this:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    bool oldValSumAutoSize = _valSum.AutoSize;
    AnchorStyles oldValSumAnchor = _valSum.Anchor;
    AnchorStyles oldDetailAnchor = _detailContent.Anchor;

    _valSum.AutoSize = true;
    _valSum.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    _detailContent.Anchor = AnchorStyles.Left | AnchorStyles.Top;

    _valSum.SetValidationMessages(validationMessages);

    newValSumHeight = _valSum.Height;
    Height = Height - oldValSumHeight + newValSumHeight;

    _valSum.AutoSize = oldValSumAutoSize;
    _valSum.Anchor = oldValSumAnchor;
    _detailContent.Anchor = oldDetailAnchor;

    _valSum.Height = newValSumHeight;
}</pre>
<p>What a <strong>verbose and dirty code</strong> for such a simple task! Saving the old property values, setting  the new values, performing some action and restoring the original property values&#8230; It&#8217;s even hard to find out the <strong>core logic</strong> of the method. Oh dear! While this solution works, it has a really <strong>poor readability</strong>. Moreover it&#8217;s not dealing with <strong>exceptions</strong> that could occur when actions are performed in between. Thus the UI could be left in an inconsistently layouted state and presented to the user in this way. What a mess! But what&#8217;s the alternative?</p>
<h3>The  Property Memento</h3>
<p>Better solution? What do you think about that:</p>
<pre class="brush:csharp">private void SomeMethod(...)
{
    int oldValSumHeight = _valSum.Height;
    int newValSumHeight = 0;

    using (GetAutoSizeMemento(_valSum, true))
    using (GetAnchorMemento(_valSum, AnchorStyles.Top|AnchorStyles.Left))
    using (GetAnchorMemento(_detailContent, AnchorStyles.Top|AnchorStyles.Left))
    {
        _valSum.SetValidationMessages(validationMessages);

        newValSumHeight = _valSum.Height;
        Height = Height - oldValSumHeight + newValSumHeight;
    }

    _valSum.Height = newValSumHeight;
}

private PropertyMemento&lt;Control, bool&gt; GetAutoSizeMemento(
    Control control, bool tempValue)
{
    return new PropertyMemento&lt;Control, bool&gt;(
        control, () =&gt; control.AutoSize, tempValue);
}

private PropertyMemento&lt;Control, AnchorStyles&gt; GetAnchorMemento(
    Control control, AnchorStyles tempValue)
{
    return new PropertyMemento&lt;Control, AnchorStyles&gt;(
        control, () =&gt; control.Anchor, tempValue);
}</pre>
<p>Notice that the logic of <code>SomeMethod()</code> is <strong>exactly the same</strong> as in the first code snippet. But now the responsibility of storing and restoring property values is encapsulated in Memento objects which are utilized inside a <code>using(){ }</code> statement. <code>GetAutoSizeMemento()</code> and <code>GetAnchorMemento()</code> are just two simple helper methods to create the Memento objects, which support readability in this blog post, but nothing more&#8230;</p>
<p>So how is the Property Memento working <strong>conceptually</strong>? On creation of the Property Memento it stores the original value of an object&#8217;s property. Optionally it&#8217;s possible to set a new temporary value for this property as well. During the lifetime of the Property Memento the value of the property can be changed by a developer. Finally when <code>Dispose()</code> is called on the Property Memento, the initial property value is restored. Thus the Property Memento clearly encapsulates the task of storing and restoring property values.</p>
<p>The <strong>technical implementation</strong> of the Property Memento in C# uses Reflection and is shown below:</p>
<pre class="brush:csharp">public class PropertyMemento&lt;TClass, TProperty&gt; : IDisposable
    where TClass : class
{
    private readonly TProperty _originalPropertyValue;
    private readonly TClass _classInstance;
    private readonly Expression&lt;Func&lt;TProperty&gt;&gt; _propertySelector;

    public PropertyMemento(TClass classInstance,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        _classInstance = classInstance;
        _propertySelector = propertySelector;
        _originalPropertyValue =
            ReflectionHelper.GetPropertyValue(classInstance, propertySelector);
    }

    public PropertyMemento(TClass memberObject,
        Expression&lt;Func&lt;TProperty&gt;&gt; memberSelector, TProperty tempValue)
        : this(memberObject, memberSelector)
    {
        SetPropertyValue(tempValue);
    }

    public void Dispose()
    {
        SetPropertyValue(_originalPropertyValue);
    }

    private void SetPropertyValue(TProperty value)
    {
        ReflectionHelper.SetPropertyValue(
            _classInstance, _propertySelector, value);
    }
}</pre>
<p>This implementation uses the following <code>ReflectionHelper</code> class:</p>
<pre class="brush:csharp">static class ReflectionHelper
{
    public static PropertyInfo GetProperty&lt;TEntity, TProperty&gt;(
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        return GetProperty&lt;TEntity&gt;(GetPropertyName(propertySelector));
    }

    public static PropertyInfo GetProperty&lt;T&gt;(string propertyName)
    {
        var propertyInfos = typeof(T).GetProperties();
        return propertyInfos.First(pi =&gt; pi.Name == propertyName);
    }

    public static string GetPropertyName&lt;T&gt;(
        Expression&lt;Func&lt;T&gt;&gt; propertySelector)
    {
        var memberExpression = propertySelector.Body as MemberExpression;
        return memberExpression.Member.Name;
    }

    public static TProperty GetPropertyValue&lt;TEntity, TProperty&gt;(
        TEntity entity, Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector)
    {
        return (TProperty)GetProperty&lt;TEntity, TProperty&gt;(propertySelector)
            .GetValue(entity, null);
    }

    public static void SetPropertyValue&lt;TEntity, TProperty&gt;(TEntity entity,
        Expression&lt;Func&lt;TProperty&gt;&gt; propertySelector, TProperty value)
    {
        GetProperty&lt;TEntity, TProperty&gt;(propertySelector)
            .SetValue(entity, value, null);
    }
}</pre>
<p>As you can see, the Property Memento implementation is no rocket science. The constructor gets the class instance and an <code>Expression</code> which selects the property from this instance. Optionally you can provide a property value that should be set temporarily in place of the original value. Getting and setting the property value is done via the <code>ReflectionHelper</code> class. For the sake of shortness the implementation doesn&#8217;t have a good error handling mechanism. You could employ your own checks if you want. What I like is the use of generics. This eliminates many error sources and guides a developer with the usage of the Property Memento.</p>
<h3>Really a pattern and a Memento?</h3>
<p>I&#8217;ve used the Property Memento now in several different situations with success and thus I think it&#8217;s justified to call it a <em>pattern</em>.</p>
<p>But is it a <em>Memento</em> as well? Wikipedia says about the <a href="http://en.wikipedia.org/wiki/Memento_pattern" target="_blank">Memento pattern</a>:</p>
<blockquote><p>&#8220;The <strong>memento pattern</strong> is a <a title="Design pattern (computer science)" href="http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29">software design pattern</a> that provides the ability to restore an object to its previous state [...]&#8220;</p></blockquote>
<p>And this is true for the Property Memento, where the &#8220;object&#8221; equals a property value on a class instance! The &#8220;previous state&#8221; is stored on creation of the Memento and &#8220;restore an object&#8221; is done on call of <code>Dispose()</code>.</p>
<h3>Finally</h3>
<p>This blog post has shown the Property Memento as pattern for storing original property values and later on restoring them.</p>
<p>Compared to the &#8220;manual way&#8221; the Property Memento has valuable advantages. It <strong>encapsulates the responsibility</strong> of storing an original value and restoring it when the <code>using()</code> block is finished. Client code remains clean and is condensed to the <strong>core logic</strong>, while delegating responsibilities to the Property Memento by an explicit <code>using(){ }</code> block. Thus the code becomes much more concise and <strong>readable</strong>. Last but not least the Property Memento employs an automatic <strong>exception handling</strong> mechanism. If an exception occurs inside a <code>using()</code> block of the Property Memento, finally the <code>Dispose()</code> method is called. Thus the Property Memento restores the original property state even in exceptional situations and the user gets a consistent layouted UI.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d975" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/property-memento-pattern/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting encapsulated type of Nullable</title>
		<link>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/underlying-nullable-type</link>
		<comments>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/underlying-nullable-type#comments</comments>
		<pubDate>Sun, 08 Aug 2010 11:01:26 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[encapsulated type]]></category>
		<category><![CDATA[Nullable]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=1013</guid>
		<description><![CDATA[Just a short tip for today.. Sometimes I&#8217;ve had the requirement to treat value types, where I don&#8217;t know if the value type is Nullable&#60;T&#62; or not. Regardless of whether the value type is declared as Nullable&#60;T&#62; or not, it should everytime be treat as T. Thus I&#8217;ve had to find out the underlying type [...]]]></description>
			<content:encoded><![CDATA[<p>Just a short tip for today..</p>
<p>Sometimes I&#8217;ve had the requirement to treat value types, where I don&#8217;t know if the <strong>value type is Nullable&lt;T&gt;</strong> or not. Regardless of whether the value type is declared as <code>Nullable&lt;T&gt;</code> or not, it should everytime be treat as <code>T</code>. Thus I&#8217;ve had to find out the underlying type of the <code>Nullable&lt;T&gt;</code>.</p>
<p>The following <strong>extension method on <code>Type</code></strong> realizes this requirement:</p>
<pre class="brush:csharp">public static class TypeExtensions
{
    public static Type GetBareType(this Type dataType)
    {
        if (dataType != null)
        {
            if (dataType.IsGenericType &amp;&amp;
               (dataType.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;)))
            {
                dataType = Nullable.GetUnderlyingType(dataType);
            }
        }
        return dataType;
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/dot-net/c-sharp/underlying-nullable-type/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Latch me if you can!</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern#comments</comments>
		<pubDate>Wed, 04 Aug 2010 07:22:38 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[design pattern]]></category>
		<category><![CDATA[Latch]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=968</guid>
		<description><![CDATA[In my first blog post I&#8217;ve shown a common UI problem when it comes to event handling and programmatic vs. user-triggered events on the one handside and to infinite loops due to recursive event chains on the other. With event detach/attach and boolean flags I&#8217;ve shown two simple solutions which are very common in many [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem">first blog post</a> I&#8217;ve shown  a <strong>common UI problem</strong> when it comes to event handling and programmatic  vs. user-triggered events on the one handside and to infinite loops due to recursive event chains on the other. With event detach/attach  and boolean flags I&#8217;ve shown two simple solutions which are very common  in many development projects. But they have their shortcomings and just don&#8217;t feel <em>natural</em>. This blog post shows an alternative which I found  simple and beautiful.</p>
<h3>Latch to the rescue</h3>
<p>Jeremy Miller introduced the <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/07/02/build-your-own-cab-12-rein-in-runaway-events-with-the-quot-latch-quot.aspx">Latch design pattern</a> as possible solution for the  problem at hand. It&#8217;s a tiny beautiful, yet little know solution and  the latter is a pitty. A <strong>Latch</strong> encapsulates the logic of executing an  action depending on the current state of the Latch. If the Latch is in  &#8220;Latched&#8221; state, no action is executed. And actions can be executed inside  of the Latch (changing the state to &#8220;Latched&#8221;), preventing other actions  from executing.</p>
<h3>Latch #1: Disposing Latch</h3>
<p>Before reading Jeremy&#8217;s post, I&#8217;ve made a sort of Latch pattern for myself. Here the Latch implements <code>IDisposable</code>, and the Latched state is set on creation of the Latch and  reset at a call of <code>Dispose()</code>. This allows the application of the <code>using() { }</code> syntax and the Latch state is reset automatically when exceptions  occur. The <code>Latch</code> class would look like this:</p>
<pre class="brush:csharp">public class Latch : IDisposable
{
    public bool IsLatched { get; private set; }

    public Latch()
    {
        IsLatched = true;
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }

    public void Dispose()
    {
        IsLatched = false;
    }

    public static Latch Latched
    {
        get { return new Latch(); }
    }
    public static Latch UnLatched
    {
        get { return new Latch { IsLatched = false }; }
    }
}</pre>
<p>The  <code>RunIfNotLatched()</code> method is just a little helper which executes an action given on the current state of the Latch. The actual application of the Latch in the example code from the <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem">previous post</a> is shown here:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private Latch _textSetByCodeLatch = Latch.UnLatched;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                using (_textSetByCodeLatch = new Latch())
                {
                    _someTextBox.Text = value.SomeValue;
                }
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =&gt;
        {
            // perform data/view update operations
        });
    }
}</pre>
<p>At first sight I liked the <code>using() { }</code> syntax. It frees the application code from manually reseting the Latch to UnLatched state. At  second sight I think there could be a cleaner solution. In my Latch  implementation the <code>using() { }</code> syntax is kind of <em>misused</em> and could lead  to irritations because there is implicit knowledge about the internal  functionality of the Latch. Again, the intent is not <em>explicitly</em> revealed.</p>
<h3>Latch #2: Boolean Latch</h3>
<p>A cleaner solution with explicit methods for running actions inside  of the Latch and missing action execution when other actions have  entered the Latch could be the following Latch implementation:</p>
<pre class="brush:csharp">public class Latch
{
    public bool IsLatched { get; private set; }

    public void RunLatched(Action action)
    {
        try
        {
            IsLatched = true;
            action();
        }
        finally
        {
            IsLatched = false;
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}</pre>
<p>Here the basic boolean logic behind matches with  the Disposing Latch, but the syntax has changed. The Latch now contains  two methods. <code>RunLatched()</code> executes an action inside the Latch and  prevents actions from being executed in <code>RunIfNotLatched()</code>. Here&#8217;s the usage for this Latch type in our example:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private readonly Latch _textSetByCodeLatch = new Latch();

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _textSetByCodeLatch.RunLatched(() =&gt;
                {
                    _someTextBox.Text = value.SomeValue;
                });
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        _textSetByCodeLatch.RunIfNotLatched(() =&gt;
        {
            // perform data/view update operations
        });
    }
}</pre>
<p>Now  the Latch has a cleaner and more explicit syntax. And like the Disposing  Latch it has a clean exception handling mechanism. That&#8217;s the good  news. With that our Boolean Latch is applicable in most simple  scenarios. But not in all! Imagine <em>parallel execution</em> of UI actions.  Moreover imagine having two actions which should be run in <code>RunLatched()</code> of the same Latch object &#8211; again in parallel:</p>
<ol>
<li>Action 1 enters <code>RunLatched()</code> and the Latch changes its state.</li>
<li>Action 2 enters <code>RunLatched()</code>, the Latch state remains in  <code>IsLatched</code>.</li>
<li>Action 1 leaves <code>RunLatched()</code> and the Latch changes its state to  not latched.</li>
</ol>
<p>Step 3 is the problem. Action 2 is still running inside the Latch,  but due to the boolean logic the Latch is not latched any longer. Thus  other actions are executed when given to <code>RunIfNotLatched()</code>, which is no  help on the initial problem. This is not only true for the Boolean  Latch, but for the Disposing Latch as well.</p>
<h3>Latch #3: Counting Latch</h3>
<p>This problem is solved by the Counting Latch, which is most similar  to Jeremy&#8217;s Latch implementation. Instead of having just a boolean  discriminator, it employs a counter for parallel <code>RunLatched()</code> calls. The  <code>IsLatched</code> state is determined based on this counter. If it&#8217;s equal to <code>0</code>, the Latch is not latched (because no method is currently running  inside of <code>RunLatched()</code>). Else the Latch is treat as latched. Here&#8217;s the  implementation of this Latch variant (edit: thanks nwiersma for the thread-safe <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern#comment-6208">hint</a>):</p>
<pre class="brush:csharp">public class Latch
{
    private readonly object _counterLock = new object();

    public int LatchCounter { get; private set; }

    public bool IsLatched
    {
        get { return (LatchCounter &gt; 0); }
    }

    public void RunLatched(Action action)
    {
        try
        {
            lock(_counterLock) { LatchCounter++; }
            action();
        }
        finally
        {
            lock(_counterLock) { LatchCounter--; }
        }
    }

    public void RunIfNotLatched(Action action)
    {
        if (IsLatched)
            return;

        action();
    }
}</pre>
<p>The  usage in this case is equivalent to the Boolean Latch. You should note that <em>each</em> of these Latch implementations works, it&#8217;s just a matter  of your requirements which of them you want to use. The Counting Latch as  most generic Latch implementation above and applies to most situations.</p>
<h3>Benefits of using the Latch</h3>
<p>Using the Latch for the foresaid problems has clear advantages over the  use of event detach/attach and boolean flags. First the Latch  <em>encapsulates the logic</em> of running actions depending on a state, in this  case the current execution of another action. Thus the purpose of a  Latch is <em>explicit</em>, in contrast to the implicit intent of e.g. boolean  flags. This <em>increases code readability</em>.</p>
<p>The second advantage  comes with <em>resetting the initial state</em>. The Latch performs this task  itself when an action leaves the <code>RunLatched()</code> method for example. With  boolean flags and event detach/attach this is your task. It&#8217;s most likely getting problematic if exceptions are thrown  inside an action. The Latch takes over the responsibility of automatically rolling back the state of the Latch on occurrence of an exception.</p>
<p>In <strong>conclusion</strong> the Latch is a pretty simple design pattern which increases readability  and <em>feels right</em> for the problem of dependent action execution. For  myself, at least I&#8217;ve found some nice solution for UI event reaction  depending on the source of the trigger of the event and for infinite event loops, without relying on  ugly boolean flags or event attach/detach.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d968" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A common UI problem</title>
		<link>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem</link>
		<comments>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem#comments</comments>
		<pubDate>Tue, 03 Aug 2010 12:50:43 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[boolean flags]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[UI problem]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=963</guid>
		<description><![CDATA[This blog post is all about a common UI-related programming problem. Ever since my first UI-based application I&#8217;ve come across with this problem and never found a satisfying way to resolve it (until now ). This first blog post is about describing the problem and my former solution approaches. In the next blog post I [...]]]></description>
			<content:encoded><![CDATA[<p>This blog post is all about a common UI-related programming problem.  Ever since my first UI-based application I&#8217;ve come across with this  problem and never found a satisfying way to resolve it (until now <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ). This first blog post is about describing the problem and my former solution approaches. In <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">the next blog post</a> I will demonstrate a more proper solution.</p>
<p>The code in these two blog posts is using WinForms  and C#, but it should be easy adoptable to other UI technologies as  well.</p>
<h3>Problem description</h3>
<p>It&#8217;s a common problem: you  want to react on an event like the <code>TextChanged</code> event on a <code>TextBox</code>, but <strong> <em>ONLY</em> if the user changed</strong> the text and it&#8217;s not changed programmatically. For example you want to update some data, when the user changes the content of a <code>TextBox</code>, but this update process should not be triggered when the progam itself sets some data and therefore updates the text. The  starting point for that could be something like the following code:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.Text = value.SomeValue;
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}</pre>
<p>Here the <code>OnSomeTextBoxTextChanged()</code> method is bound to the <code>_someTextBox.TextChanged</code> event. <code>ViewData</code> is a class with arbitrary data that should show up in the UI.<br />
<strong>Notice the problem</strong>: when the <code>ViewData</code> property is set programmatically the <code>OnSomeTextBoxTextChanged()</code> method is being executed, which is not what was intended (firing the event only when the user changes the value of the <code>TextBox</code>).</p>
<p>A similar problem arises with <strong>infinite loops</strong>. Imagine a user changes something in the UI and an event <code>X</code> is fired. You hook this event and start a complex UI workflow, which at the end fires the event <code>X</code> again. The proces is executed again and very easy you come into an infinite loop situation. If you are an UI developer you would very probably agree that UI event chains are often opaque and can get messy.</p>
<p>Let&#8217;s look at some obvious, however not very elegant, solutions.</p>
<h3>Approach #1: Temporary event detach</h3>
<p>One of those simple solution is the <strong>temporary detachment</strong> of the problematic event. For example if you don&#8217;t want to react on the <code>TextChanged</code> event when the <code>TextBox.Text</code> property is set programmatically, you could detach your event handler from <code>TextChanged</code> before setting the <code>Text</code> and afterwards attach it again. This approach is shown in the following  example code:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.TextChanged -= OnSomeTextBoxTextChanged;
                _someTextBox.Text = value.SomeValue;
                _someTextBox.TextChanged += OnSomeTextBoxTextChanged;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}</pre>
<p>While this is working, it&#8217;s not a recommendable solution, because there are <strong>several shortcomings</strong>. First the manual event handling is not very intuitive and <em>doesn&#8217;t explicitly reveal the intent</em> of the programmer with this manual process. Thus your code is more difficult to read for others (and after some months for you as well). Moreover, you get <em>undefined states</em> when exceptions are thrown and caught in an outer component (and you miss a <code>finally</code> which attaches the event again). Then the event handler could be detached further on and the UI isn&#8217;t working properly afterwards. The whole event detach/attach process is getting very messy if you have <em>complex views</em> with many such problematic events. Last but not least this manual event handling process <em>binds your code tightly</em> to the view and you get trouble if you want to refactor several parts out.</p>
<h3>Approach #2: Boolean flags</h3>
<p>A similarly simple approach comes with <em>boolean flags</em> which indicate that a value is currently set  programmatically and thus that <em>Changed</em> events should not be handled. The following code shows an example how this could solve our initial problem:</p>
<pre class="brush:csharp">public partial class SomeControl : UserControl
{
    // ...

    private bool _isTextSetByProgram = false;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _isTextSetByProgram = true;
                _someTextBox.Text = value.SomeValue;
                _isTextSetByProgram = false;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        if (!_isTextSetByProgram)
        {
            // perform data/view update operations
        }
    }
}</pre>
<p>I think this is the <strong>most common solution</strong> that I&#8217;ve seen for the problem. For myself I must admit that I&#8217;ve mostly used this approach. But it has the <strong>same disadvantages</strong> like the event detach/attach solution (except the tight view coupling). Boolean variables don&#8217;t explicitly show the intent behind them and get likewise messy if used in complex situations where you could have dozens of those variables scattered around a view.</p>
<p>So while those solutions are very widespread and work they <strong>just don&#8217;t feel <em>right</em> and clean</strong>. But what&#8217;s the alternative? An interesting little one I will show you in <a href="http://www.minddriven.de/index.php/technology/development/design-patterns/latch-design-pattern">the next post</a> which comes shortly.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d963" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/design-patterns/common-ui-problem/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Some thoughts on Event-Based Components</title>
		<link>http://www.minddriven.de/index.php/technology/development/event-based-components</link>
		<comments>http://www.minddriven.de/index.php/technology/development/event-based-components#comments</comments>
		<pubDate>Fri, 09 Jul 2010 17:20:09 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[event-based programming]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[interfaces]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=886</guid>
		<description><![CDATA[The German software engineer Ralf Westphal currently spreads some knowledge about an alternative model for programming components and especially communication between them. Due to their nature they are called Event-Based Components. After some discussion with colleagues at SDX I want to share some of my thoughts on that with you (of course for further discussion [...]]]></description>
			<content:encoded><![CDATA[<p>The German software engineer <a href="http://ralfw.de/">Ralf Westphal</a> currently spreads some knowledge about an alternative model for programming components and especially communication between them. Due to their nature they are called <strong>Event-Based Components</strong>. After some discussion with colleagues at <a href="http://www.sdx-ag.de">SDX</a> I want to share some of my thoughts on that with you (of course for further discussion as well).<br />
The aim of Event-Based Components (EBC) is to create software components that are <em>really</em> composable without specific topological dependencies. You can compare EBCs with elements in electronic circuits. But first things first&#8230;</p>
<h3>Interface-Based Components style</h3>
<p>Normally we&#8217;re developing components in .NET as IBCs: <strong>Interface-Based Components</strong>. That means client classes have topological and functional dependencies to interfaces (or directly to other classes), which provide some sort of functionality. Well developed, such a dependency could be resolved with a Dependency Injection container like StructureMap:</p>
<pre class="brush:csharp">class Program
{
    static void Main(string[] args)
    {
        // Bind (here: StructureMap)
        ObjectFactory.Initialize(x =&gt;
        {
            x.For&lt;IBusinessClient&gt;().Use&lt;BusinessClient&gt;();
            x.For&lt;IDataAccessComponent&gt;().Use&lt;DataAccessComponent&gt;();
        });

        // Resolve and Run
        IBusinessClient client = ObjectFactory.GetInstance&lt;IBusinessClient&gt;();
        client.BusinessOperation(0);
    }
}

interface IBusinessClient
{
    void BusinessOperation(int personId);
}

class BusinessClient : IBusinessClient
{
    private readonly IDataAccessComponent _dataAccessComponent;

    public BusinessClient(IDataAccessComponent dataAccessComponent)
    {
        _dataAccessComponent = dataAccessComponent;
    }

    public void BusinessOperation(int personId)
    {
        Person p = _dataAccessComponent.GetPerson(personId);
        // do something ...
    }
}

interface IDataAccessComponent
{
    Person GetPerson(int id);
}

class DataAccessComponent : IDataAccessComponent
{
    public Person GetPerson(int id)
    {
        return  // ...some person...
    }
}</pre>
<p>That&#8217;s pretty standard so far, isn&#8217;t it? In Ralf&#8217;s opinion this programming style lacks real <em>composability</em> of the components. Due to the <strong>topological dependency</strong> the clients is bound to a specific interface and no <em>arbitrary</em> component can perform the functionality. Instead a component has to implement the specific interface. You&#8217;re not able to use components which <em>could</em> provide the functionality, but don&#8217;t implement the interface&#8230;</p>
<h3>Event-Based Components style</h3>
<p>Ralf suggests <strong>Event-Based Components</strong> to the rescue. Components in this programming style can be compared to components in electronic circuits. Methods act as <em>input pins</em> of a component and can be called by other components. Events/delegates act as <em>output pins</em> and establish a connection to other components that should be used by the component or to provide calculation results. The output pins can be bound to any arbitrary method that meet the signature. Thus the dependency is still functional, but <em>not topological</em> any more.<br />
The example above in EBC style could look as follows:</p>
<pre class="brush:csharp">class Program
{
    static void Main(string[] args)
    {
        // Build
        var client = new BusinessClient();
        var dataAccess = new DataAccessComponent();

        // Bind
        client.GetPerson = dataAccess.GetPerson;

        // Run
        client.BusinessOperation(0);
    }
}

class BusinessClient
{
    public Func&lt;int, Person&gt; GetPerson { get; set; }

    public void BusinessOperation(int personId)
    {
        Person p = GetPerson(personId);
        // do something ...
    }
}

class DataAccessComponent
{
    public Person GetPerson(int id)
    {
        return  // ... some person ...
    }
}</pre>
<p>This example shows the components <code>BusinessClient</code> and <code>DataAccessComponent</code> interacting as EBCs in a very simple form by using the <code>Func&lt;T&gt;</code> delegate type and thus enabling <em>symmetric</em> communication. Ralf encourages the use of standard input/output pins as <code>Action&lt;object&gt;</code>, which leads to <em>asymmetric</em> communication, because the <code>DataAccessComponent</code> would need to declare an output pin for providing the <code>Person</code> as result of <code>GetPerson()</code>. For the sake of simplicity I haven&#8217;t followed this principle here.</p>
<p>So the example uses a <code>Func&lt;T&gt;</code> delegate and no event. But you can still think of it as Event-Based Component, just because events are nothing more than multicast delegates. I could have used events instead of the simple delegate as well, but I&#8217;m quite fine, because I don&#8217;t need the functionality of multiple subscribers here.</p>
<p>As you can see from the example, just like IBCs the EBCs have some kind of initial <em>Bootstrapper</em> phase. This is the time when the components are composed. The output pins of a component&#8217;s client (<code>BusinessClient</code> in this example) are connected with the input pins of the component itself (here: <code>DataAccessComponent</code>).</p>
<h3>Benefits</h3>
<p>When I first saw EBCs I thought: &#8220;Dude, this is damn cool, isn&#8217;t it?&#8221;. Indeed this kind of programming style first feels strange and alternate and thus for me it&#8217;s really interesting. But are there some <em>real</em> benefits as well?</p>
<p>I think one big benefit of EBCs is their <strong>composability</strong>. A client hasn&#8217;t to know the interface of a component from which he wants to use some functionality. A component on the other side is not forced to implement an interface to provide some functionality, but it&#8217;s still retaining loose coupling. Even without interfaces the components are still independent from each other and have great <strong>testability</strong>.</p>
<p>Other benefits I see are the <strong>exchangeability</strong> and the <strong>topological independence</strong>. Components are not bound to a specific topological context in form of interfaces and thus are independent from topological changes on the interfaces. You can exchange the components easily by replacing the binding section with any other setup phase and can binding other methods to them. Especially your components are not forced to use (or implement) some kind of interface from which they will perhaps use just one single functionality&#8230;</p>
<p>Last but not least I see a very easy way to <strong>intercept calls</strong> and adding functionality without changing the components themselves. If you use events as output pins you can add some more event handlers in the binding phase. Thus you can easily integrate Logging, Tracing etc. into your applications. Of course you can achieve this with IBCs as well, I just say that EBCs are suiting very well for those requirements.</p>
<h3>Drawbacks</h3>
<p>Besides those benefits in my opinion there are some significant drawbacks as well.</p>
<p>First of all is the additional <strong>complexity</strong> which comes with EBCs. <strong>Composing</strong> EBCs can become complex, at least in projects of significant size. Due to binding methods and events together on the fine instead of interfaces on the coarse, there have to be much more binding statements. In fact you can think of an event&#8217;s signature as a <em>one-method interface</em> that has to be fulfilled from components. Furthermore (again especially in projects of a reasonable size) you will loose <strong>intelligibility</strong> and  <strong>overview</strong> over your system and the component interaction. Any arbitrary component can provide a functionality and there is no way to navigate between layers and components as clients and suppliers of functionality. Explicit interfaces are much more comprehensive than such &#8220;implicit&#8221; specifications.  Perhaps in the future there will be tools that simplify composition between EBCs and navigation through EBCs, but until there&#8217;s such a tool I consider this as serious drawback.</p>
<p>Another drawback of EBCs is the loss of <strong>interfaces as formal contract</strong> of coherent functionality. Of course you can define interfaces and let your components implement them, but while clients are not compelled to use them they loose much of their value. Interfaces force components to implement a certain set of functionality completely and make this set explicit. Clients have to refer this contract explicitly. Explicit contracts lead to <a href="http://domaindrivendesign.org/node/113">intention revealing</a> and this is a good thing!</p>
<h3>Conclusion</h3>
<p>So in my opinion EBCs have benefits as well as shortcomings. I think they are worth investigating and knowing them, but at the moment I don&#8217;t see that they will establish well and become a replacement for IBCs. First there is the higher complexity, which could perhaps be solved by tools and some sort of &#8220;DI container&#8221; for EBCs in the future. But second, being explicit and define formal contracts through explicit interfaces is no bad thing. Of course it&#8217;s not cheap as well, but I don&#8217;t see that this justifies the application of EBCs on the small scale. On the big scale there are other solutions like BizTalk, NServiceBus etc. to achieve the goal of pluggable components which have features like scalability as well. So perhaps there are delimited scenarios for using EBCs (like component topologies that change often), but I would not suggest to use them in general.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d886"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d886" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/development/event-based-components/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Thanks Microsoft!</title>
		<link>http://www.minddriven.de/index.php/technology/visual-studio/microsoft-visual-studio-2010-gift</link>
		<comments>http://www.minddriven.de/index.php/technology/visual-studio/microsoft-visual-studio-2010-gift#comments</comments>
		<pubDate>Fri, 25 Jun 2010 16:50:52 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Code Contracts]]></category>
		<category><![CDATA[gift]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=874</guid>
		<description><![CDATA[Hey guys. Wow, one month has elapsed without any blog post here. Sorry for that&#8230; At the moment I&#8217;m really busy with some private, but also technical/conceptual topics. So here comes just a short sign of life But stay tuned for more blog posts in some weeks&#8230; Today I was really surprised when FedEx delivered [...]]]></description>
			<content:encoded><![CDATA[<p>Hey guys. Wow, one month has elapsed without any blog post here. Sorry for that&#8230; At the moment I&#8217;m really busy with some private, but also technical/conceptual topics. So here comes just a short sign of life <img src='http://www.minddriven.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  But stay tuned for more blog posts in some weeks&#8230;</p>
<p>Today I was really surprised when FedEx delivered a package from Microsoft (by air freight) to me. Inside was a <strong>Visual Studio 2010</strong> surprise gift: A laser-engraved cube from the VS2010/.NET4-team with a nice statement from Soma. He and Microsoft say &#8220;Thank you&#8221; (me), so it&#8217;s time for me to say: Thank you for that surprise as well!</p>
<p><a href="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4795.jpg"><img class="alignnone size-medium wp-image-875" title="Microsoft Thank You gift box" src="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4795-300x199.jpg" alt="Microsoft Thank You gift box" width="300" height="199" /></a> <a href="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4796.jpg"><img class="alignnone size-medium wp-image-876" title="Microsoft Thank You gift" src="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4796-300x199.jpg" alt="Microsoft Thank You gift" width="300" height="199" /></a> <a href="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4797.jpg"><img class="alignnone size-medium wp-image-877" title="Somasegar's Thank You text" src="http://www.minddriven.de/wp-content/uploads/2010/06/IMG_4797-300x278.jpg" alt="Somasegar's Thank You text" width="215" height="199" /></a></p>
<p>I don&#8217;t exactly know why I got this present but I think it&#8217;s because of my engagement and direct contact to the <a href="http://www.minddriven.de/index.php/category/technology/dot-net/code-contracts">Code Contracts</a> team in 2009. Thanks guys! I hope to see this technology improving further and becoming a first-level feature of Visual Studio (the tools!), .NET and perhaps C# as well. And I hope to give more support to evolving Microsoft technologies. There are some inspiring movements and a lot of innovation at the moment, which are really encouraging me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/visual-studio/microsoft-visual-studio-2010-gift/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Contracts Survey</title>
		<link>http://www.minddriven.de/index.php/technology/dot-net/code-contracts/code-contracts-survey</link>
		<comments>http://www.minddriven.de/index.php/technology/dot-net/code-contracts/code-contracts-survey#comments</comments>
		<pubDate>Tue, 25 May 2010 09:06:42 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[Code Contracts]]></category>
		<category><![CDATA[Code Contracts tools]]></category>
		<category><![CDATA[survey]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=854</guid>
		<description><![CDATA[Some days ago I took deeper insights into Code Contracts, which are included in .NET 4.0. Microsoft currently takes a survey on Code Contracts and the Code Contracts tools. Give them feedback to support improvement of Code Contracts. You can find the survey here: http://codecontracts.questionpro.com]]></description>
			<content:encoded><![CDATA[<p>Some days ago I took deeper insights into Code Contracts, which are included in .NET 4.0.<br />
Microsoft currently takes a <a href="http://codecontracts.questionpro.com/">survey</a> on Code Contracts and the Code Contracts tools. Give them feedback to support improvement of Code Contracts.</p>
<p>You can find the survey here: <a href="http://codecontracts.questionpro.com/">http://codecontracts.questionpro.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/dot-net/code-contracts/code-contracts-survey/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Quick Tip: Check Data Annotations from code</title>
		<link>http://www.minddriven.de/index.php/technology/dot-net/web/asp-net-mvc/check-data-annotations-from-code</link>
		<comments>http://www.minddriven.de/index.php/technology/dot-net/web/asp-net-mvc/check-data-annotations-from-code#comments</comments>
		<pubDate>Sun, 02 May 2010 17:36:04 +0000</pubDate>
		<dc:creator>Matthias Jauernig</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[actionfilterattribute]]></category>
		<category><![CDATA[ASP.NET Dynamic Data]]></category>
		<category><![CDATA[custom validation]]></category>
		<category><![CDATA[data annotations]]></category>
		<category><![CDATA[data annotations model binder]]></category>
		<category><![CDATA[model]]></category>
		<category><![CDATA[model binding]]></category>
		<category><![CDATA[model metadata]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[validation from code]]></category>

		<guid isPermaLink="false">http://www.minddriven.de/?p=841</guid>
		<description><![CDATA[During the last weeks I got some insights on ASP.NET MVC 2. Personally I like the programming model of MVC in contrast to WebForms, although the productivity first seems to be lower in common data-driven scenarios. One of the most advertised features of MVC 2 is the support of Data Annotations for adding validators and [...]]]></description>
			<content:encoded><![CDATA[<p>During the last weeks I got some insights on <a href="http://www.asp.net/MVC/"><strong>ASP.NET MVC 2</strong></a>. Personally <a href="http://www.minddriven.de/?p=217">I like the programming model</a> of MVC in contrast to WebForms, although the productivity first seems to be lower in common data-driven scenarios. One of the most advertised features of MVC 2 is the support of <strong>Data Annotations</strong> for adding validators and further information right to your model via attributes. <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx">Data Annotations</a> have their origins in <a href="http://www.asp.net/dynamicdata/">ASP.NET Dynamic Data</a> and are defined in the <code>System.ComponentModel.DataAnnotations</code> namespace that ships with .NET 4.0. Microsoft is promoting Data Annotations even further and beside MVC and Dynamic Data they can be used in Silverlight, too.</p>
<p>Data Annotations offer many capabilities for <strong>model validation</strong> to your application. There are <em>predefined</em> validators for common constraints: <code>RangeAttribute</code>, <code>RegularExpressionAttribute</code>, <code>RequiredAttribute</code> and <code>StringLengthAttribute</code>. Those attributes can be automatically checked on the client-side (via Javascript) as well. Furthermore there is a <code>CustomValidationAttribute</code> which allows you to define custom validation logic. Personally I feel a bit <em>ambivalent</em> on Data Annotations. Beside of validation logic you are able to define <em>UI-relevant information</em> on your model which I can&#8217;t encourage if done on the core domain model. On the other side you are able to extend your model with Data Annotations on the UI layer&#8230; But I don&#8217;t want to discuss the usage of Data Annotations here. There are scenarios where they are a perfect match and there are other cases where you want to do validation on your own&#8230;</p>
<h3>Simple example</h3>
<p>If you use Data Annotations for <strong>validation</strong> you get great <strong>tool support</strong> in ASP.NET MVC 2 and other UI technologies. Imagine the following model class <code>Product</code>:</p>
<pre class="brush:csharp">public class Product
{
    [Required(ErrorMessage="ProductID is a required field")]
    public int ProductID { get; set; }

    [Required(ErrorMessage = "ProductName is a required field")]
    [StringLength(40, ErrorMessage = "ProductName can only contain up to 40 characters")]
    public string ProductName { get; set; }

    [StringLength(20, ErrorMessage = "QuantityPerUnit can only contain up to 20 characters")]
    public string QuantityPerUnit { get; set; }

    [Range(0, (double)decimal.MaxValue, ErrorMessage = "UnitPrice must be a valid positive currency")]
    public decimal? UnitPrice { get; set; }
}</pre>
<p>Entities of this model class should be editable through the following strongly-typed view <code>Edit.aspx</code>:</p>
<pre class="brush:xhtml">&lt;%@ Page Title="Edit Product" Language="C#"  Inherits="System.Web.Mvc.ViewPage&lt;Product&gt;" %&gt;

&lt;h2&gt;Edit Product&lt;/h2&gt;

&lt;% using (Html.BeginForm()) {%&gt;
&lt;%: Html.ValidationSummary(true) %&gt;

&lt;fieldset style="padding:10px;"&gt;
&lt;legend&gt;Product Fields model.ProductName) %&gt;
&lt;/div&gt;
&lt;div class="editor-field"&gt;
    &lt;%: Html.TextBoxFor(model =&gt; model.ProductName) %&gt;
    &lt;%: Html.ValidationMessageFor(model =&gt; model.ProductName) %&gt;
&lt;/div&gt;

&lt;div class="editor-label" style="margin-top:10px;"&gt;
    &lt;%: Html.LabelFor(model =&gt; model.QuantityPerUnit) %&gt;
&lt;/div&gt;
&lt;div class="editor-field"&gt;
    &lt;%: Html.TextBoxFor(model =&gt; model.QuantityPerUnit) %&gt;
    &lt;%: Html.ValidationMessageFor(model =&gt; model.QuantityPerUnit) %&gt;
&lt;/div&gt;

&lt;div class="editor-label" style="margin-top:10px;"&gt;
    &lt;%: Html.LabelFor(model =&gt; model.UnitPrice) %&gt;
&lt;/div&gt;
&lt;div class="editor-field"&gt;
    &lt;%: Html.TextBoxFor(model =&gt; model.UnitPrice, String.Format("{0:F}", Model.UnitPrice)) %&gt;
    &lt;%: Html.ValidationMessageFor(model =&gt; model.UnitPrice) %&gt;
&lt;/div&gt;

&lt;p style="margin-top:10px;"&gt;
    &lt;input type="submit" value="Save" /&gt;
&lt;/p&gt;
&lt;/fieldset&gt;
&lt;% } %&gt;</pre>
<p>When <strong>posting the form</strong> in this view the following action <code>Edit()</code> on the <code>ProductController</code> is invoked:</p>
<pre class="brush:csharp">[HttpPost]
public ActionResult Edit(Products product)
{
    if (!ModelState.IsValid)
        return View(product);

    // ...
}</pre>
<p>And here&#8217;s where magic comes into play. When posting the form the Data Annotations on the <code>Product</code> class are <strong>checked automatically</strong>. If there are any validation errors <code>ModelState.IsValid</code> is set to <code>false</code> and <code>ModelState</code> itself will contain the error messages. Those error messages automatically are displayed in the UI through the <code>Html.ValidationMessageFor()</code> helpers as shown below:<br />
<img class="size-full wp-image-843 alignnone" style="margin: 10px;" title="ASP.NET MVC 2 - Validation with Data Annotations" src="http://www.minddriven.de/wp-content/uploads/2010/05/MVC_ProductValidation.png" alt="ASP.NET MVC 2 - Validation with Data Annotations" width="537" height="282" /></p>
<h3>Everything&#8217;s fine?</h3>
<p>Now you could think that everything&#8217;s fine with this solution, right? But that&#8217;s not the case! Data Annotations have an important and not very obvious <strong>shortcoming</strong> which can lead to serious data consistency problems. The problem: Data Annotations are checked during the model binding phase based on the posted form values <strong>and not on the bound model entity</strong>. That means only the Data Annotations on the posted form values are checked, but not other properties which are perhaps defined on the model class, but missing in the form values. Imagine for example some bad guy who visits your page and edits a Product. Before posting the form he <strong>manipulates</strong> the DOM of the page and removes some form values. Those values will not be checked on server-side and thus the (invalid) <code>Product</code> will be saved to the DB or some operations will be done on it. Got the point?</p>
<p>So what can we do? We can <strong>manually check</strong> the defined validation Data Annotations in our controller action on the model class <em>after</em> the model binding procedure. Therefore we can for example develop a <strong>custom action filter attribute</strong> (inspired from <a href="http://stackoverflow.com/questions/1142083/best-practice-entity-validation-in-asp-net-mvc-ado-net-entity-framework">here</a>):</p>
<pre class="brush:csharp">public class ModelValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // get the controller for access to the ModelState dictionary
        var controller = filterContext.Controller as Controller;
        if(controller != null)
        {
            var modelState = controller.ModelState;

            // get entities that could have validation attributes
            foreach (var entity in filterContext.ActionParameters.Values.Where(o =&gt; o != null))
            {
                // get metadata attribute
                MetadataTypeAttribute metadataTypeAttribute =
                    entity.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true)
                        .FirstOrDefault() as MetadataTypeAttribute;

                Type attributedType = (metadataTypeAttribute != null)
                    ? metadataTypeAttribute.MetadataClassType
                    : entity.GetType();

                // get all properties of entity class and possibly defined metadata class
                var attributedTypeProperties = TypeDescriptor.GetProperties(attributedType)
                    .Cast&lt;PropertyDescriptor&gt;();
                var entityProperties = TypeDescriptor.GetProperties(entity.GetType())
                    .Cast&lt;PropertyDescriptor&gt;();

                // get errors from all validation attributes of entity and metadata class
                var errors = from attributedTypeProperty in attributedTypeProperties
                             join entityProperty in entityProperties
                             on attributedTypeProperty.Name equals entityProperty.Name
                             from attribute in attributedTypeProperty.Attributes.OfType&lt;ValidationAttribute&gt;()
                             where !attribute.IsValid(entityProperty.GetValue(entity))
                             select new KeyValuePair&lt;string, string&gt;(attributedTypeProperty.Name,
                                 attribute.FormatErrorMessage(string.Empty));

                // add errors to ModelState dictionary
                foreach (var error in errors)
                    if (!modelState.ContainsKey(error.Key))
                        modelState.AddModelError(error.Key, error.Value);
            }
        }

        base.OnActionExecuting(filterContext);
    }
}</pre>
<p>This attribute takes all validation attributes into account which are defined on the <strong>model class</strong> itself or on an associated <strong>metadata class</strong>. The attribute adds all validation errors to the <code>ModelState</code> dictionary of the controller which have not been added before and which are defined in the ErrorMessage or the Error Resource of the validation attribute. Note that your controller has to derive from the <code>Controller</code> class and not from <code>ControllerBase</code>, but that&#8217;s the default setting and should not be a problem.</p>
<p>Now we only have to <strong>add this attribute to our controller action</strong> and validation will be done on the bound model class:</p>
<pre class="brush:csharp">[HttpPost]
[ModelValidation]
public ActionResult EditProduct(Products product)
{
    if (!ModelState.IsValid)
        return View(product);

    // ...
}</pre>
<h3>Conclusion</h3>
<p>This post has shown how you can check defined validation Data Annotations from your code and why it&#8217;s important in ASP.NET MVC 2 to do so. Of course you don&#8217;t have to define a custom action filter attribute for this task and can do this task by a custom validation helper in your business logic if you like. Once again this story told me one thing: <strong>don&#8217;t rely</strong> on technical solutions and question their background behavior all the time&#8230;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d841"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d841" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.minddriven.de/index.php/technology/dot-net/web/asp-net-mvc/check-data-annotations-from-code/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
