<?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; StoryTeller</title>
	<atom:link href="http://www.bjoernrochel.de/tag/storyteller/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>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>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>
		<item>
		<title>Diving into the StoryTeller trunk, Part 6: The main players in the screen activation lifecycle</title>
		<link>http://www.bjoernrochel.de/2009/08/07/diving-into-the-storyteller-trunk-part-6-the-main-players-in-the-screen-activation-lifecycle/</link>
		<comments>http://www.bjoernrochel.de/2009/08/07/diving-into-the-storyteller-trunk-part-6-the-main-players-in-the-screen-activation-lifecycle/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 17:42:40 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/2009/08/07/diving-into-the-storyteller-trunk-part-6-the-main-players-in-the-screen-activation-lifecycle/</guid>
		<description><![CDATA[
It has been an interesting time with the StoryTeller codebase so far. I&#8217;ve learned a lot about advanced StructureMap usage by scanning through the code, trying to understand the unit tests, debugging StoryTeller and writing some smaller programs based on the newly discovered patterns &#38; features.
However, my initial motivation for spending time with that codebase [...]]]></description>
			<content:encoded><![CDATA[<p>
It has been an interesting time with the StoryTeller codebase so far. I&#8217;ve learned a lot about advanced StructureMap usage by scanning through the code, trying to understand the unit tests, debugging StoryTeller and writing some smaller programs based on the newly discovered patterns &amp; features.</p>
<p>However, my initial motivation for spending time with that codebase wasn&#8217;t StructureMap or the Convention over Configuration topic but rather StoryTellers implementation of the screen activation lifecycle. Jeremy wrote bits about it in his &#8220;Build your Own Cab&#8221; series, but they where rather abstract and didn&#8217;t show a lot of code. Many responsibilities he described seemed totally logical to me, but I had trouble putting all those concepts together into code (which mostly undermines that I only understood have of the stuff I read <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ).</p>
<p>Things became really interesting again when Jeremy showed more parts at the Presentation Patterns talk at last NDC. Damn, I wasn&#8217;t aware that a lot of the patterns he described were already implemented in the StoryTeller codebase (or did they emerge after the recent rewrite ???). With part 6 of my Story Teller journey I would like to spend some time describing the general players in the screen activation lifecycle. This will be a no-code-post. A high level view so to say.</p>
<p><span style="underline;"><strong>ScreenCollection</strong></span></p>
<p>In his Presentation Patterns talk Jeremy described that the kind of desktop application he worked on in the past implemented mostly one of two major navigation styles: Tab-style navigation or Web-style-navigation..</p>
<ul>
<li>Tab-style-navigation more or less means that every new screen or control is displayed on a different tab, a new content control in the UI.</li>
<li>Web-style-navigation means that every new screen or control is mostly displayed in the same content control and replaces the previously displayed control. Basically a way how a browser handles things (of course, in the old ages before the empire, hm I mean tab <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ).</li>
</ul>
<p>StoryTeller implements a Tab-style navigation. However you don&#8217;t interact with a TabControl directly in StoryTeller . It is exposed via the IScreenCollection interface. The functionality of this interface is mostly similar to CAL/CAG/PRISMs IRegion or the old IWorkspace interface in CAB. However there&#8217;s a huge difference in what the IScreenCollection accepts in his Open, Close or Activate methods. They don&#8217;t accept UserControls or UIElements, they accept only instances implementing the IScreen interface.</p>
<p><span style="underline;"><strong>Screen</strong></span></p>
<p>The complete screen activation lifecycle in StoryTeller is based on the IScreen interface and therefore completely decoupled from the related UI technology. Testability, baby !!!</p>
<p>The screen interface is mostly implemented directly by Presenters or ViewModels and exposes methods for determining current caption for the screen, or the activation and deactivation of commands. Screens are created by a ScreenSubject.</p>
<p><strong><span style="underline;">ScreenSubject</span></strong></p>
<p>ScreenSubject is a really nice abstraction which deals with the creation and the identification of a particular screen. This abstraction is really valuable in applications which behave a lot like Visual Studio when opening code files. Think about it, when you first open up a source code file by double clicking it in the Source Code Explorer a new tab or window is created for it. Double clicking the file again doesn&#8217;t open a new window but rather activates the related tab or window. That&#8217;s exactly what the ScreenSubject abstraction tries to achieve, too.</p>
<p>Freeing the consumer code from the decision whether to create a new screen or to activate an already existing screen is the responsibility of the ScreenSubject implementations.</p>
<p><strong><span style="underline;">ShellConductor</span></strong></p>
<p>The ShellConductor is THE BIG PLAYER in the screen activation lifecycle. In Martin Fowlers terms the ShellConductor fulfills the role of the ApplicationController. The ShellConductor is the piece of code that (besides some other topics) controls and coordinates the whole Screen handling.</p>
<p>He is responsible for screen activation and deactivation, controls the closing of Screens and acts as kind of a facade for typical application code working with the framework. You could say that the ScreenConductor is an ApplicationController broken down into more smaller, specialized parts.</p>
<p>As you can imagine the ShellConductor knows a lot of his buddies in the neighborhood. Just to give you an impression how a typical operation on the ShellConductor might look like, I&#8217;d like to walk you through the simple topic of opening a screen in the UI. Here are the Steps:</p>
<ol>
<li>Client code calls OpenScreen(new MyScreenSubject()) on the ShellConductor.</li>
<li>ShellConductor knows the ScreenCollection and tries to find a Screen matching the subject in the collection.</li>
<li>If a Screen was found, it&#8217;s activated.</li>
<li>If no Screen was found, the ShellConductor
<ol>
<li>creates the target screen via the supplied ScreenSubject,</li>
<li>adds it to the ScreenCollection and</li>
<li>activates it in the ScreenCollection.</li>
</ol>
</li>
</ol>
<p>The ShellConductor will be a larger topic I&#8217;m going to look into in one of the next posts, so please forgive me for the moment if I continue my overview with the last element for today, the Shell.</p>
<p><span style="underline;"><strong>Shell</strong></span></p>
<p>The Shell is the host window for the application. It&#8217;s the frame in which the ScreenCollection and Screens are displayed. It&#8217;s actually pretty dumb, since it only has kind of a container functionality.</p>
<p><strong><span style="underline;">What I didn&#8217;t touch today</span></strong></p>
<p>To be honest there is a more in the StoryTeller UI layer than the stuff I described today. On of the major topics for instance I left out for the moment is the whole topic dealing with Commands, CommandBindings and InputGestures.</p>
<p>StoryTeller shows a nice way of how to use a little internal Dsl for defining Commands on the fly. So far I&#8217;ve looked at it only sufficiently but it looks really promising. I&#8217;m definitely going to spend a post or two for that topic, so stay tuned.</p>
<p>See you next time when it&#8217;s time to look at some code again . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/08/07/diving-into-the-storyteller-trunk-part-6-the-main-players-in-the-screen-activation-lifecycle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 5: The EventAggregator</title>
		<link>http://www.bjoernrochel.de/2009/07/20/diving-into-the-storyteller-trunk-part-5-the-eventaggregator/</link>
		<comments>http://www.bjoernrochel.de/2009/07/20/diving-into-the-storyteller-trunk-part-5-the-eventaggregator/#comments</comments>
		<pubDate>Mon, 20 Jul 2009 19:19:11 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>
		<category><![CDATA[StructureMap]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=439</guid>
		<description><![CDATA[I&#8217;ve spend some time with the Pub / Sub topic on my own in the past. Although I still like my own implementation, even a year after I&#8217;ve originally written it (yes, rare but sometimes that happens), I really like how Jeremy implemented it. The EventAggregator in StoryTeller is one of those examples of how [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spend some time with the Pub / Sub topic on my own in the <a href="http://www.bjoernrochel.de/tag/publish-subscribe/">past</a>. Although I still like my own implementation, even a year after I&#8217;ve originally written it (yes, rare but sometimes that happens), I really like how Jeremy implemented it. The EventAggregator in StoryTeller is one of those examples of how much you can achieve with only a few lines of code.  So let&#8217;s go diving again <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>
A type who is interested in recieving messages from the EventAggregator in StoryTeller has to implement the IListener&lt;T&gt; interface where T specifies the concrete message / event. A container extension is used for automatic registration of instances at the EventAggregator after instances have been created in the container (more on this later in the post).
</p>
<pre class="brush: csharp">
public interface IListener&lt;T&gt;
{
      void Handle(T message);
}
</pre>
<p>The interface to the EventAggregator looks like this.  </p>
<pre class="brush: csharp">

public interface IEventAggregator
{
      void SendMessage&lt;T&gt;(Action&lt;T&gt; action) where T : class;
      void SendMessage&lt;T&gt;(T message);
      void AddListener(object listener);
      void RemoveListener(object listener);
}
</pre>
<p>Most of the interface looks familiar to me, except the SendMessage&lt;T&gt;(Action&lt;T&gt; action) method. The EventAggregator implementation in StoryTeller adds a interesting feature to the topic: Using delegates instead of explicit event classes. One of the things Jeremy mentioned in his NDC &#8220;Presentation Patterns&#8221; talk is that sometimes creating event classes for events felt a bit tedious to him, especially when those events only have signal character and don&#8217;t carry any data with them around. IIRIC the varation with delegates instead of event classes implemented in StoryTeller came up in discussion with Glenn Block and the Prism team. However it didn&#8217;t make it into Prism in the end. See the difference in usage for yourself:  </p>
<pre class="brush: csharp">
aggregator.SendMessage(new ScreenClosingMessage(screen));
aggregator.SendMessage&lt;IWantToKnowWhenAScreenClosed&gt;(x =&gt; x.ScreenHasClosed(screen));
</pre>
<p>Below is the code for the EventAggregator. There are some interesting things to notice. </p>
<ul>
<li>
First of all, the EventBroker doesn&#8217;t know about subscriptions for a particular type. It only knows listener objects. Compatible listeners are found on the fly when the event / message is published by iterating over all known listener objects and calling the CallOn extension method.  I&#8217;ll spare the code for this extension method because all it does is executing an Action&lt;T&gt; only when an object can be cast to the type specified by T.
</li>
<li>
Automatic thread-synchronization to the main-thread is applied by using the SynchronizationContext class. Imho, one of the gems in the .NET 2.0 release that more people should be aware of. I think this class is a really great feature for freeing client code from dealing with callback synchronization issues. Just let the framework handle the InvokeRequired stuff for you. No one likes to write that stuff anyway.
</li>
<li>
Jeremy likes it functional <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . I think this is an interesting example how C# 3.0 code can actually differ from an 1.0 implementation. The shown code is really, really dense and focussed by using a lot of the C# 2.0 and 3.0 features like lamda expressions, extension methods and of course generics. Personally I really like this coding style, however a lot of my colleagues don&#8217;t. The debugging story differs a lot from the one using classic if and for loops, which isn&#8217;t such a problem for the test-first or test-parallel guys, but I can see where this might feel a bit awkward when you&#8217;ve relied on the debugger for most of your developing efforts in the past. In my opinion it&#8217;s just a matter of personal taste. Just give it a try and make your own opinion . . .
 </li>
</ul>
<pre class="brush: csharp">
    public class EventAggregator : IEventAggregator
    {
        private readonly SynchronizationContext _context;
        private readonly List&lt;object&gt; _listeners = new List&lt;object&gt;();
        private readonly object _locker = new object();

        public EventAggregator(SynchronizationContext context)
        {
            _context = context;
        }

        #region IEventAggregator Members

        public void SendMessage&lt;T&gt;(Action&lt;T&gt; action) where T : class
        {
            sendAction(() =&gt; all().Each(x =&gt; x.CallOn(action)));
        }

        public void SendMessage&lt;T&gt;(T message)
        {
            sendAction(() =&gt; all().CallOnEach&lt;IListener&lt;T&gt;&gt;(x =&gt; { x.Handle(message); }));
        }

        public void AddListener(object listener)
        {
            withinLock(() =&gt;
            {
                if (_listeners.Contains(listener)) return;
                _listeners.Add(listener);
            });
        }

        public void RemoveListener(object listener)
        {
            withinLock(() =&gt; _listeners.Remove(listener));
        }

        #endregion

        private object[] all()
        {
            lock (_locker)
            {
                return _listeners.ToArray();
            }
        }

        private void withinLock(Action action)
        {
            lock (_locker)
            {
                action();
            }
        }

        protected virtual void sendAction(Action action)
        {
            _context.Send(state =&gt; { action(); }, null);
        }

        public void AddListeners(params object[] listeners)
        {
            foreach (object listener in listeners)
            {
                AddListener(listener);
            }
        }

        public bool HasListener(object listener)
        {
            return _listeners.Contains(listener);
        }

        public void RemoveAllListeners()
        {
            _listeners.Clear();
        }
    }
</pre>
<p>As I said earlier in this post, instances are registered after they&#8217;ve been created by the container. The functionality for this is provided by a TypeInterceptor class. This class is part of the StructureMap API. Once it has been registered every created instances is passed through this interceptor after it has been resolved. If the instance is identified as relevant for the EventAggregator it is automatically registered.</p>
<pre class="brush: csharp">
    public class EventAggregatorInterceptor : TypeInterceptor
    {
        #region TypeInterceptor Members

        public object Process(object target, IContext context)
        {
            context.GetInstance&lt;IEventAggregator&gt;().AddListener(target);
            return target;
        }

        public bool MatchesType(Type type)
        {
            return
                type.ImplementsInterfaceTemplate(typeof (IListener&lt;&gt;)) ||
                type.CanBeCastTo(typeof (ITestListener)) ||
                type.CanBeCastTo(typeof (ICloseable));
        }

        #endregion
    }
</pre>
<p><b>Conclusion</b></p>
<p>EventAggregation is one of the standard patterns in modern enterprise applications. I like the elegant way how Jeremy implemented this. However having spend some time with this in the past, I miss a functional part in his implementation: Type based subscriptions. Type based subscriptions can be really handy when you&#8217;re implementing PageFlows or state-ful MessageHandlers. Once a message is recieved the type is resolved by the container and the related handler method is called on the newly created type. I had them in my last application and liked them a lot. Maybe StoryTeller goes alternative routes to achive a similar effect. We&#8217;ll see as we proceed in the code . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/07/20/diving-into-the-storyteller-trunk-part-5-the-eventaggregator/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Diving into the StoryTeller trunk, Part 4: Registration of Generics</title>
		<link>http://www.bjoernrochel.de/2009/07/17/diving-into-the-storyteller-trunk-part-4-registration-of-generics/</link>
		<comments>http://www.bjoernrochel.de/2009/07/17/diving-into-the-storyteller-trunk-part-4-registration-of-generics/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 20:36:55 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[StoryTeller]]></category>
		<category><![CDATA[StructureMap]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=422</guid>
		<description><![CDATA[

I really like the way StructureMap automates the container registration. Part 1 already showed a lot of the convention based container registration mechanism. Today I would like to touch an aspect of registration which doesn&#8217;t really fit under the term &#34;convention over configuration&#34;, but is a really cool functionality non the less. For this post [...]]]></description>
			<content:encoded><![CDATA[<p></p>
<p>
I really like the way StructureMap automates the container registration. Part 1 already showed a lot of the convention based container registration mechanism. Today I would like to touch an aspect of registration which doesn&#8217;t really fit under the term &quot;convention over configuration&quot;, but is a really cool functionality non the less. For this post I would like to take a look at what you can do with generic types in StructureMap (taking you of course through some code parts of StoryTeller).
<p />
Let&#8217;s start with a look at the IScreenSubject interface in the StoryTeller trunk. This interface plays a very important role in the UI layer of StoryTeller. Its basic responsibility is the creation and the identification of a single screen. The whole topic will be part of later posts, so don&#8217;t be mad with me, if I don&#8217;t go into full detail here. What matters for the context of this post is that there is also an IScreenSubject&lt;T&gt; marker interface.   </p>
<pre class="brush: csharp">
public interface IScreenSubject
{
      bool Matches(IScreen screen);
      IScreen CreateScreen();
}   

//Marker interface
public interface IScreenSubject&lt;t&gt; : IScreenSubject { }
</pre>
<p>If you take a look at StoryTellers UserInterfaceRegistry class, the class containing all the StructureMap configuration, you&#8217;ll notice a method on the configuration expression with the name &quot;ConnectImplementationsToTypesClosing&quot; which takes a single open generic type as the parameter (The IScreenSubject&lt;&gt; type in the following snippet).   </p>
<pre class="brush: csharp">

public class UserInterfaceRegistry : Registry
{
     public UserInterfaceRegistry()
     {
           . . .
           Scan(x =&gt;
           {
                x.TheCallingAssembly();
                x.WithDefaultConventions();
                x.ConnectImplementationsToTypesClosing(typeof(IScreenSubject&lt;&gt;));
            });
            . . .
         }
      }
}
</pre>
<p>For those of you who haven&#8217;t heard of open and closed generic types: An open generic type is a generic type which doesn&#8217;t have his type parameters specified (for instance typeof(IListener&lt;&gt;)), while a closed generic type is a generic type which has his type parameters specified (for example typeof(IListener&lt;string&gt;)). </p>
<p />
So what&#8217;s the deal with those types?  StoryTeller has several implementations of the IScreenSubject&lt;T&gt; interface. The following snippet shows one of them. It has been a bit simplified for this post. What&#8217;s important here is that because this type closes the IScreenSubject&lt;T&gt; type with the TestScreen type, it is automatically registered in the container if it resides in one of the assemblies scanned by StructureMap.  </p>
<pre class="brush: csharp">

public class TestScreenSubject : IScreenSubject&lt;TestScreen&gt;
{
       private readonly IContainer _container;       

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

        #region IScreenSubject Members       

        public bool Matches(IScreen screen)
        {
                return screen is TestScreen;
        }       

        public IScreen CreateScreen()
        {
                return _container.GetInstance&lt;TestScreen&gt;();
        }       

        #endregion
}
</pre>
<p>Client code can access this instance after registration via   </p>
<pre class="brush: csharp">
//&lt;-- this will give you an TestScreenSubject instance
container.GetInstance&lt;IScreenSubject&lt;TestScreen&gt;&gt;();
</pre>
<p>What we&#8217;ve seen so far is how instances can be automatically registered for closed generic interfaces by StructureMap. However if we take a look at the TestScreenSubject class, isn&#8217;t there something which can be generalized and reused? In fact you can find the ScreenSubject&lt;SCREEN&gt; class in the StoryTeller which looks like a generalized version of it.  </p>
<pre class="brush: csharp">

public class ScreenSubject&lt;SCREEN&gt; : IScreenSubject where SCREEN : IScreen
{
         private readonly IContainer _container;       

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

         #region IScreenSubject Members       

         public bool Matches(IScreen screen)
         {
                 return screen is SCREEN;
         }       

         public IScreen CreateScreen()
         {
                  return _container.GetInstance&lt;SCREEN&gt;();
         }       

         #endregion
}
</pre>
<p>This class however isn&#8217;t automatically picked up by auto registration or one of the conventions. Besides that, notice that this is not an abstract class. So, using it as a base class in order to fit in the ConnectImplementationsToTypesClosing scheme is probably not really the main usage scenario for this class (although you could of course do it). What we can do instead is register this class as the default implementation for the IScreenSubject&lt;T&gt; interface. (SIDENOTE: StoryTeller doesn&#8217;t really use this so the rest of the post is more or less a  StructureMap feature demo <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> )   </p>
<pre class="brush: csharp">
public class UserInterfaceRegistry : Registry
{
       public UserInterfaceRegistry()
       {
             . . .
             For(typeof( IScreenSubject&lt;&gt;)).TheDefaultIsConcreteType(typeof(ScreenSubject&lt;&gt;));
             . . .
        }
}
</pre>
<p>Looks strange at first, but it&#8217;s a really handy thing once you&#8217;ve got used to it. Here&#8217;s an example how the container behaves after both TestScreenSubject (implicitly by ConnectAllTypeClosing) and ScreenSubject&lt;T&gt; (explicitly by For&#8230;) have been registered.  </p>
<pre class="brush: csharp">

//This will return an instance of the type TestScreenSubject
container.GetInstance&lt;IScreenSubject&lt;&lt;TestScreen&gt;&gt;();  

//This will return an instance of the ScreenSubject&lt;SomeOtherScreen&gt;
container.GetInstance&lt;IScreenSubject&lt;&lt;SomeOtherScreen&gt;&gt;();   
</pre>
<p>The container basically does this: If the requested closed generic type is directly implemented by a registered type (TestScreenSubject here) this type is resolved. On the other hand when the requested generic type is not directly implemented by any registered type, but an open generic type implementing the open version of the interface is registered (ScreenSubject&lt;&gt; here) the container will close that type and return an instance for it. AFAIK this is called &#8220;generic specialization&#8221;.   </p>
<p>A simple example where generic specialization is really handy: You want to implement validation. Therefore you create an IValidator&lt;T&gt; interface and an standard implementation Validator&lt;T&gt; for it which validates static rules based on attributes (string length, not null, etc). For one particular type you realize that this is not sufficient, because maybe you need some sort of catalog in order to validate correctly. With generic specialization you&#8217;re able to introduce this special case for the particular type very, very easily. Just follow the steps described in this post. From a clients perspective nothing changes . . .  </p>
<p>
<b>Conclusion</b>
</p>
<p>Generic specialization is one of the things I really love when using an IoC. It&#8217;s one of those areas where IoC imho really shines. To be fair, this ability is not StructureMap exclusive. Most of the other containers have it, too. However, I&#8217;m amazed how much fluff (or ceremony as Jeremy likes to say) can be cut from registration by StructureMap . . .   </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/07/17/diving-into-the-storyteller-trunk-part-4-registration-of-generics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
