<?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>Dude, where is my Kaizen? &#187; Testing</title>
	<atom:link href="http://www.bjoernrochel.de/category/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bjoernrochel.de</link>
	<description>Björn Rochel&#039;s weblog</description>
	<lastBuildDate>Mon, 21 Jun 2010 07:26:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Testing F# code with xUnit.net (on .NET 4.0)</title>
		<link>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/</link>
		<comments>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 07:48:46 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[xUnit]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=784</guid>
		<description><![CDATA[A lot of my free time currently goes into learning F#. While I had a great time playing around with the F# REPL FSI, I came to the conclusion that using FSI is not my preferred way of a) learning the F# language and b) to develop code. Writing unit tests simply for the purpose [...]]]></description>
			<content:encoded><![CDATA[<p>A lot of my free time currently goes into learning F#. While I had a great time playing around with the F# REPL FSI, I came to the conclusion that using FSI is not my preferred way of a) learning the F# language and b) to develop code. Writing unit tests simply for the purpose of learning and understanding of a language/component/system (aka &quot;Learning tests&quot;) seems to be a better fit, at least for me. So, I sat down in order to see how I can use my beloved xUnit.net for this. As it turns out it&#8217;s not that difficult, but it&#8217;s got some hurdles. </p>
<p><strong>Possible runtime differences</strong> </p>
<p>xUnit.net 1.5 is compiled against the .Net Framework 3.5. If you&#8217;re using F# in combination with the VS2010 RC or RTM (like I do) you&#8217;ve got at least to options to make them work together. </p>
<ol>
<li>Use multi-targeting&#160; and configure the F# projects to compile for the .NET 3.5 runtime (Properties/Application/Target Framework). </li>
<li>Update the app.config files of xunit.console.exe and xunit.gui.exe with a startup section and specify the .NET framework 4.0 version as supported.
<pre class="brush: xml">

     &lt;startup&gt;
    	&lt;supportedRuntime version=&quot;v4.0.30128&quot; safemode=&quot;true&quot;/&gt; &lt;!-- VS2010 RC --&gt;
    	&lt;supportedRuntime version=&quot;v4.0.30319&quot; safemode=&quot;true&quot;/&gt; &lt;!-- VS2010 RTM --&gt;
     &lt;/startup&gt;
</pre>
</li>
</ol>
<p><strong>Pay attention to your parentheses</strong> </p>
<p>My choice was to update the xUnit.net configurations. After the update of the configuration files my assembly was loaded, however the test runner failed to detect my unit tests. As it turns out the open parentheses after a test function play an important role.</p>
<p><pre class="brush: csharp">
     [&lt;Fact&gt;]
     let After_converting_a_valid_data_row_the_title_should_have_been_extracted = //This compiles, but the test doesn&#039;t show up in the test runner.
        let row = convertDataRow &quot;Test, 1234&quot;
        Assert.Equal(fst(row), &quot;Test&quot;)

     [&lt;Fact&gt;]
     let After_converting_a_valid_data_row_the_title_should_have_been_extracted() = //This will work fine
        let row = convertDataRow &quot;Test, 1234&quot;
        Assert.Equal(fst(row), &quot;Test&quot;)
  </pre>
</p>
<p>My first reaction was: WTF? But after reading some more chapters of &quot;Real world functional programming&quot; and a discussion at our local F# book club the behavior makes sense to me. My current understanding is that omitting the parentheses results in a different method signature. You can easily spot this in FSI. The first one is <em>val After_converting_a_valid_data_row_the_title_should_have_been_extracted : unit</em> while the second one results in a <em>val After_converting_a_valid_data_row_the_title_should_have_been_extracted : unit -&gt; unit</em>. What you can see here is that the first function signature doesn&#8217;t have a parameter while the second has a parameter of the type unit. One interesting difference between F# and C# is that the F# equivalent to C#&#8217;s void is an actual type called unit. The fun part is that () is it&#8217;s only value. Parentheses play a completely different role here <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  The xUnit test runner looks for methods with one unit parameter and a return type of unit. That&#8217;s why you need the parentheses. </p>
<p><strong>Testing exceptions with xUnit.Net</strong> </p>
<p>One little subtlety I came across when testing exceptions is that you have to explicitly &quot;ignore&quot; the return value when you&#8217;re using Assert.Throws and pass in a method which doesn&#8217;t return unit. Feels a bit strange at first, but explainable. Again a signature mismatch. Assert.Throws expects a method with a unit -&gt; unit signature. You have to do this in order to please the compiler. (If there&#8217;s a better way for this, please let me know) </p>
<p><pre class="brush: csharp">
    [&lt;Fact&gt;]
    let Trying_to_convert_an_invalid_format_throws() =
        Assert.Throws(fun () -&gt; convertDataRow &quot;FuBar&quot; |&gt; ignore)
  </pre>
</p>
<p>The ignore function simply throws away any value it receives, returns a unit and makes the F# compiler happy.</p>
<p><strong>Conclusion</strong> </p>
<p>I hope you saw in this post that testing F# with xUnit.net is actually pretty easy. It&#8217;s also a wonderful case for language interop on top of the CLR. Go see it for yourself <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 11.3: Commands strike back</title>
		<link>http://www.bjoernrochel.de/2010/02/15/diving-into-the-storyteller-trunk-part-11-3-commands-strike-back/</link>
		<comments>http://www.bjoernrochel.de/2010/02/15/diving-into-the-storyteller-trunk-part-11-3-commands-strike-back/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 19:21:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=762</guid>
		<description><![CDATA[One of the things that can hit you really hard when writing blog posts about open source software (like StoryTeller is), is the fact that your posts tend to get very fast outdated, especially when you don&#8217;t pay that much attention to the detail (like I did, sigh). If you&#8217;re not aware of what I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things that can hit you really hard when writing blog posts about open source software (like StoryTeller is), is the fact that your posts tend to get very fast outdated, especially when you don&#8217;t pay that much attention to the detail (like I did, sigh). If you&#8217;re not aware of what I&#8217;m talking about, it&#8217;s StoryTellers command story. I&#8217;m not sure when it changed but it definitely has changed and I needed to update my last post (<a href="http://www.bjoernrochel.de/2010/01/09/diving-into-the-storyteller-trunk-part-11-2-more-on-commands/" target="_blank">11.2</a>) quite a bit in order to reflect the changes. Today I would like to conclude my trip through StoryTellers UI infrastructure with a look at how Commands are integrated into the Screen Activation Lifecycle.</p>
<p>Some of my older posts on the topic showed that the component responsible for Screen activation and deactivation in StoryTeller is the ScreenConductor. However, when the ScreenConductor activates or deactivates a Screen, it delegates a major part of work to the so called IShellService. The only implementer of this interface, the ShellService, is just a little facade around three things.</p>
<ol>
<li>The ICommandbar, which is the main toolbar of StoryTeller</li>
<li>the IOptionsMenu, which is a kind of Shortcut menu for StoryTellers Commands and</li>
<li>the IScreenObjectRegistry, which acts as a store  / front-end for the current Command registration.</li>
</ol>
<pre class="brush: csharp">

    public class ShellService : IShellService
    {
        private readonly ICommandBar _Commands;
        private readonly IOptionsMenu _options;
        private readonly IScreenObjectRegistry _registry;

        public ShellService(
              IScreenObjectRegistry registry,
              ICommandBar Commands,
              IOptionsMenu options)
        {
            _registry = registry;
            _Commands = Commands;
            _options = options;
        }

        #region IShellService Members

        public void ActivateScreen(IScreen screen)
        {
            _registry.ClearTransient();
            screen.Activate(_registry);
            refill();
        }

        public void ClearTransient()
        {
            _registry.ClearTransient();
            refill();
        }

        public void Start()
        {
            refill();
        }

        #endregion

        private void refill()
        {
            _Commands.Refill(_registry.Actions);
            _options.Refill(_registry.Actions);
        }
</pre>
<p>You can see some interesting aspects in the short code above.</p>
<ol>
<li>The word transient appears several times. StoryTeller differentiates between two types of Commands: Permanent Commands and transient Commands. Permanent Commands are displayed, well permanently, while transient Commands are what I depicted as contextual Commands. They are Commands which should be only visible in a particular context.
<p /></li>
<li>Contextualization of Commands is handled on a per Screen basis in StoryTeller. Every time a Screen gets activated or deactivated the ICommandBar and the IOptionsMenu get reset and completely rebuild. With this you can have a very different Command UI depending on which Screen is activated.
<p /></li>
<li>The actual Command configuration in the Screen Activation Lifecycle is completely delegated to the active Screen. In his Activate() method he receives a reference to the IScreenObjectRegistry which can be used in order to start the Command configuration via a small fluent API.
<p /></li>
</ol>
<pre class="brush: csharp">

    public interface IScreenObjectRegistry
    {
        //Gets a collection of all currently known command configurations
        IEnumerable&lt;ScreenAction&gt; Actions { get; }

        //Removes all transient command configurations from the registry
        void ClearTransient();

        //DSL starting point for the configuration of transient Commands
        IActionExpression Action(string name);

        //DSL starting point for the configuration of permanent Commands
        IActionExpression PermanentAction(string name);
    }
</pre>
<p>The following code snippet shows an example of how this API could be leveraged inside a Screen.</p>
<pre class="brush: csharp">

        public void Activate(IScreenObjectRegistry screenObjects)
        {
            screenObjects
                .Action(&quot;Save&quot;)
                .Bind(ModifierKeys.Control, Key.S)
                 .To(_save); //This can be either Systen.Action or an System.Windows.Input.ICommand

            screenObjects
                .Action(&quot;Cancel&quot;)
                .Bind(Key.Escape)
                .To(_cancel);
        }
</pre>
<p>Gabriel Schenker has <a href="http://www.lostechies.com/blogs/gabrielschenker/archive/2010/01/08/fluent-silverlight-table-of-content.aspx" target="_blank">written an excellent series on how to write such a fluent API</a>. Although it&#8217;s targeting Silverlight, most of the involved problems are explained in detail there, so forgive me if I don&#8217;t dive into the actual DSL implementation.</p>
<p><strong>Some final thoughts</strong></p>
<p>Making the Screen responsible for setting up his Commands makes a lot of sense to me, since the Screen is the unit which gets plugged into the UI infrastructure and it also very likely plays the role of the Command receiver in terms of the classic GoF pattern description. This doesn&#8217;t necessary mean that Screens are the only place for Command configuration. The initialization of modules in a Composite application is also a very likely place for registration of permanent Commands.</p>
<p>I consider having a fluent API for configuring the Commands also a plus, because it IMHO makes the actual Command configuration a lot easier and accessible. I&#8217;ve used the same setup (fluent API + delegation to screen) on my last 3 projects and it always worked for me like a charm.</p>
<p>Like I mentioned in the previous post, what I don&#8217;t like that much is the idea of mixing in visual aspects (Icon, Size, Location) into the Command configuration, mostly because I&#8217;ve been burned by this in the past when facing complex menus, like the ribbon. I think it&#8217;s a good idea to externalize the visual aspect via XML, at least for all the static stuff.</p>
<p><strong>This is it</strong></p>
<p>This was the last post about StoryTeller (at least for a while). It has been an interesting voyage which taught me a lot about UI infrastructure design, StructureMap usage and Convention over Configuration. Although it was primarily my learning excercise I hope you took something interesting with you from this blog series, too.</p>
<p>I&#8217;m going to continue my research on UI architecture with another deep dive into <a href="http://devlicio.us/blogs/rob_eisenberg/default.aspx" target="_blank">Rob Eisenbergs</a> <a href="http://www.codeplex.com/caliburn" target="_blank">Caliburn </a>soon. If your interested I would be very happy to have you with me on that trip . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2010/02/15/diving-into-the-storyteller-trunk-part-11-3-commands-strike-back/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 11.2: More on Commands</title>
		<link>http://www.bjoernrochel.de/2010/01/09/diving-into-the-storyteller-trunk-part-11-2-more-on-commands/</link>
		<comments>http://www.bjoernrochel.de/2010/01/09/diving-into-the-storyteller-trunk-part-11-2-more-on-commands/#comments</comments>
		<pubDate>Sat, 09 Jan 2010 19:38:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=737</guid>
		<description><![CDATA[!!! Updated to current StoryTeller trunk on 15.02.2010 !!!
Let’s take a look at some of the questions I left unanswered in the last post.
Is the basic GoF Command pattern sufficient for a modern composite application?
The basic GoF Command pattern has no notion of visual state of a Command, such as (Is)Enabled or (Is)Visible. Its original [...]]]></description>
			<content:encoded><![CDATA[<p><strong>!!! Updated to current StoryTeller trunk on 15.02.2010 !!!</strong></p>
<p>Let’s take a look at some of the questions I left unanswered in the last post.</p>
<p><strong>Is the basic GoF Command pattern sufficient for a modern composite application?</strong></p>
<p>The basic GoF Command pattern has no notion of visual state of a Command, such as (Is)Enabled or (Is)Visible. Its original purpose was to encapsulate an action, so that it can be passed around and executed at some later point of time. Not more, not less.</p>
<pre class="brush: csharp">
interface ICommand
{
   void Execute();
}
</pre>
<p>Obviously real world desktop apps need something a bit more sophisticated. I’ve seen several infrastructures in my (not so old) career so far (home grown as well as OS alternatives), which extended this basic idea with at least one of those properties mentioned above.</p>
<p>Take for instance the P&amp;P Composite UI Application Block (now better known as part of the Smart Client Software Factory).  CAB implements a delegate based variation on the Command pattern. The delegate represents the action which is passed around. However, this delegate is managed by the Command class which has a notion of Status.</p>
<pre class="brush: csharp">
enum CommandStatus
{
    Enabled, //visible and enabled
    Disabled, //visible and disabled
    Unavailable //invisible
}
</pre>
<p>The WPF Command infrastructure version of the Command interface is more like the original pattern and adds the Enabled Property and an EnabledChangedEvent to the interface definition.</p>
<pre class="brush: csharp">
interface ICommand
{
    void Execute();
    bool Enabled {get;}
    event EventHandler EnabledChanged;
}
</pre>
<p>To be honest the Command interface <strong>never looked like the original GoF definition in ANY APPLICATION or project I’ve worked on so far</strong>. It always had a slight modification in one or another way.</p>
<p><strong>StoryTeller’s Command interface</strong></p>
<p>StoryTeller is a WPF based application, so naturally it gets the WPF Command infrastructure out of the box. However it composes the WPF ICommand into a StoryTeller specific structure, the IScreenAction.</p>
<pre class="brush: csharp">

public interface IScreenAction
{
     bool IsPermanent { get; set; }
     InputBinding Binding { get; set; }
     string Name { get; set; }
     Icon Icon { get; set; }
     ICommand Command { get; }
     bool ShortcutOnly { get; set; }
     void BuildButton(ICommandBar bar);
}
</pre>
<p>ScreenAction extends the capabilities of the original GoF-Pattern with a lot of metadata, mostly for visual aspects (Icon, Description). If you’re wondering why he included visual aspects: That basically tries to solve a reoccurring problem in composite apps:</p>
<p>In composite applications modules are not known at compile time to the infrastructure. Neither are all their capabilities and how they might be displayed in the infrastructure shell. Because of that, the infrastructure needs a dynamic, deferred way for doing the shells visual configuration at application startup.</p>
<p>One way to implement this is to delegate the responsibility for setting this up to the modules itself. This can be done during the module load time or every time a screen is displayed. This fits very well with the idea of the Open Closed Principle, since adding new modules/screens doesn’t require any reconfiguration/recompilation of other modules or the infrastructure. This is more or less the approach that StoryTeller takes.</p>
<p><strong>Some personal thoughts on IScreenAction</strong></p>
<p>I’ve worked on three applications in the past which followed down the same road. One thing I noticed throughout those three applications is that this approach isn’t really well suited when you’ve got strict and/or complex requirements about how the UI of an application should look. Let me clarify a bit what I mean:</p>
<ul>
<li> <strong>The Ordering Problem</strong>. Even if you organize tools representing commands in a simple toolbar (as StoryTeller does) you can very easily get into situations where the product owner wants to have the tools in a very specific order which is different to module load order,  some internal event order, whatever. I’ve encountered this several times now.
<p>First time we solved this by introducing a global constant class containing tool names. Very, very bad idea, do not repeat this. This introduces a kind of hidden temporal coupling, because now modules must be loaded in a particular order (so that a tool already exists to which we can refer by name).</p>
<p>StoryTellers take on this is a bit better (but IMHO not much). The Icon class has an Integer based Order property. All tools get sorted based on this property in StoryTellers CommandBar when it’s reloaded. This is less coupled, because it eliminates the temporal aspect of the coupling, but still has coupling.</li>
<li> <strong>API bloat with visual aspects</strong>. One area where I really started to find this approach annoying is when you stop having simple toolbars and start to use more complex menu types like for instance the Ribbon.  Taking the ribbon as an example: Now don’t have simply an ordering problem, but at minimum an icon problem (Normal icon vs. Quick Access Toolbar), a size problem (Displayed large or small) and a positioning problem (/Tab/Group/ElementGroup vs. /ApplicationMenu/Left).
<p>We added all those stuff to our Command registration and guess what, we weren’t happy with that. We created a monster API actually doing very little.</li>
</ul>
<p>So what do I (currently) prefer? Our current project (also using the Ribbon) completely strips the visual aspect of the Command. Our Command API looks very much like the WPF one, with the only addition of an Id property. The whole visual aspect is configured using an XML file which is loaded at application startup.</p>
<pre class="brush: xml">
&lt;Ribbon&gt;
   &lt;Tab&gt;
      &lt;Group&gt;
         &lt;Button imageId=”CancelIcon“ commandId=”CommandXYZ” /&gt;
      &lt;/Group&gt;
   &lt;/Tab&gt;
&lt;/Ribbon&gt;
</pre>
<p>I think you get the point. It works very well for our scope. (Slight warning though: This solution might not be the best in case you need to represent menu state based on dynamically loaded data).</p>
<p>See you next time for: Commands strike back <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2010/01/09/diving-into-the-storyteller-trunk-part-11-2-more-on-commands/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 11.1: Commands</title>
		<link>http://www.bjoernrochel.de/2009/12/23/diving-into-the-storyteller-trunk-part-111-commands/</link>
		<comments>http://www.bjoernrochel.de/2009/12/23/diving-into-the-storyteller-trunk-part-111-commands/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 18:16:13 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=651</guid>
		<description><![CDATA[Welcome back to the &#8220;Diving into the StoryTeller trunk&#8221; series. The main topic for the last couple of posts about StoryTeller is its Command handling or to be a bit more specific the reoccurring problem of how Screen related Commands are managed in the app infrastructure. Couple of posts? Yeah, right. Today&#8217;s post is going [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome back to the &#8220;Diving into the StoryTeller trunk&#8221; series. The main topic for the last couple of posts about StoryTeller is its Command handling or to be a bit more specific the reoccurring problem of how Screen related Commands are managed in the app infrastructure. Couple of posts? Yeah, right. Today&#8217;s post is going to be a bit shorter than the usual posts in the series. When I started to write this post I quickly realized that this topic contains more aspects to talk about than I had originally anticipated. Besides that Christmas is near, I&#8217;m running out of time for this year and just wanted to get at least some bits of the content out there before going on vacation. Today&#8217;s post is going to be more general one on the topic.</p>
<p><strong>The Command Pattern</strong></p>
<p>A lot of the content in this series dealt exclusively with how the StoryTeller UI layer manages Screens in its content area, but as you know most of the time an application consists of more parts than just the plain content area. A typical desktop application is probably going to have some sort of Mainmenu, a Statusbar and of course Contextmenus. Items displayed in those areas very often represent actions an application can perform. They act as a trigger of those actions.</p>
<p>A typical way to implement this is using the <a href="http://en.wikipedia.org/wiki/Command_pattern" target="_blank">GoF-Command Pattern</a>, which separates the invoker of an action (for instance a button) from the receiver instance which executes the action by introducing the Command abstraction. A Command encapsulates the knowledge needed for an invokation of the receiver instance, so that it can be executed at a later time.</p>
<p><strong>Commands are potentially contextual</strong></p>
<p>An application can have lots and lots of Commands. While some of these Commands are available all of the time, some of them can only be executed in a particular context. A typical example for Commands of the first category might be the &#8220;Exit application&#8221; Command. A typical example for the latter category might be the &#8220;Undo&#8221; Command or &#8220;Redo&#8221; Command in all kinds of text editors, which can only be executed when the currently viewed document has some changes. It&#8217;s not uncommon to have lots of contextual Commands in an application that are only related to a very specific Screen or Screen state.</p>
<p>When we think in terms of usability, the least a user should be able to take granted from an app is that the app appropriately shows which actions can be performed at a particular point of time. This can be achieved by enabling / disabling related items depending on the availability of the Command (be it manually or through databinding). Sometimes though,it might be a better approach to have an even more contextualized UI that only shows the commands related to the current context. So for instance if no code editor view is shown in Visual Studio than the &#8220;Undo&#8221; and &#8220;Redo&#8221; Commands should also not be visible (NOTE: VS doesn&#8217;t actually behave that way). I think this idea of contextualized UIs becomes more and more popular. Office 2007/2010 was build with this idea in mind.</p>
<p><strong>Commands in a Composite UI</strong></p>
<p>Composite UIs which follow the Open / Closed Principle add another problem to the mix. When new modules or new screens are loaded into a composite app, they shouldn&#8217;t need to modify the app infrastructure in order to add their related commands. The app infrastructure needs to provide a way to plug those commands in without modification. This also includes their visual representation (Text, Tooltip, Icon, etc.).</p>
<p><strong>Questions we should take a closer look at</strong></p>
<ul>
<li>Do we need to differentiate between types of Commands?</li>
<li>Who is responsible for adding / registering commands?</li>
<li>How is the visual representation of commands configured?</li>
<li>Who is responsible for deciding whether Commands are available?</li>
<li>Is there build-in .NET Framework support for this?</li>
<li><strong>Of course: How does StoryTeller implement all this?</strong></li>
</ul>
<p>I&#8217;m afraid that&#8217;s all for today. I wish you all merry Christmas and a happy new year.</p>
<p>See you in 2010</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/12/23/diving-into-the-storyteller-trunk-part-111-commands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 10: Coordination Baby!</title>
		<link>http://www.bjoernrochel.de/2009/11/30/diving-into-the-storyteller-trunk-part-10-coordination-baby/</link>
		<comments>http://www.bjoernrochel.de/2009/11/30/diving-into-the-storyteller-trunk-part-10-coordination-baby/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 08:13:22 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[CompositeApps]]></category>
		<category><![CDATA[StoryTeller]]></category>
		<category><![CDATA[Composite Apps]]></category>
		<category><![CDATA[Design]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=619</guid>
		<description><![CDATA[So far in this series I&#8217;ve talked extensively about what I consider the most of the important parts in the StoryTeller UI design. This includes Screens, the ScreenCollection, ScreenSubject, ScreenFactory, EventAggregation and the application of Convention of Configuration in general.
You could say that we mostly talked about ingredients. Today I would like to take some [...]]]></description>
			<content:encoded><![CDATA[<p>So far in this series I&#8217;ve talked extensively about what I consider the most of the important parts in the StoryTeller UI design. This includes <a href="http://www.bjoernrochel.de/2009/08/14/diving-into-the-storyteller-trunk-part-7-screens/" target="_blank">Screens</a>, <a href="http://www.bjoernrochel.de/2009/08/21/diving-into-the-storyteller-trunk-part-8-the-screencollection/" target="_blank">the ScreenCollection</a>, <a href="http://www.bjoernrochel.de/2009/09/07/diving-into-the-storyteller-trunk-part-9-screensubject-screenfactory/" target="_blank">ScreenSubject</a>, <a href="http://www.bjoernrochel.de/2009/09/07/diving-into-the-storyteller-trunk-part-9-screensubject-screenfactory/" target="_blank">ScreenFactory</a>, <a href="http://www.bjoernrochel.de/2009/07/20/diving-into-the-storyteller-trunk-part-5-the-eventaggregator/" target="_blank">EventAggregation</a> and the application of <a href="http://www.bjoernrochel.de/2009/07/13/diving-into-the-storyteller-trunk-part1-convention-based-registration/" target="_blank">Convention of Configuration</a> in general.</p>
<p>You could say that we mostly talked about ingredients. Today I would like to take some additional time in order to show how this is all assembled into an actual API. Those of you who&#8217;veÂ  already spend some time with the StoryTeller codebase too or have watched one of the many screencasts about the <a href="http://www.jeremydmiller.com/ppatterns/Default.aspx?Page=ScreenActivationLifecycle&amp;AspxAutoDetectCookieSupport=1" target="_blank">Screen Activation Lifecycle</a> probably know what I&#8217;m going to show today. Today is all about the <strong>Screen Conductor</strong>.</p>
<p><strong>Screen Conductor vs. Application Controller</strong></p>
<p>Before we dive into the actual code, let&#8217;s take a short break and talk a little bit about a more high level view on the Screen Conductor and the role the conductor is fulfilling in an application.</p>
<p>Martin Fowler identified the pattern ApplicationController some years ago as <em>&#8220;<a href="http://martinfowler.com/eaaCatalog/applicationController.html">A centralized point for handling screen navigation and the flow of an application.&#8221;</a></em></p>
<p>It&#8217;s kind of a coordination structure which manages / coordinates the lifecylcle of child screens in an application as well as the lifecycle of the application shell itself (think about controlled shutdown for instance).</p>
<p>You can think of the ApplicationController as a Facade client code can call in order to create/activate/deactivate screens in an application. This Facade defines a nice separation between application code on the one side and the UI infrastructure on the other side. It shields away implementation details of how the application is actually displaying screens (tab style, web style, etc) from the client and also provides a nice point for handling scenarios like dirty checks on screens.</p>
<p>As an application grows over time, it&#8217;s a good idea to break down the ApplicationController into several collaborating classes and decouple its implementation details from another in order to make the system more manageable and maintainable. Adding a new screen to the application for instance should not require a change in one of the UI infrastructure classes.</p>
<p>When breaking down the ApplicationController into several collaborating classes a good lead is to use the Single Responsibility Principle in order to identify responsibilities which can be extracted. That&#8217;s exactly what Jeremy D. Miller did in his <a href="http://www.jeremydmiller.com/ppatterns/Default.aspx?Page=ScreenActivationLifecycle&amp;AspxAutoDetectCookieSupport=1" target="_blank">Screen Activation Lifecycle</a>.</p>
<p>He broke down the ApplicationController pattern into several smaller responsibilities, the most important beeing</p>
<ul>
<li>the ScreenCollection (which keeps track of all existing screens and the one beeing the active screen)</li>
<li>the ScreenSubject (which is used to separate identification and creation of a screen from the screen itself)</li>
<li>Screens (which provide the content beeing displayed and hooks for instance for the dirty check when the application closes)</li>
<li>and the ScreenConductor.</li>
</ul>
<p>Jeremy describes the ScreenConductor and its responsibilities as the following:</p>
<p><em>&#8220;Controls the activation and deactivation lifecycle of the screens within the application. Depending on the application, the conductor may be synchronizing the menu state of the shell, attaching views in the main panel or otherwise, and calling hook methods on the Presenter&#8217;s to bootstrap the screen. It may also be just as important to deactivate a screen when it&#8217;s made the inactive tab to stop timers. My first exposure to a Screen Conductor was an insurance application that was built with web style navigation. Anytime the user moved away from a screen we needed to check for &#8220;dirty&#8221; screens to give the user a chance to deal with unsaved work. On the other hand, we also had to check the entry into a requested screen to see if we could really open the screen based on pessimistic locking or permission rules. We pulled our a Layer SuperType for our Presenters for methods like CanLeave() and CanEnter(). The Screen Conductor would use these methods and others to manage screen navigation.&#8221;</em></p>
<p>To me the ScreenConductor is more or less an OCP-fied subset of the original ApplicationController pattern, focussing on the coordination and facade ideas of the original pattern.</p>
<p><strong>A short episode in the Screen Activation Lifecycle</strong></p>
<p>Let&#8217;s give our discussion a bit more detail. So far it was rather abstract. Before looking into the actual code I would like to walk you through a typical usecase which depicts how those components actually work together. The example Jeremy mostly uses for this is &#8220;Opening a source code file in Visual Studio&#8221; . I&#8217;m lazy, so I&#8217;m going to reuse this one.</p>
<p><em>&#8220;Consider you double-click a file in theÂ  Solution Explorer of VS. When you do this for the first time a new tab displaying the contents of the file will be opened. Doing the same thing a second time will not open a new tab, but rather focus the existing tab displaying the contents of the file.&#8221;</em></p>
<p>It&#8217;s actually easy to translate this story into a more abstract version using the responsibilities described in this post so far.</p>
<p><em>&#8220;Consider you want to open a <strong>Screen</strong> via a <strong>ScreenSubject</strong>. When the <strong>ScreenSubject</strong> detects that no related <strong>Screen</strong> is being displayed to the user, a new <strong>Screen </strong>will be created by the subject and then added to the <strong>ScreenCollection</strong>. Doing the same thing a second time will not open up a <strong>Screen</strong>, but rather activate the existing <strong>SCREEN</strong>, because the <strong>ScreenSubject </strong>detected that the <strong>Screen </strong>is already open.&#8221;</em></p>
<p>The interesting sidenode in this design is that from a client code perspective there is no difference between opening up a screen and activating a screen. Really nice . . .</p>
<p><strong>Usecase: Opening a Screen</strong></p>
<p>Now that you&#8217;re familiar with the first scenario, time to show some code. I&#8217;ve shown parts of this before in the previous post (Sorry for the duplication), but added some bits in order to illustrate this example.</p>
<p>From the outside world a call to the ScreenConductor for this usecase might look like this.</p>
<pre class="brush: csharp">

var subject = new CSharpFileSubject(@&quot;C:\end\of\the\world.cs&quot;);
screenConductor.OpenScreen(subject);
</pre>
<p>Notice that all data needed for creating the actual Screen will be passed in with the concrete ScreenSubject implementation.</p>
<pre class="brush: csharp">

public class CSharpFileSubject : IScreenSubject
{
     private _fileName;

     public CSharpFileSubject(string fileName) { _fileName = fileName;}

     public bool Matches(IScreen screen)
     {
          return screen is SourceCodeScreen &amp;&amp;
                    string.Equals((SourceCodeScreen)screen.FileName, _fileName));
     }

     public IScreen CreateScreen(IScreenFactory screenFactory)
     {
          var screen =Â  screenFactory.Build&lt;SourceCodeScreen&gt;();
          screen.File = _fileName;
          return screen;
     }
}
</pre>
<p>This is not quite the code I would write for a real system, but I think you get the point. Two methods need to be implemented for the IScreenSubject interface. This is bool Matches(IScreen) which identifies a related screen and IScreen CreateScreen(IScreenFactory) which is used to create the screens.</p>
<p>I really like this kind of API design since it gives you all sorts of extension points without the need to open up the actual infrastructure. Want to show a WaitCursor while you create the Screen? Go ahead. Want to do some loading before the screen is opened? Here&#8217;s the place to do it . . .</p>
<p>Anyway, the ScreenConductors side of things looks like this.</p>
<pre class="brush: csharp">

        public virtual void  OpenScreen(IScreenSubject subject)
        {
            if (subject.Matches(_screens.Active))
            {
                return;
            }

            IScreen screen = findScreenMatchingSubject(subject);

            if (screen == null)
            {
                screen = createNewActiveScreen(subject);
            }
            else
            {
                activate(screen);
            }

            _screens.Show(screen);
        }
</pre>
<p>Pretty slick, isn&#8217;t it? The whole code is really dense. Most of the methods involved are not more than 5 lines long. Finding the related screen for instance is just a matter of a LINQ-Query on the ScreenCollection using the Matches-method as its predicate.</p>
<pre class="brush: csharp">

private IScreen findScreenMatchingSubject(IScreenSubject subject)
{
      return _screens.AllScreens.FirstOrDefault(subject.Matches);
}
</pre>
<p>Creation of the target screen on the other hand is just a matter of handing the ScreenFactory (which is actually just a facade to the IoC-Container of choice) to the subject, activating the created Screen and adding it to the ScreenCollection.</p>
<pre class="brush: csharp">

private IScreen createNewActiveScreen(IScreenSubject subject)
{
     IScreen screen = subject.CreateScreen(_factory);
     activate(screen);
     _screens.Add(screen);
     return screen;
}
</pre>
<p>The last missing piece here is the actual activation of the Screen.</p>
<pre class="brush: csharp">

private void activate(IScreen screen)
{
    _shellService.ActivateScreen(screen);
}
</pre>
<p>This is delegated to the so called IShellService. You might ask yourself why this particular dependency exists (at least I did). The main purpose of this service is mostly the topic of registering Commands and filling up option panes related to the current Screen. This will be a post on its own, so don&#8217;t be mad at me, when I don&#8217;t cover it today. Instead I would like to take a look at another common use case:</p>
<p><strong>Usecase: Closing a Screen</strong></p>
<p>Now that we&#8217;ve seen how a Screen gets opened, let&#8217;s take a look at the other side of the coin, at how it&#8217;s closed.</p>
<pre class="brush: csharp">
public virtual void Close(IScreen screen)
{
    if (removeScreen(screen))
    {
        activateCurrentScreen();
    }
}
</pre>
<p>Most of the handling is in the removeScreen-method (btw, where does this convention of having all private methods beeing camel-cased come from? Is this some Java-exposure leaking through? <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> )</p>
<pre class="brush: csharp">
private bool removeScreen(IScreen screen)
{
     if (!screen.CanClose()) return false;

    _events.RemoveListener(screen);
    _screens.Remove(screen);

    _shellService.ClearTransient();

    return true;
}
</pre>
<p>It delegates the decision whether a screen can be closed to the screen and in case it can be closed, it removes the screen from the EventAggregator(_events), from the ScreenCollection (_screens) and clears its Command-registration (_shellService.ClearTransient()), before it activates the next screen becoming visible (in case there is one).</p>
<pre class="brush: csharp">

private void activateCurrentScreen()
{
        IScreen screen = _screens.Active;

        if (screen != null)
        {
            activate(screen);
        }
}
</pre>
<p><strong>Usecase: App shutdown coordination</strong></p>
<p>There is another common usecase implemented by the ScreenConductor I would like to show you. This is how the whole app shutdown is coordinated.</p>
<p>Prerequesites for this: Instances interested in beeing notified when the user tries to shut the application down, need to a) implement the <em><strong>IClosable </strong></em>interface and b) be registered at the <strong><em>EventAggregator</em></strong>. The latter is done automatically for Screens by the ScreenConductor.</p>
<pre class="brush: csharp">

public interface ICloseable
{
    void AddCanCloseMessages(CloseToken token);
    void PerformShutdown();
}
</pre>
<p>The IClosable interface just consists of two methods. void AddCanCloseMessage(CloseToken) is called in order to get feedback from listeners whether the application is allowed to be shutdown. You can think of CloseToken as a more or less extended version of CancelEventArgs.</p>
<pre class="brush: csharp">

public class CloseToken
{
     private readonly List&lt;string&gt; _messages = new List&lt;string&gt;();

     public string[] Messages { get { return _messages.ToArray(); } }

     public void AddMessage(string message)
     {
         _messages.Add(message);
     }
}
</pre>
<p>The following code piece is hooked into the Closing &#8211; event of StoryTellers main window (the shell). It heavily leverages the delegate based eventing of StoryTellers EventBroker in order to interact with all interested listeners.</p>
<pre class="brush: csharp">

public bool CanClose()
{
     var token = new CloseToken();

     _events.SendMessage&lt;ICloseable&gt;(x =&gt; x.AddCanCloseMessages(token));

    bool returnValue = true;

    if (token.Messages.Length &gt; 0)
    {
         string userMessage = string.Join(&quot;\n&quot;, token.Messages);
         returnValue = _messageBox.AskUser(CAN_CLOSE_TITLE, userMessage);
    }

    if (returnValue)
    {
        _events.SendMessage&lt;ICloseable&gt;(x =&gt; x.PerformShutdown());
    }

    return returnValue;
}
</pre>
<p>One remark to the CanClose() code: _messageBox is just a small wrapper abstraction in order to make user interaction via message prompts testable. There&#8217;s nothing really fancy behind that.</p>
<p>I really like the way the app shutdown is implemented. In fact we&#8217;ve added something very similar in my current project. However, I&#8217;m not so sure when it comes to the question whether this particular code piece should be part of the ScreenConductor. You could argue that this method has only very limited cohesion with the rest of the ScreenConductors methods. In fact most of the stuff the ScreenConductor interacts with (ScreenCollection, Screens, ScreenFactory, ScreenSubject) isn&#8217;t touched in this method. Besides that, it&#8217;s code that client application code normally IMHO doesn&#8217;t need to or even should call. In our current app we&#8217;ve extracted this responsibillity into a separate class called the ApplicationShutdownCoordinator because of that.</p>
<p><strong>Some more impressions on StoryTellers ScreenConductor</strong></p>
<p>The exposed API of the ScreenConductor is pretty small, actually only 6 &#8220;core&#8221; methods and some overloads.Â  Most of the API really shines. However, besides the already mentioned CanClose() functionality, there is another functionality which in my opinion should not be in the ScreenConductor. Can you spot it?</p>
<p><a href="http://www.bjoernrochel.de/wp-content/uploads/2009/11/screenconductorinterface1.jpg"><img class="aligncenter size-full wp-image-630" src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/screenconductorinterface1.jpg" alt="" width="307" height="232" /></a></p>
<p>LoadHierarchy(Func&lt;Hierarchy&gt;)) looks a bit misplaced to me because it seems to work on a different abstraction level than the rest of the methods. It looks very application specific, while the rest of the StoryTeller APIs look very general purpose (independant from the fact whether Jeremy actually wanted to achieve this or this being just the result of applying good design practices).</p>
<p>Same applies to one of the Messages / Events the ScreenConductor is registered for at the EventBroker, namely DeleteTestMessage. I don&#8217;t think it should be directly handled in the ScreenConductor.</p>
<p><a href="http://www.bjoernrochel.de/wp-content/uploads/2009/11/screenconductorhandlers.jpg"><img class="aligncenter size-full wp-image-629" src="http://www.bjoernrochel.de/wp-content/uploads/2009/11/screenconductorhandlers.jpg" alt="" width="500" height="327" /></a></p>
<p>A static code analysis might indicate that the ScreenConductor has too many dependencies. In fact there&#8217;re</p>
<p>7 direct dependencies injected into the constructor,</p>
<ul>
<li>IEventAggregator</li>
<li>IScreenCollection</li>
<li>IScreenFactory</li>
<li>IApplicationShell</li>
<li>IShellService</li>
<li>IScreenObjectLocator</li>
<li>IMessageCreator</li>
</ul>
<p>6 transient dependencies (method parameters or local scope),</p>
<ul>
<li>IScreen</li>
<li>IScreenSubject</li>
<li>CloseToken</li>
<li>UserScreenActivation</li>
<li>OpenItemMessage</li>
<li>DeleteTestMessage</li>
</ul>
<p>and 3 Message interests</p>
<ul>
<li>UserscreenActivation</li>
<li>OpenItemMessage</li>
<li>DeleteTestMessage</li>
</ul>
<p>in the ScreenConductor class. Sounds pretty heavy and like a refactoring candidate at first. However, as I mentioned earlier, the ScreenConductor is mostly a Facade with some additional coordination logic in it. When I say &#8220;some additional coordination logic&#8221; I mean this literally. <strong>ScreenConductor has just round about 250 LOC</strong>.</p>
<p>I&#8217;m totally ok with this. It certainly has some potential for optimization of the dependencies (IScreenObjectLocator seems to be at least partially obsolete, IApplicationShell and IShellService could be merged I guess), but even without that I consider it a really good example of strong extensible design forÂ  composite desktop apps.</p>
<p>For me personally the ScreenConductor fills a really important gap in the p&amp;p composite app guidance (be it CAB / SCSF or PRISM). I always had the feeling that I&#8217;m missing something there, but was unable to point out exactly what I&#8217;ve been missing. This feeling mostly came up when I added some screen activation or screen creation logic in places that didn&#8217;t felt right. Now I know why. Interestingly others <a href="http://neverindoubtnet.blogspot.com/2009/05/birth-and-death-of-m-v-vm-triads.html" target="_blank">observed the need for something similar as well</a>.</p>
<p>Having a ScreenConductor in your application makes IMHO the whole UI infrastructure a lot more approchable and easier to understand.</p>
<p><strong>Some final thoughts</strong></p>
<p>I left the rest of the ScreenConductors code out of this post intentionally, because if there&#8217;s one thing I&#8217;d like you to take from this post or even the complete series is that StoryTeller is a really good learning resource. I really value, what I&#8217;ve learned from the Dovetail guys while inspecting the code. I wish I had done this earlier.</p>
<p>Good design matters. If you&#8217;re looking for a place to learn more about it, the <a href="http://storyteller.tigris.org/source/browse/storyteller/" target="_blank">StoryTeller codebase</a> might just be the place for you.</p>
<p>See you next time, when we take some time to dig into the command structure of StoryTeller . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/11/30/diving-into-the-storyteller-trunk-part-10-coordination-baby/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>xUnit.BDDExtensions now runs with xUnit 1.5 final</title>
		<link>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/</link>
		<comments>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 21:25:33 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=551</guid>
		<description><![CDATA[I&#8217;ve just upgraded the trunk to the final 1.5 version of xUnit released last week. This update now allows BDDExtensions to be used with the latest version independant resharper runner for xUnit from xunitcontrib.
Current Version is 1.0.1.16. You can download it here or get the latest sources from the trunk.
Happy specifying . . .
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just upgraded the trunk to the final 1.5 version of xUnit released last week. This update now allows BDDExtensions to be used with the latest version independant resharper runner for xUnit from xunitcontrib.</p>
<p>Current Version is 1.0.1.16. You can download it <a href="http://xunitbddextensions.googlecode.com/files/xunit.bddextensions.1.0.1.16.zip">here</a> or get the latest sources from the <a href="http://xunitbddextensions.googlecode.com/svn/trunk/">trunk</a>.</p>
<p>Happy specifying . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>xUnit.BDDExtensions update</title>
		<link>http://www.bjoernrochel.de/2009/09/07/xunitbddextensions-update/</link>
		<comments>http://www.bjoernrochel.de/2009/09/07/xunitbddextensions-update/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 07:07:51 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=549</guid>
		<description><![CDATA[xUnit.BDDExtensions now uses Rhino.Mocks 3.6 internally. I&#8217;ve just updated the trunk. As usual you
can find it here: http://xunitbddextensions.googlecode.com/svn/trunk/
]]></description>
			<content:encoded><![CDATA[<p>xUnit.BDDExtensions now uses Rhino.Mocks 3.6 internally. I&#8217;ve just updated the trunk. As usual you<br />
can find it here: <a href="http://xunitbddextensions.googlecode.com/svn/trunk/" target="_blank"><tt><strong><em>http</em></strong>://xunitbddextensions.googlecode.com/svn/trunk/</tt></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/09/07/xunitbddextensions-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 9: ScreenSubject &amp; ScreenFactory</title>
		<link>http://www.bjoernrochel.de/2009/09/07/diving-into-the-storyteller-trunk-part-9-screensubject-screenfactory/</link>
		<comments>http://www.bjoernrochel.de/2009/09/07/diving-into-the-storyteller-trunk-part-9-screensubject-screenfactory/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 07:01:19 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=544</guid>
		<description><![CDATA[Hello back again on my little exploration of the UserInterface implementation of Jeremy Millers StoryTeller. I&#8217;d like to start today with a little excuse (oh my). Although I said last time that the current post would be focused on the ScreenConductor, I decided to delay that at least for one post in the series in [...]]]></description>
			<content:encoded><![CDATA[<p>Hello back again on my little exploration of the UserInterface implementation of Jeremy Millers StoryTeller. I&#8217;d like to start today with a little excuse (oh my). Although I said last time that the current post would be focused on the ScreenConductor, I decided to delay that at least for one post in the series in order to add some content related to what Jeremy calls ScreenSubject and ScreenFactory. I consider them to be fairly simple but yet really powerful pattern which can help you a lot to structure your UI layer, especially the fine line of the UI layer where the UI infrastructure meets the common application code. It&#8217;s also a very good example of applying the Open Closed Principle.</p>
<p><b>The common use case for the ScreenSubject</b></p>
<p>Lets first start with a little description of the usage of the two patterns in StoryTeller. When application code wants to open a new screen in StoryTeller it&#8217;ll probably use one of the OpenScreen overloads on the IScreenConductor facade in order to do that.</p>
<pre class="brush: csharp">
public interface IScreenConductor
{
    void OpenScreen(IScreenSubject subject);
    void OpenScreen&lt;T&gt;() where T: IScreenSubject;
}
</pre>
<p>The common use case for the ScreenSubject can be easily depicted using a tool we all know quite well, Visual Studio. Think about it: What happens when you click onto a source code file in the Source Code Explorer for the first time? Well, a new tab is created displaying the content of the file. However, if you click the item in the Source Control Explorer the second time, the previously created tab gets activated and NO NEW TAB IS CREATED.</p>
<p><b>How is this implemented</b></p>
<p>Let&#8217;s take a look at how this behavior is implemented in StoryTeller. The following code snippet shows a very small part of the ScreenConductor. I&#8217;ve inline some comments in order to make it more visible<br />
what is going on there.</p>
<pre class="brush: csharp">

        public virtual void OpenScreen(IScreenSubject subject)
        {
            //_screens is of type IScreenCollection
            if (subject.Matches(_screens.Active))
            {
                return;
            }

            //This simply makes a LINQ-lookup on the ScreenCollection
            //using ScreenSubject.Matches as a predicate
            IScreen screen = findScreenMatchingSubject(subject);

            if (screen == null)
            {
                //This passes the global IScreenFactory into the
                //ScreenSubjects CreateScreen method in order to create
                //the screen.
                screen = createNewActiveScreen(subject);
            }
            else
            {
                activate(screen);
            }

            _screens.Show(screen);
        }
</pre>
<p>The IScreenSubject abstraction plays a quite important role in this use case. The interface defines only two methods matching the responsibilities of the ScreenSubject</p>
<pre class="brush: csharp">

    public interface IScreenSubject
    {
        bool Matches(IScreen screen);
        IScreen CreateScreen(IScreenFactory factory);
    }
</pre>
<p>As we saw in the ScreenConductor snippet the Matches method is used as a predicate in order to find the related screen. The CreateScreen method isn&#8217;t directly shown in the snippet, but it&#8217;s not that complicated. It&#8217;s responsible for coordinating the creation of a screen. When I say coordination I&#8217;m referring to the fact that the actual screen creation is the responsibility of the IScreenFactory (which is just a simple wrapper around StructureMap).</p>
<pre class="brush: csharp">

   public interface IScreenFactory
    {
        T Build&lt;T&gt;() where T : IScreen;
        IScreen&lt;T&gt; Build&lt;T&gt;(T subject);
    }
</pre>
<p>With this design in place we have a very nice extension point in place to do all kinds of things around the screen creation. Want to do some deferred data loading before the screen is shown? That&#8217;s your place. Maybe you want to show some progress indicator while doing this. Guess what, that&#8217;s your place to do this. And the best of it: The screen doesn&#8217;t have to know anything of this, you can free<br />
him of this kind of logic.</p>
<p>There&#8217;re some base classes which provide some base implementation for different use cases in StoryTeller. I&#8217;m only going to show one of them, the ScreenSubject&lt;T&gt;. This class adds a bit generics on top of the ScreenSubject (in order to allow auto-registration using StructureMaps convention over configuration features). </p>
<pre class="brush: csharp">

   // Marker interface
    public interface IScreenSubject&lt;T&gt; : IScreenSubject
    {
    }

    public class ScreenSubject&lt;T&gt; : IScreenSubject&lt;T&gt;
    {
        private readonly T _subject;

        public ScreenSubject(T subject)
        {
            _subject = subject;
        }

        #region IScreenSubject&lt;T&gt; Members

        public bool Matches(IScreen screen)
        {
            var specific = screen as IScreen&lt;T&gt;;
            if (specific == null) return false;

            return specific.Subject.Equals(_subject);
        }

        public IScreen CreateScreen(IScreenFactory factory)
        {
            return factory.Build(_subject);
        }

        #endregion

        public bool Equals(ScreenSubject&lt;T&gt; other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other._subject, _subject);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (ScreenSubject&lt;T&gt;)) return false;
            return Equals((ScreenSubject&lt;T&gt;) obj);
        }

        public override int GetHashCode()
        {
            return _subject.GetHashCode();
        }
    }
</pre>
<p>The basic idea used in this implementation of IScreenSubject is that a ScreenSubject is related to a single data instance. Coming back to the Visual Studio example, this could have been represented as something like ScreenSubject&lt;SourceCodeFile&gt;. Really interesting . . .</p>
<p>The last code snippet for today I&#8217;d like to show is how the ScreenFactory is actually implemented. As usual really short, not very much code. </p>
<pre class="brush: csharp">

    public class ScreenFactory : IScreenFactory
    {
        private readonly IContainer _container;

        public ScreenFactory(IContainer container)
        {
            _container = container;
        }

        #region IScreenFactory Members

        public SCREEN Build&lt;SCREEN&gt;() where SCREEN : IScreen
        {
            return _container.GetInstance&lt;SCREEN&gt;();
        }

        public IScreen&lt;T&gt; Build&lt;T&gt;(T subject)
        {
            return _container.With(subject).GetInstance&lt;IScreen&lt;T&gt;&gt;();
        }

        #endregion
    }
</pre>
<p>I really like the way how StructureMap allows injecting transient parameters in the resolution process . . .</p>
<p><b>Closing thoughts</b></p>
<p>I&#8217;m honest with you. I consider ScreenSubject to be one of the most valuable patterns I&#8217;ve learned so far while playing with the StoryTeller sources. It provides such a nice extension point for screen initialization. I think it&#8217;s one of those patterns you don&#8217;t know how much you miss it until you see it for the first time and recognize how much it could have helped you in the past. At least that was my reaction. </p>
<p>In the past I&#8217;ve put a lot of the functionality which resides in StoryTeller in ScreenSubject implementations on my screens which polluted my screens with a lot of initialization code and sometimes (especially when you have high network latency) doesn&#8217;t even really look good (I bet you know what I&#8217;m talking about, don&#8217;t you? I bet a lot of you have seen the frozen screen, too).</p>
<p>The ScreenSubject pattern was introduced to my project last week and what can I say: I&#8217;m pretty happy to have it in our application <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/09/07/diving-into-the-storyteller-trunk-part-9-screensubject-screenfactory/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 8: The ScreenCollection</title>
		<link>http://www.bjoernrochel.de/2009/08/21/diving-into-the-storyteller-trunk-part-8-the-screencollection/</link>
		<comments>http://www.bjoernrochel.de/2009/08/21/diving-into-the-storyteller-trunk-part-8-the-screencollection/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 14:19:11 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=502</guid>
		<description><![CDATA[
Welcome back again to the &#8220;Diving into the StoryTeller trunk&#8221; series. Got your diving suit on? If so, good. If not: Suit-up! (Sorry, the HIMYM fanboy in me was too strong  )

Last time we spend some time with the concept of Screens. Screens more or less provide the content of an application. Content needs [...]]]></description>
			<content:encoded><![CDATA[<p>
Welcome back again to the &#8220;Diving into the StoryTeller trunk&#8221; series. Got your diving suit on? If so, good. If not: Suit-up! (Sorry, the HIMYM fanboy in me was too strong <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> )
</p>
<p>Last time we spend some time with the concept of Screens. Screens more or less provide the content of an application. Content needs to be displayed somewhere and that&#8217;s where the ScreenCollection concept comes into play.</p>
<p>
In abstract a ScreenCollection is a container for multiple Screens. It&#8217;s used to display screens. The ScreenCollection concept is comparable to PRISMs Regions or CABs WorkSpaces. It doesn&#8217;t really contain a lot of intelligence. It only allows you to add a Screen, remove a Screen, getting all Screens in the container, make a Screen the active one. You know, all in all the typical stuff you would expect from a collection (maybe except the last one). The ScreenCollection contract is represented by the IScreenCollection interface which looks like this:</p>
<pre class="brush: csharp">

        public interface IScreenCollection
       {
             void ClearAll();
             IScreen Active { get; }
             void Show(IScreen screen);
             void Add(IScreen screen);
             void Remove(IScreen screen);
             IEnumerable&lt;IScreen&gt; AllScreens { get; }
             void RenameTab(IScreen screen, string name);
        }
</pre>
<p>If take a closer look at the interface you&#8217;ve probably recognized the last method which doesn&#8217;t really fit in there. Let&#8217;s spare that discussion for a moment. I&#8217;m going to comment on that in a moment.</p>
<p />
StoryTeller contains only one implementation for the IScreenCollection interface, which is called (what-a-surprise) ScreenCollection.  This class simply wraps around a standard WPF TabControl. Let&#8217;s take a look at how this is implemented, starting with the constructor.</p>
<pre class="brush: csharp">
    public class ScreenCollection : IScreenCollection
    {
        private readonly Cache&lt;IScreen, StoryTellerTabItem&gt; _tabItems = new Cache&lt;IScreen, StoryTellerTabItem&gt;();
        private readonly TabControl _tabs;

        public ScreenCollection(TabControl tabs, IEventAggregator events)
        {
            _tabs = tabs;
            _tabItems.OnMissing = screen =&gt; new StoryTellerTabItem(screen, events);
            _tabs.SelectionChanged += (s, c) =&gt; { events.SendMessage&lt;UserScreenActivation&gt;(); };

	    // Hack.  Sigh.
            events.AddListener(new RenameTestHandler(new ScreenFinder(this), this));
        }

	...
    }
</pre>
<p>There&#8217;re are two interesting things to notice here. The ScreenCollection uses a cache concept in order to correlate Screens and the TabItems used to display them. The Cache&lt;TKey,TValue&gt; class is a smart wrapper around an IDictionary&lt;TKey,TValue&gt;  which (besides some other functionality) allows you to plug-in a custom handler which is called when no value is found for the specified key. This handler acts as a kind of value factory. That&#8217;s exactly what we see when we take a look at the line with _tabItems.OnMissing. Each time a Screen is not found in the cache StoryTeller creates a new StoryTellerTabItem.</p>
<p>
The other interesting thing to notice is that the ScreenCollection doesn&#8217;t directly expose events but rather uses the Eventbroker for this. You can see this at the UserScreenActivation message.
</p>
<p>Yeah and then there is the &#8220;RenameTab&#8221; thing. It&#8217;s marked as a hack. It simply shouldn&#8217;t be there. The problem it currently solves it that when a test is renamed the related TabHeader must also be updated (We take a look at the TabItem in a moment). I wonder whether this isn&#8217;t something that could be done in a cleaner way using WPF databinding on Screen.Title instead. </p>
<p />
Lets take a look at how the cache magic is used. It&#8217;s really compact code. Most of the methods are one or two liners.</p>
<pre class="brush: csharp">

        public void ClearAll()
        {
            _tabs.Items.Clear();
        }

        public void Show(IScreen screen)
        {
            _tabs.SelectedItem = _tabItems[screen];
        }

        public void Add(IScreen screen)
        {
            _tabs.Items.Add(_tabItems[screen]);
        }

        public void Remove(IScreen screen)
        {
            TabItem tabItem = _tabItems[screen];
            _tabItems.Remove(screen);
            _tabs.Items.Remove(tabItem);
        }

        public IEnumerable&lt;IScreen&gt; AllScreens { get { return new List&lt;IScreen&gt;(_tabItems.Keys()); } }
</pre>
<p>The cache class is used like you would use a good old Hashtable. All in all I think I don&#8217;t need to say more here.  Here is the code for determining the active Screen.</p>
<pre class="brush: csharp">

        public IScreen Active
        {
            get
            {
                if (_tabs.SelectedItem != null) return toScreen(_tabs.SelectedItem);

                return null;
            }
        }

        private IScreen toScreen(object tab)
        {
            return tab.As&lt;TabItem&gt;().Tag.As&lt;IScreen&gt;();
        }
</pre>
<p>Last but not least here&#8217;s the code for the TabItem which is build around a screen.</p>
<pre class="brush: csharp">

    public class StoryTellerTabItem : TabItem
    {
        private Label _label;

        public StoryTellerTabItem(IScreen screen, IEventAggregator events)
        {
            Func&lt;Action&lt;IScreenConductor&gt;, Action&gt; sendMessage = a =&gt; () =&gt; events.SendMessage(a);

            Header = new StackPanel().Horizontal()
                .AddText(screen.Title, x =&gt; _label = x)
                .IconButton(Icon.Close, sendMessage(s =&gt; s.Close(screen)), b =&gt; b.SmallerImages());

            Content = new DockPanel().With(screen.View);
            Tag = screen;

            ContextMenu = new ContextMenu().Configure(o =&gt;
            {
                o.AddItem(&quot;Close&quot;, sendMessage(s =&gt; s.Close(screen)));
                o.AddItem(&quot;Close All But This&quot;, sendMessage(s =&gt; s.CloseAllBut(screen)));
                o.AddItem(&quot;Close All&quot;, sendMessage(s =&gt; s.CloseAll()));
            });
        }

        public string HeaderText { get { return _label.Content as string; } set { _label.Content = value; } }
    }
</pre>
<p>I need to talk more about this part, don&#8217;t I? </p>
<p>Again two intersting things here. First thing, it really makes heavy usage of C#3.0. You can see a lot of Extension Methods on WPF classes used in order to build and configure WPF elements in a very fluent and compact way.</p>
<p>
Besides that you see here again how the EventBroker can be nicely integrated into Screen handling. Take a look at the context menu of each TabItem. It provides handlers which call directly into the EventBroker for triggering the typical close operations you can also see in Visual Studio. The important thing here to take away is that the close operations are only triggered here but performed by the IScreenConductor.
</p>
<p>For those of you who didn&#8217;t follow my &#8220;StoryTeller&#8221; investigations from the start: The  ScreenConductor is the great coordinator for the Screen Activation Lifecycle behind the scenes. It&#8217;s (as far as I can tell) the central facade to the Screen Activation Lifecyle from the perspective of typical application code. The ScreenConductor is a big topic which will be discussed in one of the next posts.</p>
<p>
<b>Closing thoughts</b>
</p>
<p>Lets not comment on the RenameTab thing, ok? I bet, Jeremy is going to fix that pretty soon. The ScreenCollection is (again) a good example of how much you can do with so few lines. However sometimes this can have downsides, too. I can only imagine .NET developers unfamiliar with<br />
this heavy usage of C#3.0 features staring at the code and thinking something like: WTF, what&#8217;s happening here? Personally, I like it, especially the cache aspect of it. I&#8217;ve done the .Tag thing far too often now. </p>
<p>
Sadly one thing I would have loved to see is missing in the code, the ability to block deactivation or activation. Typical example for this is a requirement forcing the user to save or discard changed data before leaving a Screen. I had this requirement in the last 5 applications I worked on. It would have been interesting to see how Jeremy tackles such a requirement. I&#8217;m just assuming that he would use the EventBroker for that &#8230;
</p>
<p>Enought Screen Mania for today. I hope you&#8217;ve enjoyed the ride so far and we&#8217;ll rejoin next time when it&#8217;s time to take a look at the big guy in the game, the ScreenConductor.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/21/diving-into-the-storyteller-trunk-part-8-the-screencollection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 7: Screens</title>
		<link>http://www.bjoernrochel.de/2009/08/14/diving-into-the-storyteller-trunk-part-7-screens/</link>
		<comments>http://www.bjoernrochel.de/2009/08/14/diving-into-the-storyteller-trunk-part-7-screens/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 15:04:15 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=476</guid>
		<description><![CDATA[
In the previous post I gave a short overview over the players that are involved in the so called
Screen Activation Lifecycle. Today I would like to take a closer look at, guess what, the Screen.

For me personally, the design &#8216;around&#8217; a Screen is one of the crutial elements for success in
developing a composite UI layer. [...]]]></description>
			<content:encoded><![CDATA[<p>
In the previous post I gave a short overview over the players that are involved in the so called<br />
Screen Activation Lifecycle. Today I would like to take a closer look at, guess what, the Screen.
</p>
<p>For me personally, the design &#8216;around&#8217; a Screen is one of the crutial elements for success in<br />
developing a composite UI layer. Why do I think so?</p>
<p>
Mostly because it&#8217;s one of the central points which connects the UI infrastructure with all the rest of the application, the actual application code. It&#8217;s THE INTERFACE that fills you&#8217;re framework / infrastructure with life.  If you fail here you probably feel the result throughout the complete application. Day to day work happens around that interface and since the UI seems to be one of those places in an application that is very volatile and changes a lot, a Screen design with principles like DRY and OCP in mind will make your life as an application developer much easier.
</p>
<p>So what are the basic responsibilities of a Screen?
<ul>
<li>
First of all it provides content. While a composite UI&#8217;s shell provides the hull of the application, the Screen provides the UI to fulfill a business requirement. I think it&#8217;s comparable to the relationship between an Asp.Net Masterpage and the aspx pages displayed in its content placeholder (Disclaimer: I&#8217;m no Asp.net expert so feel free to correct).
</li>
<li>
Controlling Screen Activation. Since the UI infrastructure can&#8217;t possibly now what has to happen when a Screen is activated, it delegates the responsibility to the Screen itself. A practical example of the Tell-Don&#8217;t-Ask-principle. Interaction with the Command infrastructure mostly happens here.
</li>
<li>
Controlling Screen Deactivation / Closing. I&#8217;ve seen this in several applications now. A Screen with changed data can only be left / closed when a) changes have been persisted or b) the user votes to discard the changes. Like in point 2. the UI infrastructure can&#8217;t possibly know when that&#8217;s the case, so it&#8217;s delegated.
</li>
</ul>
<p>With those 3 points in mind, let&#8217;s take a look at the Screen interface in StoryTeller.</p>
<pre class="brush: csharp">
    public interface IScreen
    {
        object View { get; }
        string Title { get; }
        void Activate(IScreeObjectRegistry screenObjects);
        bool CanClose();
    }
</pre>
<p>Pretty straight forward, isn&#8217;t it?. Next question, who is actually implementing the interface? And the answer is surprisingly: It depends! This interface can be implemented for instance by Passive View &#8211; or Supervising Controller &#8211; style Presenters. It can be implemented by ViewModels in Model-View-View-Model implementations. It can even be implemented by UserControls (though StoryTeller uses this only for very simplistic screens). It&#8217;s a very pragmatic solution giving a lot of choice to an application developer on how to interact with the UI infrastructure. </p>
<p>
I think that&#8217;s a good choice. We, as a community, shouldn&#8217;t be dogmatic about MVVM vs. MVP, or the whole No-Code-Behind-debate. Consistency is import but, sticking to a pattern not suited for a particular screen (for instance using Passive View for a screen with a lot of fields) can hurt much more than the (pattern) consistency would justify. Mh,  that was a little bit off-topic, wasnâ€™t it?
</p>
<p>Most of the Screens in StoryTeller are classical Model View Presenter implementations getting their view injected in the constructor.</p>
<pre class="brush: csharp">
    public class SuitePresenter : IListener&lt;TestIconChanged&gt;, ISuitePresenter, IListener&lt;TestAdded&gt;
    {
        private readonly Cache _drivers;
        private readonly ITestExplorer _explorer;
        private readonly ITestService _service;
        private readonly Suite _suite;
        private readonly ISuiteView _view;

        public SuitePresenter(Suite suite, ISuiteView view, ITestExplorer explorer, ITestService service)
        {
            _suite = suite;
            _view = view;
            _explorer = explorer;
            _service = service;

            _view.Presenter = this;
            _drivers = new Cache&lt;Test, ITestLineDriver&gt;(t =&gt; _view.AddTest(t, queueTest));
        }

	..........
    }
</pre>
<p>The structural aspect of the screens isn&#8217;t that interesting to me. Standard MVP stuff. The activation however (in particular the usage of IScreenObjectRegistry) looks really interesting. Take a look for yourself:</p>
<pre class="brush: csharp">
     public void Activate(IScreenObjectRegistry screenObjects)
     {
            screenObjects
               .Action(&quot;Run&quot;)
               .Bind(ModifierKeys.Control, Key.D1)
               .To(_presenter.RunCommand).Icon = Icon.Run;
     }
</pre>
<p>IScreenObjectRegistry will be inspected in a future post. The next post though, will take a closer look at the ScreenCollection. So,  if you&#8217;re eager to learn more about the diamonds and jewels Jeremy has created in StoryTellers trunk (like I am) rejoin me for the next post when it&#8217;s time to go diving again . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/14/diving-into-the-storyteller-trunk-part-7-screens/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
