<?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>Generation 5 &#187; Silverlight</title>
	<atom:link href="http://gen5.info/q/category/tools/silverlight/feed/" rel="self" type="application/rss+xml" />
	<link>http://gen5.info/q</link>
	<description>Towards Intelligent Systems</description>
	<lastBuildDate>Fri, 20 Aug 2010 19:43:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Subverting XAML: How To Inherit From Silverlight User Controls</title>
		<link>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/</link>
		<comments>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 20:31:21 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=188</guid>
		<description><![CDATA[The Problem Many Silverlighters use XAML to design the visual appearance of their applications.  A UserControl defined with XAML is a DependencyObject that has a complex lifecycle:  there&#8217;s typically a .xaml file,  a .xaml.cs file,  and a .xaml.g.cs file that is generated by visual studio. The .xaml.g.cs file is generated by Visual Studio,  and ensures [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://gen5.info/q/wp-content/uploads/2009/02/noxamlinheritance.png"><img style="float: right;" title="noxamlinheritance" src="http://gen5.info/q/wp-content/uploads/2009/02/noxamlinheritance.png" alt="" width="343" height="254" /></a>The Problem</h2>
<p>Many Silverlighters use XAML to design the visual appearance of their applications.  A UserControl defined with XAML is a <em>DependencyObject</em> that has a complex lifecycle:  there&#8217;s typically a .xaml file,  a .xaml.cs file,  and a .xaml.g.cs file that is generated by visual studio. The .xaml.g.cs file is generated by Visual Studio,  and ensures that objects defined in the XAML file correspond to fields in the object (so they are seen in intellisense and available to your c# code.)  The XAML file is re-read at runtime,  and drives a process that instantiates the actual objects defined in the XAML file &#8212; a program can compile just fine,  but fail during initialization if the XAML file is invalid or if you break any of the assumptions of the system.</p>
<p>XAML is a pretty neat system because it&#8217;s not tied to WPF or WPF/E.  It can be used to initialize any kind of object:  for instance,  it can be used to design workflows in asynchronous server applications based on Windows Workflow Foundation.</p>
<p>One problem with XAML,  however,  is that you cannot write controls that inherit from a UserControl that defined in XAML.  Visual Studio might compile the classes for you,  but they will fail to initialize at at runtime.  This is serious because it makes it impossible to create subclasses that let you make small changes to the appearance or behavior of a control.</p>
<p><span id="more-188"></span></p>
<h2>Should We Just Give Up?</h2>
<p>One approach is to give up on XAML.  Although Visual Studio encourages you to create UserControls with XAML,  there&#8217;s nothing to stop you from creating a new class file and writing something like</p>
<pre>class MyUserControl:UserControl {
      public MyUserControl {
      var innerPanel=new StackPanel();
      Content=innerPanel;
      innerPanel.Children.Add(new MyFirstVisualElement());
      innerPanel.Children.Add(new MySecondVisualElement());
      ...
}</pre>
<p>UserControls defined like this have no (fundamental) problems with inheritance,  since you&#8217;ve got complete control of the initialization process.  If it were up to me,  I&#8217;d write a lot of controls like this,  but I work on a team with people who design controls in XAML,  so I needed a better solution.</p>
<h2>Or Should We Just Cheat?</h2>
<p>If we still want to use XAML to define the appearance of a control,  we&#8217;ve got another option.  We can move the XAML into a control that is outside the inheritance hierarchy:  the XAML control is then contained inside another control which doesn&#8217;t have restrictions as to how it is used:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2009/02/cheatingxaml.png"><img class="aligncenter size-full wp-image-192" title="cheatingxaml" src="http://gen5.info/q/wp-content/uploads/2009/02/cheatingxaml.png" alt="" /></a></p>
<p>The <em>XamlPanelInnards.xaml.cs</em> code-behind is almost completely empty:  it contains only the constructor created by Visual Studio&#8217;s XAML designer.  <em>XamlPanel.cs</em> contains a protected member called <em>InnerControl</em> which is of type <em>XamlPanelInnards</em>.  <em>InnerControl</em> is initialized in the constructor of <em>XamlPanel</em>,  and is also assigned to the <em>Content</em> property of the <em>XamlPanel</em>,  to make it visible.  Everything that you&#8217;d ordinarily put in the code-behind <em>XamlPanelInnards.xaml.cs</em> goes into XamlPanel.cs,  which uses the <em>InnerControl</em> member to get access to the <em>internal</em> members defined by the XAML designer.</p>
<h2>Step-by-Step Refactoring</h2>
<p>Let&#8217;s imagine that we&#8217;ve got an existing <em>UserControl</em> implemented in XAML called the <em>XamlPanel</em>.  We&#8217;d like to subclass the <em>XamlPanel </em>so we can use it for multiple purposes.  We can do this by:</p>
<ol>
<li>Renaming <em>XamlPanel</em> to <em>OldXamlPanel</em>;  this renames both the *.xaml and *.xaml.cs files so we can have them to look at</li>
<li>Use Visual Studio to create a new &#8220;Silverlight User Control&#8221; called <em>XamlPanelInnards</em>.  This will have both a *.xaml and *.xaml.xs file</li>
<li>Copy the contents of OldXamlPanel.xaml to XamlPanelInnards.cs.  Edit the x:Class attribute of the &lt;UserControl&gt; element to reflect the new class name,  &#8220;XamlPanelInnards&#8221;</li>
<li>Use Visual Studio to create a new <strong>class</strong>,  called XamlPanel.cs.  Do not create a XamlPanel.xaml.cs file!</li>
<li>Copy the constructor,  methods,  fields and properties from the OldXamlPanel.xaml.cs file to the XamlPanel.cs file.</li>
<li>Create a new private field in XamlPanel.cs like
<pre>private XamlPanelInnards InnerControl;</pre>
</li>
<li>Now we modify the constructor,  so that it does something like this:
<pre>public XamlPanel() {
   InnerControl = new XamlPanelInnards();
   Content = InnerControl;
   ... remainder of the constructor ...
}</pre>
</li>
<li>Most likely you&#8217;ll have compilation errors in the XamlPanel.cs file because there are a lot of references to public fields that are now in the InnerControl.  You need to track these down,  and replace code that looks like
<pre>TitleTextBlock.Text="Some Title";</pre>
<p>with</p>
<pre>InnerControl.TitleTextBlock.Text="SomeTitle";</pre>
</li>
<li>Any event handler attachments done from the XAML file will fail to work (they&#8217;ll trigger an error when you load the application.)  You&#8217;ll need to convert
<pre>&lt;Button x:PressMe ... Click="PressMe_OnClick"&gt;</pre>
<p>in the XAML file to</p>
<pre>InnerControl.PressMe.Click += PressMe_OnClick</pre>
<p>in the constructor of XamlPanel.</li>
<li style="text-align: left;">UI Elements that are defined in XAML are public,  so there&#8217;s a good chance that other classes might expect UI Elements inside the XamlPanel to be accessable.  You&#8217;ve got some choices:  (a) make the InnerControl public and point those references to the InnerControl (yuck!),  (b) selectively add properties to XamlPanel to let outside classes access the elements that they need to access,  or (c) rethink the encapsulation so that other class don&#8217;t need direct access to the members of XamlPanelInnards.</li>
<li>There are a few special methods that are defined in DependencyObject and FrameworkElement that you&#8217;ll need to pay attention to.  For instance,  if your class uses FindName to look up elements dynamically,  you need to replace
<pre>FindName("Control"+controlNumber);</pre>
<p>with</p>
<pre>InnerControl.FindName("Control"+controlNumber);</pre>
</li>
</ol>
<p>So far this is a refactoring operation:  we&#8217;re left with a program that does what it already did,  but is organized differently.  Where can we go from here?</p>
<h2>Extending The XamlPanel</h2>
<p>At this point,  the XamlPanel is an ordinary UserControl class.  It&#8217;s initialization logic is self-sufficient,  so it can inherit (it doesn&#8217;t necessarily have to derive from UserControl) and be inherited from quite freely.</p>
<p>If we want to change the behavior of the XamlPanel,  for instance,  we could declare it abstract and leave certain methods (such as event handlers) abstract.  Alternately,  methods could be declared as virtual.</p>
<p>A number of methods exist to customize the appearance of XamlPanel:  since XamlPanel can see the objects inside XamlPanelInnards,  it can change colors,  image sources and text contents.  If you&#8217;re interested in adding additional graphical element to the Innards,  the innards can contain an empty StackPanel &#8212; children of XamlPanel can Add() something to the StackPanel in their constructors.</p>
<p>Note that you can still include a child XamlPanel inside a control defined in XAML by writing something like</p>
<pre>&lt;OURNAMESPACE:SecondXamlPanel x:Name="MyInstance"&gt;</pre>
<p>you&#8217;re free to make XamlPanel and it&#8217;s children configurable via the DependencyObject mechanisms.  The one thing that you lose is public access to the graphical element inside the StackPanelInnards:  many developers would think that this increase in encapsulation is a good thing,  but it may involve a change in the way you do things.</p>
<h2>Related articles</h2>
<p>The community at <a href="http://silverlight.net/">silverlight.net</a> has pointed me to a few other articles about XAML,  inheritance and configuring Custom XAML controls.</p>
<p>In a lavishly illustrated blog entry,  Amyo Kabir explains <a href="http://amyotech.spaces.live.com/blog/cns!4B03AA8222DC3C5E!226.entry">how to make a XAML-defined control inherit from a user-defined base class</a>.  It&#8217;s the converse of what I&#8217;m doing in this article,  but it&#8217;s also a powerful technique:  I&#8217;m using it right now to implement a number of Steps in a Wizard.</p>
<p>Note that Silverlight has mechanisms for creating <a href="http://www.silverlightshow.net/items/Creating-a-Silverlight-Custom-Control-The-Basics.aspx">Custom Controls</a>:  these are controls that use the DependencyObject mechanism to be configurable via XAML files that include them.  If you&#8217;re interested in customizing individual controls rather than customizing subclasses,  this is an option worth exploring.</p>
<h2>Conclusion</h2>
<p>XAML is a great system for configuring complex objects,  but you can&#8217;t inherit from a Silverlight class defined in XAML.  By using a containment relation instead of an inheritance relation,  we can push the XAML-configured class outside of our inheritance hierarchy,  allowing the container class to participate as we desire.  This way we can have both visual UI generation and the software engineering benefits of inheritance.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Zemified by Zemanta" href="http://reblog.zemanta.com/zemified/1309efe8-1c65-4657-8a29-aea199856afb/"><img class="zemanta-pixie-img" style="border: medium none ; float: right;" src="http://img.zemanta.com/reblog_e.png?x-id=1309efe8-1c65-4657-8a29-aea199856afb" alt="Reblog this post [with Zemanta]" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulate HTML Forms With Silverlight 2</title>
		<link>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/</link>
		<comments>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 22:17:30 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=164</guid>
		<description><![CDATA[Introduction Lately I&#8217;ve been working on a web application based on Silverlight 2.  The application uses a traditional web login system based on a cryptographically signed cookie.  In early development,  users logged in on an HTML page,  which would load a Silverlight application on successful login.  Users who didn&#8217;t have Silverlight installed would be asked [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/skippy/11865024/"><img class="size-full wp-image-161" style="float: right; margin: 5px" title="11865024_af61ae2358_m" src="http://gen5.info/q/wp-content/uploads/2009/01/11865024_af61ae2358_m.jpg" border="0" alt="Remote Control" width="180" height="240" /></a></p>
<h2>Introduction</h2>
<p>Lately I&#8217;ve been working on a web application based on Silverlight 2.  The application uses a traditional web login system based on a <a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fpdos.csail.mit.edu%2Fpapers%2Fwebauth%3Asec10.pdf&amp;ei=a493SdXUCuPetgfhhPmgBg&amp;usg=AFQjCNFt9lqlfx_ALls4BBI9IPax51wBpw&amp;sig2=QsCk70fmt9nJASYWb4Dp0g">cryptographically signed cookie</a>.  In early development,  users logged in on an HTML page,  which would load a Silverlight application on successful login.  Users who didn&#8217;t have Silverlight installed would be asked to install it after logging in,  rather than before.</p>
<p>Although it&#8217;s (sometimes) possible to determine what plug-ins a user has installed using Javascript,  the methods are dependent on the specific browser and the plug-ins.  We went for a simple and effective method:  make the login form a Silverlight application,  so that users would be prompted to install Silverlight before logging in.</p>
<p>Our solutionn  was to make the Silverlight application a drop-in replacement for the original HTML form.  The Silverlight application controls a hidden HTML form:  when a user hits the &#8220;Log In&#8221; buttonin the Silverlight application,  the application inserts the appropriate information into the HTML form and submits it.  This article describes the technique in detail.<span id="more-164"></span></p>
<h2>The HTML Form</h2>
<p>The HTML form is straightforward &#8212; the main thing that&#8217;s funky about it is that all of the controls are invisible,  since we don&#8217;t want users to see them or interact with them directly:</p>
<pre>[01] &lt;form id="loginForm" method="post" action=""&gt;
[02]     &lt;div class="loginError" id="loginError"&gt;
[03]        &lt;%= Server.HtmlEncode(errorCondition) %&gt;
[04]     &lt;/div&gt;
[05]     &lt;input type="hidden" name="username" id="usernameField"
[06]        value="&lt;%= Server.HtmlEncode(username) %&gt;" /&gt;
[07]     &lt;input type="hidden" name="password" id="passwordField"  /&gt;
[08] &lt;/form&gt;</pre>
<p>The CSS file for the form contains the following directive:</p>
<pre>[09] .loginError { display:none }</pre>
<p>to prevent the error message from being visible on the HTML page.</p>
<h2>Executing Javascript In Silverlight 2</h2>
<p>A Silverlight 2 application can execute Javascript using the <em>HtmlPage.Window.Eval() </em>method;  HtmlPage.Window is static,  so you can use it anywhere,  so long as you&#8217;re running in the UI thread.  Our simple application doesn&#8217;t do communication and doesn&#8217;t launch new threads,  so we don&#8217;t need to worry about threads.  We add a simple wrapper method to help the rest of the code flow off the tips of our fingers</p>
<pre>[10] using System.Windows.Browser
[11] ...
[12] namespace MyApplication {
[13] public partial class Page : UserControl {
[14]      ...
[15]        Object JsEval(string jsCode) {
[16]            return HtmlPage.Window.Eval(jsCode);
[17]        }</pre>
<p>Note that Visual Studio doesn&#8217;t put the <em>using</em> in by default,  so you&#8217;ll need to add it.  The application is really simple,   with just two event handlers and a little XAML to define the interface,  so it&#8217;s all in a single class,  the Page.xaml and Page.xaml.cs files created when I made the project in VIsual Studio.</p>
<p>Note that JsEval returns an Object,  so you can look at the return value of a javascript evaluation.  Numbers are returned as doubles and strings are returned as strings,  which can be quite useful.  References to HTML elements are returned as instances of the HtmlElement class.  HtmlElement has some useful methods,  such as GetAttribute() and SetAttribute(),  but I&#8217;ve found that I get more reliable results by writing snippets of Javascript code.</p>
<h2>Finding HTML Elements</h2>
<p>One practical is problem is how to find the HTML Elements on the page that you&#8217;d like to work with.  I&#8217;ve been spoiled by the $() function in Prototype and JQuery,  so I like to access HTML elements by id.  There isn&#8217;t a standard method to do this in all browser,  so I slipped the following snippet of Javascript into the document:</p>
<pre>[18]    function returnObjById(id) {
[19]        if (document.getElementById)
[20]            var returnVar = document.getElementById(id);
[21]        else if (document.all)
[22]            var returnVar = document.all[id];
[23]        else if (document.layers)
[24]            var returnVar = document.layers[id];
[25]        return returnVar;
[26]    }</pre>
<p>(code snippet courtesy of <a href="http://www.netlobo.com/javascript_get_element_id.html">NetLobo</a>)</p>
<p>I wrote a few convenience methods in C# inside my Page class:</p>
<pre>[27]   String IdFetchScript(string elementId) {
[28]        return String.Format("returnObjById('{0}')", elementId);
[29]   }
[30]
[31]   HtmlElement FetchHtmlElement(string elementId) {
[32]        return (HtmlElement)JsEval(IdFetchScript(elementId));
[33]   }</pre>
<h2>Manipulating HTML Elements</h2>
<p>At this point you can do anything that can be done in Javascript.  That said,  all I need is a few methods to get information in and out of the form:</p>
<pre>[34]       string GetTextInElement(string elementId) {
[35]           HtmlElement e = FetchHtmlElement(elementId);
[36]           if (e == null)
[37]               return "";
[38]
[39]           return (string)JsEval(IdFetchScript(elementId) + ".innerHTML");
[40]       }
[41]
[42]       void Set(string fieldId, string value) {
[43]            HtmlElement e = FetchHtmlElement(fieldId);
[44]            e.SetAttribute("value", value);
[45]       }
[46]
[47]       string GetFormFieldValue(string fieldId) {
[48]            return (string) JsEval(IdFetchScript(fieldId)+".value");
[49]       }
[50]
[51]       void SubmitForm(string formId) {
[52]            JsEval(IdFetchScript(formId) + ".submit()");
[53]       }</pre>
<p>Isolating the Javascript into a set of helper methods helps make the code maintainable:  these methods are usable by a C#er who isn&#8217;t a Javascript expert &#8212; if we discover problems with cross-browser compatibility,  we can fix them in a single place.</p>
<h2>Putting it all together</h2>
<p>A little bit of code in the constructor loads form information into the application:</p>
<pre>[54]        public Page() {
[55]            ...
[56]            LoginButton.Click += LoginButton_Click;
[57]            UsernameInput.Text = GetFormFieldValue("usernameField");
[58]            ErrorMessage.Text = GetTextInElement("loginError");
[59]         }</pre>
<p>The LoginButton_Click event handler populates the invisible HTML form and submits it:</p>
<pre>[60]      void LoginButton_Click(object sender, RoutedEventArgs e) {
[61]           SetFormFieldValue("usernameField", UsernameInput.Text);
[62]           SetFormFieldValue("passwordField", PasswordInput.Password);
[63]           SubmitForm("loginForm");</pre>
<pre>[64]       }</pre>
<h2>Conclusion</h2>
<p>Although Silverlight 2 is capable of direct http communication with a web server,  sometimes it&#8217;s convenient for a Silverlight application to directly manipulate HTML forms.   This article presents sample source code that simplifies that task.</p>
<p><strong>P.S.</strong> A commenter on the Silverlight.net forums pointed me to <a href="http://timheuer.com/blog/archive/2008/03/09/calling-javascript-functions-from-silverlight-2.aspx">another article by Tim Heuer</a> that describes alternate methods for manipulating the DOM and calling Javascript functions.</p>
<p><small>(Thanks <a href="http://www.flickr.com/photos/skippy/">skippy</a> for the <a href="http://www.flickr.com/photos/skippy/11865024/">remote control image.</a>)</small></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f01%2f21%2fmanipulate-html-forms-with-silverlight-2%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f01%2f21%2fmanipulate-html-forms-with-silverlight-2%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Converting A Synchronous Program Into An Asynchronous Program</title>
		<link>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/</link>
		<comments>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 17:58:48 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=49</guid>
		<description><![CDATA[Introduction One of the challenges in writing programs in today&#8217;s RIA environments  (Javascript, Flex, Silverlight and GWT)  is expressing the flow of control between multiple asynchronous XHR calls.  A &#8220;one-click-one-XHR&#8221; policy is often best,  but you don&#8217;t always have control over your client-server protocols.  A program that&#8217;s simple to read as a synchronous program can [...]]]></description>
			<content:encoded><![CDATA[<h2 style="text-align: left;">Introduction</h2>
<p style="text-align: left;">One of the challenges in writing programs in today&#8217;s RIA environments  (Javascript, Flex, Silverlight and GWT)  is expressing the flow of control between multiple asynchronous XHR calls.  A &#8220;<a href="http://gen5.info/q/2008/03/27/managing-concurrency-with-asynchronous-http-requests/">one-click-one-XHR</a>&#8221; policy is often best,  but you don&#8217;t always have control over your client-server protocols.  A program that&#8217;s simple to read as a synchronous program can become a tangle of subroutines when it&#8217;s broken up into a number of callback functions.  One answer is <em>program translation</em>:  to manually or automatically convert a synchronous program into an asynchronous program:  starting from the theoretical foundation,  this article talks about a few ways of doing that.</p>
<p style="text-align: left;"><a href="http://www.thibaudlopez.net/">Thibaud Lopez Schneider</a> sent me a link to an interesting paper he wrote,  titled &#8220;<a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Writing Effective Asynchronous XmlHttpRequests</a>.&#8221;  He presents an informal proof that you can take a program that uses synchronous function calls and common control structures such as <em>if-else</em> and <em>do-while</em>,  and transform it a program that calls the functions asynchronously.  In simple language,  it gives a blueprint for implementing arbitrary control flow in code that uses asynchronous XmlHttpRequests.</p>
<p style="text-align: left;">In this article,  I work a simple example from Thibaud&#8217;s paper and talk about four software tools that automated the conversion of conventional control flows to asynchronous programming.  One tool,  the <a href="http://en.wikipedia.org/wiki/Windows_Workflow_Foundation">Windows Workflow Foundation,</a> lets us compose long-running applications out of a collection of asynchronous <em>Activity</em> objects.  Another two tools are<em> </em><a href="http://chumsley.org/jwacs/">jwacs</a> and <a href="http://www.neilmix.com/narrativejs/doc/">Narrative Javascript</a>,  open-source   translators that translated pseudo-blocking programs in a modified dialect of JavaScript into an asynchronous program in ordinary JavaScript that runs in your browser.</p>
<p style="text-align: left;"><span id="more-49"></span></p>
<p style="text-align: left;">
<h2 style="text-align: left;">A simple example: Sequential Execution</h2>
<p style="text-align: left;">I&#8217;m going to lift a simple example from <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Thibaud&#8217;s paper</a>,  the case of sequential execution.  Imagine that we want to write a function <em>f()</em>,  that follows the following logic</p>
<pre style="text-align: left;">[01] function f() {
[02]    ... pre-processing ...
[03]    result1=MakeRequest1(argument1);
[04]    ... think about result1 ...
[05]    result2=MakeRequest2(argument2);
[06]    ... think about result2 ...
[07]    result3=MakeRequest3(argument3);
[08]    ... think about result3 ...
[09]    return finalResult;
[10] }</pre>
<p style="text-align: left;">where functions of the form <em>MakeRequestN</em> are ordinary synchronous functions.  If,  however,  we were working in an environment like JavaScript,  GWT,  Flex,  or Silverlight,  server requests are asynchronous,  so we&#8217;ve only got functions like:</p>
<pre>[11] function BeginMakeRequestN(argument1, callbackFunction);</pre>
<p style="text-align: left;">It&#8217;s no longer possible to express a sequence of related requests as a single function,  instead we need to transform f() into a series of functions,  like so</p>
<pre style="text-align: left;">[12] function f(callbackFunction) {
[13]   ... pre-processing ...
[14]   BeginMakeRequest1(argument,f1);
[15] }
[16]
[17] function f1(result1) {
[18]    ... think about result1 ...
[19]    BeginMakeRequest2(argument2,f2);
[20] }
[21]
[22] function f2(result2) {
[23]    ... think about result2 ...
[24]    BeginMakeRequest3(argument3,f3);
[25] }
[26]
[27] function f3(result3) {
[28]   ... think about result 3 ...
[29]   callbackFunction(finalResult);
[30] }</pre>
<p style="text-align: left;">My example differs from the example of on page 19 of <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Thibaud&#8217;s paper</a> in a few ways&#8230;  In particular,  I&#8217;ve added the <em>callbackFunction</em> that <em>f()</em> uses to &#8220;return&#8221; a result to the program that calls it.  Here the <em>callbackFunction</em> lives in a scope that&#8217;s shared by all of the <em>fN</em> functions,  so it&#8217;s available in <em>f3</em>.  I&#8217;ve found that when you&#8217;re applying Thibuad&#8217;s kind of thinking,  it&#8217;s useful for <em>f()</em> to correspond to an object,   of which the <em>fN()</em> functions are methods. [<a href="http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/">1</a>] [<a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">2</a>] [<a href="http://gen5.info/q/2008/04/11/the-asynchronous-command-pattern/">3</a>]</p>
<p style="text-align: left;">Thibaud also works the implementation of <em>if-then-else</em>,  <em>switch</em>,  <em>for</em>,  <em>do-while</em>,  <em>parallel-do</em> and other common patterns &#8212; <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">read his paper</a>!</p>
<h2 style="text-align: left;">What next?</h2>
<p>There are things missing from Thibaud&#8217;s current draft:  for instance,  he doesn&#8217;t consider how to implement exception handling in asynchronous applications,  although it&#8217;s <a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">quite possible to do</a>.</p>
<p>Thinking about things systematically helps you do things by hand,  but it really comes into it&#8217;s own when we use systematic thinking to develop tools.  I can imagine two kinds of tools based on Thibaud&#8217;s ideas:</p>
<ol>
<li>Specialized languages for expressing asynchronous flows,  and</li>
<li>Compilers that transform synchronous programs to asynchronous programs</li>
</ol>
<h2>Windows Workflow Foundation</h2>
<p>Windows Workflow Foundation is an example of the first approach.</p>
<p>Although it&#8217;s not designed for use in asynchronous RIA&#8217;s,  Microsoft&#8217;s <a href="http://joeon.net/post/2008/02/Windows-Workflow-Foundation-Tutorial-Series.aspx">Windows Workflow Foundation </a>is an new approach to writing reactive programs.   Unfortunately,  like a lot of enterprise technologies,  WWF is surrounded by a lot of hype that obscures a number of worthwhile ideas:  the book <a href="http://www.amazon.com/gp/product/0321399838/103-7142849-0321425?ie=UTF8&amp;tag=honeymediasys-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0321399838">Essential Windows Workflow Foundation</a> by Shukla and Schmidt is a lucid explanation of the principles behind it.  It&#8217;s good reading even if you hate Microsoft and would never use a Microsoft product,  because it could inspire you to implement something similar in your favorite environment.  (I know someone who&#8217;s writing a webcrawler in PHP based on a similar approach)</p>
<p>What does it do?</p>
<p>In WWF,  you create an asynchronous program by composing a set of asynchronous <em>Activities</em>.  Ultimately your program is a tree of <em>Activity</em> objects that you can assemble any way you like,  but typically you&#8217;d build them with a XAML (XML) file that might look like</p>
<pre>[31] &lt;Interleave x:Name="i1"&gt;
[32]    &lt;Sequence x:Name="s1"&gt;
[33]       &lt;ReadLine x:Name="r1" /&gt;
[34]       &lt;WriteLine x:Name="w1"
[35]          Text="{wf:ActivityBind r1,path=Text}" /&gt;
[36]       &lt;ReadLine x:Name="r2" /&gt;
[37]       &lt;WriteLine x:Name="w2"
[38]          Text="{wf:ActivityBind r2,path=Text}" /&gt;
[39]    &lt;/Sequence&gt;
[40]    &lt;Sequence x:Name="s2"&gt;
[41]       &lt;ReadLine x:Name="r3" /&gt;
[42]       &lt;WriteLine x:Name="w3"
[43]          Text="{wf:ActivityBind r3,path=Text}" /&gt;
[44]       &lt;ReadLine x:Name="r4" /&gt;
[45]       &lt;WriteLine x:Name="w4"
[46]          Text="{wf:ActivityBind r4,path=Text}" /&gt;
[47]    &lt;/Sequence&gt;
[48] &lt;/Interleave&gt;</pre>
<p>(The above example is based on Listing 3.18 on Page 98 of Shukla and Schmidt,  with some namespace declarations removed for clarity)</p>
<p>This defines a flow of execution that looks like:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/08/wwfdiagram.png"><img class="alignnone size-full wp-image-60" title="wwfdiagram" src="http://gen5.info/q/wp-content/uploads/2008/08/wwfdiagram.png" alt="" width="485" height="244" /></a></p>
<p>The <em>&lt;Interleave&gt;</em> activity causes two <em>&lt;Sequence&gt;</em> activities to run simultaneously.  Each <em>&lt;Sequence&gt;</em>,  in turn,  sequentially executes two alternating pairs of <em>&lt;ReadLine&gt;</em> and <em>&lt;WriteLine&gt;</em> activities.  Note that the attribute values that look like <em>{wf: ActivityBind r3,path=Text}</em> wire out the output of a <em>&lt;ReadLine&gt;</em> activity to the input of a <em>&lt;WriteLine&gt;</em> activity.</p>
<p>Note that <em>&lt;Interleave&gt;</em>,  <em>&lt;Sequence&gt;</em>,  <em>&lt;ReadLine&gt;</em> and <em>&lt;WriteLine&gt;</em> are all asynchronous activities defined by classes <em>Interleave</em>, <em>Sequence</em>, <em>ReadLine</em> And <em>WriteLine</em> that all implement <em>Activity</em>.   An activity can invoke other activities,  so it&#8217;s possible to create new control structures.  Activities can wait for things to happen in the outside world (such as a web request or an email message) by listening to a queue.   WWF also defines an elaborate model for error handling.</p>
<p>Although other uses are possible,   WWF is intended for the implementation of server applications implementations that implement workflows.  Imagine,  for instance,  a college applications system,  which must wait for a number of forms from the outside,  such as</p>
<ul>
<li>an application,</li>
<li>standardized test scores, and</li>
<li>letters of reccomendation</li>
</ul>
<p>and that needs to solicit internal input from</p>
<ul>
<li>an initial screening committee,</li>
<li>the faculty of individual departments,  and</li>
<li>the development office.</li>
</ul>
<p>The state of a workflow can be serialized to a database,   so the workflow can be something that takes place over a long time,  such as months or weeks &#8212; multiple instances of the workflow can exist at the same time.</p>
<p>WWF looks like a fun environment to program for,  but I don&#8217;t know if I&#8217;d trust it for a real business application.  Why?  I&#8217;ve been building this sort of application for years using relational databases,  I know that it&#8217;s possible to handle the maintenance situations that occur in real life with a relational representation:  both the little tweaks you need to make to a production system from time to time,  and the more major changes required when your process changes.  Systems based on object serialization,  such as WWF,   tend to have trouble when you need to change the definition of objects over time.</p>
<p>I can say,  however,  that the <a href="http://www.amazon.com/gp/product/0321399838/103-7142849-0321425?ie=UTF8&amp;tag=honeymediasys-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0321399838">Shukla and Schmidt</a> book is so clear that an ambitious programmer could understand enough of the ideas behind WWF to develop a similar framework that&#8217;s specialized for developing asynchronous RIAs in Javascript,  Java,  or C# pretty quickly.   Read it!</p>
<h2>Transforming Javascript and Other Languages</h2>
<p>Another line of attack on asynchronous programming is the creation of compilers and translators that transform a synchronous program into a synchronous program.  This is particularly popular in Javascript,  where open-source tools such as <a href="http://chumsley.org/jwacs/demos.html">jwacs</a> (Javascript With Advanced Continuation Syntax) let you write code like this:</p>
<pre>[49] function main() {
[50]    document.getElementById('contentDiv').innerHTML =
[51]      '&lt;pre&gt;'
[52]      + JwacsLib.fetchData('GET', 'dataRows.txt')
[53]      + '&lt;/pre&gt;';
[54] }</pre>
<p>Jwacs adds four new keywords to the Javascript language:  internally,  it applies transformations like the ones in the Thibaud paper.  Although it looks as if the call to <em>JwacsLib.fetchData</em> blocks,  in reality,  it splits the <em>main()</em> function into two halves,  executing the function by a form of cooperative multitasking.</p>
<p><a href="http://neilmix.com/narrativejs/doc/index.html">Narrative Javascript</a> is a similar open-source translator that adds -&gt;,  a &#8220;yielding&#8221; operator to Javascript.  This signals the translator to split the enclosing function,  and works for timer and UI event callbacks as well as XHR.  Therefore,  it&#8217;s possible to write a pseudo-blocking sleep() function like:</p>
<pre>[55] function sleep(millis) {
[56]    var notifier = new EventNotifier();
[57]    setTimeout(notifier, millis);
[58]    notifier.wait-&gt;();
[59] }</pre>
<p>Narrative Javascript doesn&#8217;t remember the special nature of the the sleep() function,  so you need to call it with the yielding operator too.  With it,  you can animate an element like so:</p>
<pre>[60] for (var i = 0; i &lt; frameCount - 1; i++) {
[61]    var nextValue = startValue + (jumpSize * i);
[62]    element.style[property] = nextValue + "px";
[63]    sleep-&gt;(frequency);
[64] }</pre>
<p>You can use the yielding operator to wait on user interface events as well.  If you first define</p>
<pre>[65] function waitForClick(element) {
[66]    var notifier = new EventNotifier();
[67]    element.onclick = notifier;
[68]    notifier.wait-&gt;();
[69] }</pre>
<p>you can call it with the yielding operator to wait for a button press</p>
<pre>[70] theButton.innerHTML = "go right";
[71] waitForClick-&gt;(theButton);
[72] theButton.innerHTML = "--&gt;";
[73] ... continue animation ...</pre>
<p>The <a href="http://rifers.org/wiki/display/RIFE/Web+continuations">RIFE Continuation Engine</a> implements something quite similar in Java,  but it translates at the bytecode level instead of at the source code level:  it aims to transform the server-side of web applications,  rather than the client,  by allowing the execution of a function to span two separate http requests.</p>
<h2>Conclusion</h2>
<p>It&#8217;s possible to systematically transform a function that&#8217;s written in terms of conventional control structures and synchronous function calls into a collection of functions that performs the same logic using asynchronous function calls.   A paper by <a href="http://www.thibaudlopez.net/">Thibaud Lopez Schneider</a> points the way,  and is immediately useful for RIA programmers that need to convert conventional control structures in their head into asynchronous code.</p>
<p>A longer-term strategy is to develop frameworks and languages that make it easier to express desired control flows for asynchronous program.  The Windows Workflow Foundation from Microsoft is a fascinating attempt to create a specialized language for assembling asynchronous programs from a collection of <em>Activity</em> objects.  <a href="http://chumsley.org/jwacs/demos.html">jwacs</a> and <a href="http://neilmix.com/narrativejs/doc/index.html">Narrative Javascript</a> are bold attempts to extend the Javascript language so that people can express asynchronous logic as pseudo-threaded programs.  The <a href="http://rifers.org/wiki/display/RIFE/Web+continuations">RIFE Continuation Engine</a> demonstrates that this kind of behavior can be implemented in more static languages such as Java and C#.  Although none of these tools are ready for production-quality RIA work,  they may lead to something useful in the next few years.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Multiton Design Pattern</title>
		<link>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/</link>
		<comments>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 16:04:05 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=41</guid>
		<description><![CDATA[Introduction Many people have independely discovered a new design pattern, the &#8220;Multiton&#8221;, which, like the &#8220;Singleton&#8221; is an initialization pattern in the style of the Design Patterns book. Like the Singleton, the Multiton provides a method that controls the construction of a class: instead of maintaining a single copy of an object in an address [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Many people have independely discovered a new design pattern,  the &#8220;Multiton&#8221;,  which,  like the &#8220;Singleton&#8221; is an initialization pattern in the style of the Design Patterns book.  Like the Singleton,  the Multiton provides a method that controls the construction of a class:  instead of maintaining a single copy of an object in an address space,  the Multiton maintains a Dictionary that maps keys to unique objects.</p>
<p>The Multiton pattern can be used in systems that store persistent data in a back-end store,  such as a relational databases.  The Multiton pattern can be used to maintain a set of objects are mapped to objects (rows) in a persistent store:  it applies obviously to object-relational mapping systems,  and is also useful in asynchronous RIA&#8217;s,  which need to keep track of user interface elements that are interested in information from the server.</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/07/multitondiagram.png"><img title="multitondiagram" src="http://gen5.info/q/wp-content/uploads/2008/07/multitondiagram.png" alt="" /></a></p>
<p>An alternate use case of Mulitons,  seen in the &#8220;<a href="http://en.wikipedia.org/wiki/PureMVC">Multicore</a>&#8221; version of the PureMVC framework,  is the extension of the Singleton pattern to support multiple instances of a system in a single address space.</p>
<p>As useful as the Multiton pattern is,  this article explains how Multitons use references in a way that doesn&#8217;t work well with conventional garbage collection.  Multitons are a great choice when the number of Multitons is small,  but they may leak memory unacceptablely when more than a few thousand are created.  Future posts will describe patterns,  such as the Captive Multiton,  that provide the same capabilities with more scalable memory management &#8212; subscribe to our <a href="http://feeds.feedburner.com/Generation5">RSS feed</a> to keep informed.</p>
<h2><span id="more-41"></span>Use of a Multiton in An Asynchronous Application</h2>
<p>In our last article on <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">Model-View Separation in Asynchronous RIA&#8217;s</a>,   we used a Singleton object that represented an entire table in a relational database.  This object maintained a list of listerners that were interested in the contents of a table.  In this case,  the amount of information in the table was small,  and often used in the aggregate,   so retreiving a complete copy of the table was a reasonable level of granularity.  We could imagine a situation,  however,  where the number of records and size of the records is enough that we need to transfer records individually.  (This specific case is an outline of an implementation for Silverlight:  a GWT implementation would be similar &#8212; details specific to GWT are talked about in <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">a previous post</a>.)</p>
<p>Imagine,  for instance,  a <em>BlogPosting</em> object,  which represents a post in a blog,  which in turn has an integer primary key.  The BlogPosting object is a multiton,  so you&#8217;d write</p>
<pre>[01] var posting=BlogPosting.GetInstance(postId);</pre>
<p>to get the instance of <em>BlogPosting</em> that corresponds to <em>postId</em>.  Client objects can&#8217;t really write something like</p>
<pre>[02] TitleField.Text=posting.Title</pre>
<p>because the operation of retrieving text from an the server is asynchronous,  and won&#8217;t return in time to return a value,  either on line [01] or [02].  More reasonably,  a <em>BlogPostingViewer</em> can register itself against a <em>BlogPosting</em> instance so it will be notified when information is available about the blog posting.</p>
<pre>[03] public class BlogPostingViewer: UserControl,IBlogPostingListener {
[04]     protected int PostId;
[05]
[06]     public BlogPostViewer(int postId) {
[07]        PostId=postId;
[08]        BlogPosting.GetInstance(postId).AddListener(this);
[09]     }
[10]
[11]     public void Dispose() {
[12]        BlogPosting.GetInstance(postId).RemoveListener(this);
[13]        super.Dispose();
[14]     }</pre>
<p>This example shows a pattern usable in a Silverlight applicaton,  unlike the GWT style in the <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">model-view article</a>.  The <em>Dispose()</em> method will need to be called manually when the <em>BlogPostingViewer</em> is no longer needed,  since it will never be garbage collected so long as a reference to it inside the <em>BlogPosting</em> exists.  (This points to a general risk of memory leaks with Multitons that we&#8217;ll talk about later.)  This problem can be addre</p>
<p>The <em>BlogPostingViewer</em> goes on to implement the <em>IBlogPostingListener</em> interface,  updating the visual appearance of the user interface to reflect information from the UI:</p>
<pre>[15]     public void UpdatePosting(BlogPostingData d) {
[16]         if (d==null) {
[17]            ClearUserInterface();   // user-defined method blanks out UI
[18]            return
[19]         }
[20]         TitleField.Text=d.Title;
[21]         ...
[22]     }
}</pre>
<p>We assume that <em>BlogPostingData</em> represents the state of the <em>BlogPosting</em> at a moment in time,  distinct from the <em>BlogPosting</em>,  which represents the <em>BlogPosting</em> as a persistent object.  <em>BlogPostingData</em> might (roughly) correspond to the the columns of a relational table and look something like:</p>
<pre>[23] public class BlogPostingData {
[24]    public string Title { get; set;}
[25]    public Contributor Author { get; set; }
[26]    public string Body { get; set;}
[27]    public Category[] AssociatedCategories { get; set;}
[28]    ...
[29] }</pre>
<p>We could then add a <em>BlogPostingViewer</em> to the user interface and schedule it&#8217;s initialization by writing</p>
<pre>[30] var viewer=new BlogPostingViewer(PostId);
[31] OuterControl.Children.Add(viewer);
[32] BlogPosting.GetInstance(PostId).Fetch();</pre>
<p>Note that line [32] tells the <em>BlogPosting</em> instance to retreive a copy of the posting from the server (an instance of <em>BlogPostingData</em>) and call <em>UpdatePosting()</em> on all of the listeners.  Therefore,  there will be a time between line [30] and the time when the async call started on line [32] gets back when the <em>BlogPostingViewer</em> is empty (not initialized with <em>BlogPostingData</em>.)  Therfore,  the <em>BlogPostingViewer</em> must be designed so that nothing bad happens when it&#8217;s in that state:  it has to show something reasonable to user and not crash the app if the user clicks a button that isn&#8217;t ready yet.</p>
<p>(In a more developed application,  the <em>BlogPosting</em> could keep a cache of the latest <em>BlogPostingData</em>:  this could improve responsiveness by updating the <em>BlogPostingViewer</em> at the moment it registers,  or by doing a timestamp or checksum stamp against the server to reduce the bandwidth requirements of a <em>Fetch()</em>,  just watch out for the <a href="http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/">unintended consequences of multiple code paths</a>.)</p>
<h2>Implementing a Muliton</h2>
<p>Here&#8217;s an implementation of a Multiton in C# that&#8217;s not too different from the <a href="http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/">Java implementation from Wikipedia</a>.</p>
<pre>class BlogPosting {
    #region Initialization
    private static readonly Dictionary&lt;int,BlogPosting&gt; _Instances =
       new Dictionary&lt;int,BlogPosting&gt;();

    private BlogPosting(int key) {
        ... construct the object ...
    }

    public static BlogPosting GetInstance(int key) {
        lock(_Instances) {
            BlogPosting instance;
            if (_Instances.TryGetValue(key,out instance)) {
                return instance;
            }</pre>
<pre>            instance = new BlogPosting(key);
            _Instances.Add(key, instance);
            return instance;
        }
    }
    #endregion

    ... the rest of the class ...

}</pre>
<p>I&#8217;m pretty sure that a  version of this could be created in C# with slightly sweeter syntax that would look like</p>
<p>BlogPosting.Instance[postId]</p>
<p>but this doesn&#8217;t address the weak implementation of  static inheritence in many popular languages that requires us to cut-and-paste roughly 20 lines of code for each Multiton class,  rather than being able to reuse inheritence logic.  The Ruby Applications Library,  on the other hand,  contains a <a href="http://raa.ruby-lang.org/project/multiton/">Multiton</a> class that can be used to bolt Multiton behavior onto a class.  It would be interesting to see what could be accomplished with PHP 5.3&#8242;s <a href="http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html">late static binding</a>.</p>
<h2>Multitons And Memory Leaks</h2>
<p>Multitons,  unfortunately,  don&#8217;t interact well with garbage collectors.  Once a Multiton is created,  the static <em>_Instances</em> array will maintain a reference to every Multiton in the system,  so that Multitons won&#8217;t be collected,  even if  no active references exist.</p>
<p>You might think you could manually remove Multitons from the <em>_Instances</em> list,  but this won&#8217;t be entirely reliable.  In the case above,  each <em>BlogPosting </em>maintains a list of <em>IBlogPostingListeners</em>.  You could,  in principle,  scavenge <em>BlogPostings</em> with an empty set of listerners,  but that doesn&#8217;t stop a class from squirreling away a copy of a <em>BlogPosting</em> that will later conflict with a new BlogPosting that somebody creates by using <em>BlogPosting.GetInstance()</em>.</p>
<p><em>WeakReferences</em>,  as available in dot-Net and the full Java platform (as opposed to GWT),  are not an answer to this problem,  because references work backwards in this case:  a <em>BlogPosting</em> is collectable if (i) no references to the <em>BlogPosting</em> exist outside the <em>_Instances</em> array,  and (ii) a <em>BlogPosting </em>doesn&#8217;t hold references to other objects that may need to be updated in the future.</p>
<p>The severity of this issue depends on the number of Multitons created and the size of the Mulitons.  If the granularity of Multitons is coarse,  and you&#8217;ll only create five of them,  there&#8217;s no problem.  1000 Multitons that each consume 1 kilobyte will consume about a megabyte of RAM,  which is inconsequential for most applications these days.  However,  this amounts to a scaling issue:  an application that works fine when it creates 50 Mulitons could break down when it creates 50,000.</p>
<p>One answer to this problem is to restrict access to Muliton so that:  (i) references to Multitons can&#8217;t be saved by arbitrary objects and (ii) manages Multitons with a kind of reversed reference count,  so that Multitons are discared when they no longer hold useful informaton.  I call this a <em>Captive Multiton</em>,  and this will be the subject of our next exciting episode:  <a href="http://feeds.feedburner.com/Generation5">subscribe to our RSS feed </a>so you won&#8217;t miss it.</p>
<h2>More Information About Multitons</h2>
<p>So far as I can tell,  Multitons have been independently discovered by many developers in recent years.  I used Multitons (I called them &#8220;Parameterized Singleons&#8221;) in the manner above in a GWT application that I developed in summer 2007.  <a href="http://en.wikipedia.org/wiki/PureMVC">The PureMVC Framework uses Multitons</a> to allow multiple instances of the framework to exist in an address space.   A <a href="http://raa.ruby-lang.org/project/multiton/">reusable Multiton implementation</a> exists in Ruby.</p>
<h2>Conclusion</h2>
<p>The Muliton Pattern is an initialization pattern in the sense defined in the notorious &#8220;Design Patterns&#8221; Book.  Mulitons are like Singletons in that they use static methods to control access to a private constructor,  but instead of maintaining a single copy of an object in an address space,  a Multiton maintains a mapping from key values to objects.  A number of uses are emerging for mulitons:  (i) Multitons are useful when we want to use something like the Singleton pattern,  but support multiple named instances of a system in an an address space and (ii) Multitons can be a useful representation of an object in a persistent store,  such as a relational database.  Multitons,  however,  are not collected properly by conventional garbage collectors:  this is harmless for applications that create a small number of mulitons,  but poses a scaling problem when Multitons are used to represent a large number of objects of fine granularity &#8212; a future posting will introduce a Captive Multiton that solves this problem:  <a href="http://feeds.feedburner.com/Generation5">subscribe to our RSS feed</a> to follow this developing story.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f25%2fthe-multiton-design-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f25%2fthe-multiton-design-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Role Of The Model in Silverlight, GWT and Javascript</title>
		<link>http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/</link>
		<comments>http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 19:00:18 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=35</guid>
		<description><![CDATA[Introduction When people start developing RIA&#8217;s in environments such as Silverlight, GWT, Flex and plain JavaScript, they often write asynchronous communication callbacks in an unstructured manner, putting them wherever is convenient &#8212; often in an instance member of a user interface component (Silverlight and GWT) or in a closure or global function (JavaScript.) Several problems [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>When people start developing RIA&#8217;s in environments such as Silverlight,  GWT,  Flex and plain JavaScript,  they often write asynchronous communication callbacks in an unstructured manner,  putting them wherever is convenient &#8212; often in an instance member of a user interface component (Silverlight and GWT) or in a closure or global function (JavaScript.)</p>
<p>Several problems almost invariably occur as applications become more complex that force the development of an architecture that decouples communication event handlers from the user interface:  a straightforward solution is to create a model layer that&#8217;s responsible for notifying interested user interface components about data updates.</p>
<p>This article uses a simple example application to show how a first-generation approach to data updates breaks down and how introducing a model-view split makes for a reliable and maintainable application.</p>
<p>(This is one of a series of articles on RIA architecture:  subscribe to the <a href="http://feeds.feedburner.com/Generation5">Gen5 RSS feed</a> for future installments.)</p>
<h2>Example Application: Blogging And The Category Dropdown</h2>
<p>Imagine a blogging application that works like the WordPress blog used on this site.  This application consists of a number of forms,  one of which is used to write a new post:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/07/demoapplication2.png"><img class="alignnone size-full wp-image-40" title="demoapplication2" src="http://gen5.info/q/wp-content/uploads/2008/07/demoapplication2.png" alt="" width="500" height="202" /></a></p>
<p>This form lets you fill out two text fields:  a title and the body of the post.  It also contains a dropdown list of categories,  and gives you the option of adding a new category.  Categories are represented (server-side) in a table in a relational database that looks like:</p>
<pre>[01] CREATE TABLE categoryList (
[02]     id                 integer primary key auto_increment,
[03]     name               varchar(255)
[04] );<span id="more-35"></span></pre>
<p>Adding a category to the database requires a call to the server that adds a row to the database and returns the new category list,  which is then used to update the dropdown list.  I&#8217;ll show you samples of the app in a pseudocode in an imaginary environment which combines the best of Silverlight and GWT.  First we initialize the form and set an event handler that&#8217;s called when somebody clicks on the <em>AddCategoryButton</em>:</p>
<pre>[05] class CreatePostForm {
[06]    protected TextBox Title;
[07]    protected ListBox Category;
[08]    protected TextBox AddCategoryName;
[09]    protected Button  AddCategoryButton;
[10]    protected RichTextArea Body;
[11]    protected Button  Submit;
[12]
[13]    public CreatePostForm() {
[14]        ... initialize and lay out UI elements ...
[15]
[16]        AddCategoryButton.OnClick += AddCategoryButton_OnClick;
[17]
[18]        ... finish construction ...
[19]    }</pre>
<p>Leaving out error handling and other details,  the job of the event handler is to pass the name of the new category to the server.  The event handler is defined as an instance method of <em>CreatePostForm</em>:</p>
<pre>[20]    protected void AddCategoryButton_OnClick {
[21]        Server.Instance.AddCategory(AddCategoryName.Text,AddCategory_Completed)
[22]    }</pre>
<p>The <em>AddCategory</em> RPC call is defined on a Singleton called <em>Server</em>,  and takes two arguments:  (1) a string with the name of the new category,  and (2) a reference to to the callback function that gets called when the RPC call is complete.   The callback,  <em>AddCategory_Completed</em>,  is also an instance method:</p>
<pre>[23]     protected void AddCategory_Completed(List&lt;ListBoxItem&gt; items) {
[24]            Category.Items = items;
[25]     }</pre>
<p><em>ListBoxItem</em> is a class that represents a single row in a ListBox,  which has properties <em>ListBox.Id</em> and <em>ListBox.Name</em>.  This is simple and straightforward code,  and it ought to maintainable,  right?</p>
<p>Let&#8217;s see</p>
<h2>The Naive Implementation Adapts</h2>
<p>Well,  when we finish writing the class,  we notice the first problem &#8211; a minor problem.  There are two buttons on the form,  so we need two event handlers and two callback functions.  As a UI class gets complicated,  it can accumulate quite a few callback functions,  and it can get tricky keeping track of them all.  Careful naming,  code organization,  and the use of <em>#region </em>in C# can help organize the code,  but it&#8217;s easy to build UI controls that have tens of methods in which we can get lost.</p>
<p>Over time,  we&#8217;ll add more forms to the app,  and pretty soon we&#8217;ll add another form that has a category list:  perhaps this a form used by administrators to search for posts:  let&#8217;s call it <em>AdminSearchForm</em>.   <em>AdminSearchForm</em> also contains a <em>Listbox</em> called <em>Category</em>.  It&#8217;s a protected field of <em>AdminSearchForm</em>,  but we need to update it when the administrator adds a new category.   It seems reasonable to add a public method to AdminSearchForm</p>
<pre>[26] public class AdminSearchForm {
[27]     ...
[28]     protected ListBox Categories;
[29]     ...
[30]     public void UpdateCategoryList(List&lt;ListBoxItem&gt; items) {
[31]       Categories.Items=items;
[32]     }
[33] }</pre>
<p>Now we update the <em>AddCategory_Completed</em> function so it updates the <em>AdminSearchForm</em>:</p>
<pre>[34] public class CreatePostForm {
[35]    ...
[36]    protected void AddCategory_Completed(List&lt;ListBoxItems&gt; items) {
[37]       Categories.Items=items;
[38]       App.Instance.MainTabPanel.AdminSearchForm.UpdateCategoryList(items);
[39]    }
[40] }</pre>
<p>Not too bad,  eh?  just four more lines of transparent code to update <em>AdminSearchForm</em>,   even if line [38] has a rather ugly coupling to the detailed structure of the application.</p>
<h2>The Naive Implementation Breaks Down</h2>
<p>Over the next few weeks,  we add a few more dropdown lists to the application,  we keep doing the same thing,  and it&#8217;s fine for a while.  Then we start running into problems:</p>
<ol>
<li>We can&#8217;t reuse <em>CreatePostForm</em> to make different versions of the application,  because it contains a hard-coded list of all the dropdown lists in the application.</li>
<li>We can&#8217;t update the contents of a category list that it&#8217;s a dynamically generated UI element,  such as a dialog box,  a draggable representation of an item,  a search result listing,  or an application plug-in.</li>
<li>You need to consider how all of these dropdown lists get initialized when the application starts (something this code sample doesn&#8217;t show.)</li>
<li>At some point you need to add a second way that a user can add a category (for instance,  the &#8220;Manage Categories&#8221; screen in WordPress) &#8212; at that point you can (a) duplicate the code in <em>AddCategory_Completed</em> (bad idea!),  (b) have the <em>ManageCategoriesForm</em> class call the  <em>AddCategory_Completed </em>method of <em>CreatePostForm</em> (better) or (c) move <em>CreatePostForm</em> someplace else. (best)</li>
<li>If UI components were responsible for communicating with the server to update themselves,  performance could be destroyed by unnecessary communications,  with no guarantee that UI components would be updated consistently.</li>
</ol>
<p>I&#8217;m sorry to admit that,  when I built my first GWT app,  I ran into all of the above problems,  plus a number of others.  I tried a number of ad hoc solutions until I was forced to sit down and develop an architecture (the one below) that doesn&#8217;t run out of steam.  Today,  you can do better.</p>
<h2>Separating the Model And The View</h2>
<p>Ok,  the plan is to create two classes:  <em>CategoryList</em> and <em>CategoryListBox</em> that work together to solve the problem of updating CategoryList boxes.  <em>CategoryList</em> is a singleton:  it keeps track of the current state of the category list and keeps a list of clients that need to know when the list is updated.</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/07/objects.png"><img class="alignnone size-full wp-image-39" title="objects" src="http://gen5.info/q/wp-content/uploads/2008/07/objects.png" alt="" width="500" height="278" /></a></p>
<p>The code for <em>CategoryList</em> looks like:</p>
<pre>[41] public class CategoryList {
[42]    private static CategoryList _Instance;
[43]    public static CategoryList Instance {
[44]       get {
[45]           if (_Instance==null)
[46]              _Instance=new CategoryList();
[47]
[48]           return _Instance;
[49]       }
[50]    }
[51]
[52]    private List&lt;ListBoxItems&gt; Items {get; set;}
[53]    private List&lt;ICategoryListener&gt; Listeners;
[54]    private CategoryList() { ... construct ...};</pre>
<p>Java programmers might notice a few C#-isms here,  in particular the way the class defines a static property called <em>Instance</em> that other classes use.  We don&#8217;t,  however,  use the C# event mechanism,  because it doesn&#8217;t do exactly what we want to do.</p>
<p>We call <em>UpdateItems</em> when there&#8217;s a change in the category list,  or when we initialize the category list when the application starts.  <em>UpdateItems</em> as an ordinary method,  although a C# stylist might probably make the <em>Items</em> property public and put the following logic in the setter:</p>
<pre>[55]   public void UpdateItems(List&lt;ListBoxItems&gt; items) {
[56]      Items=items;
[57]      foreach(var l in Listeners) {
[58]         l.UpdateItems(Items);
[59]      }
[60]   }</pre>
<p><em>CategoryListBoxes</em> will register and unregister themselves with the <em>CategoryList</em> with the following methods:</p>
<pre>[61]    public AddListener(ICategoryListener l) {
[62]       Listeners.Add(l);
[63]       l.UpdateItems(Items);
[64]    }
[65]    public RemoveListener(ICategoryListener l) {
[66]       Listeners.Remove(l);
[67]    }
[68] }</pre>
<p>Note that we could have built all of this logic into the CategoryListBox,  but by introducing the <em>CategoryList</em> class and the <em>ICategoryListener</em> interface,  we&#8217;ve decoupled the model from the view,  and given ourselves the option to create new visual representations of the category list.  (WordPress,  for instance has a distinct representation of the category list on the &#8220;Manage Category&#8221; screens and more than one way you can show a category list to your viewers.)</p>
<p>An interesting point is that <em>AddListener</em> immediately updates the listener when it registers itself.  This is a pattern that handles asynchronous initialization:  so long as the <em>Items</em> property starts out as something harmless,  <em>ICategoryListeners</em> formed before app initialization is completed will be initialized when the application initialization code calls <em>UpdateItems</em>.  If an <em>ICategoryListener</em> is created later,  it gets initialized upon registration  &#8212; either way you&#8217;re covered without having to think about it.</p>
<p>Let&#8217;s take a look at the CategoryListBox,  which extends ListBox and implements ICategoryListener.</p>
<pre>[70] public CategoryListBox: ListBox, ICategoryListener {</pre>
<p>It implements <em>ICategoryListener</em> by implementing the <em>UpdateItems</em> method:</p>
<pre>[71]   public UpdateItems(List&lt;ListBoxItems&gt; items) {
[72]      Items=items
[73]   }</pre>
<p>We&#8217;re going to implement registration and deregistration GWT style,  because GWT has particularly strict requirements for how we can access UI components.  We&#8217;re only allowed to manipulate UI components that are attached to the underyling HTML document tree &#8212; by registering and deregistering when the component is attached and detached,  components get updated at the proper times:</p>
<pre>[74]   public OnAttach() {
[75]      super.OnAttach();
[76]      CategoryList.Instance.AddListener(this);
[77]   }
[78]
[79]   public OnDetach() {
[80]      CategoryList.Instance.RemoveListner(this);
[81]      super.OnDetach();
[82]   }</pre>
<p>The GWT style is particularly nice in that it prevents long-lasting circular references between the view and the model:  once you remove the view from the visual,  the reference in the model goes away.  Silverlight is more forgiving in where you can register the control:  you can do it either the constructor or the <em>Loaded</em> event,  but I don&#8217;t see an equivalent <em>Unloaded</em> event which could be used for automatic deregistration &#8212; manual deregistration may be necessary to prevent memory leaks.</p>
<p>So what have we got?</p>
<p>We&#8217;ve got a <em>CategoryListBox </em>control that works together with the <em>CategoryList</em> singleton to keep itself updated.  So long as we call <em>CategoryList.UpdateItems()</em> during the initialization process,  we can just include a <em>CategoryListBox</em> where we want it and never worry about initialization or updating.  We can even create new <em>ICategoryListeners</em> if we want to make other visual controls that display the category list.  This is a path to simple and scalable development.</p>
<h2>What happened to the &#8220;Controller?&#8221;</h2>
<p>The Model-View-Controller paradigm is a perennially popular buzzword in computing.  The phrase was coined in the early 1980&#8242;s to describe a <a href="http://st-www.cs.uiuc.edu/users/smarch/st-docs/mvc.html">particular implementation in Smalltalk</a>,  which was one of the first implementations of a modern GUI.  The Controller is a third component that mediates between the View,  Controller and their environment.  Although Controllers are widspread in server-based web applications, the Controller often withers away in today&#8217;s GUI environments,  because it&#8217;s functions are often implemented by the event-handling mechanisms that come with the environment.  In this case,  &#8220;Controller&#8221;-like logic is embedded in certain methods of the <em>CategoryList</em>.</p>
<p>Note that there are two objects here that could be called a &#8220;Model&#8221;.  I&#8217;m calling the <em>CategoryList</em> a model because it has a 1-1 relationship with an object on the server:  the <em>categoryList</em> table.  <em>CategoryList</em> is a relatively persistent object that lasts for the lifetime of the RIA.  There&#8217;s another kind of &#8220;Model&#8221; object,  the <em>List&lt;ListBoxItems&gt;</em> that is stored in the <em>Items</em> property of <em>CategoryList</em> and is passed to a <em>ICategoryListener</em> during initialization or update &#8212; that object represents the state of the <em>categoryList</em> table at a particular instance time.  The generic <em>List&lt;&gt;</em> is an adequate representation of the state of <em>categoryList</em>,  although there are many cases where we might want to define a new class to represent the momentary state of a server object.</p>
<p>Something else funny about <em>CategoryList</em> is that it doesn&#8217;t export a public <em>Items</em> property.  It certainly could,  bu I chose not to because <strong><em>a getter for an asynchronous model object is making an empty promise</em></strong>.</p>
<p>A getter in a synchronous application can always initialize or update itself before returning:  a similar method in an asynchronous object must return to it&#8217;s caller before it can receive information from the server.   As asynchronous model can return a cached value of <em>Items</em> if available,  but it can make a much firmer promise to deliver correct updates of <em>Items</em> when they become available.  <em>CategoryList</em> does,  however,  deliver a cached copy of <em>Items </em>to  <em>CategoryListeners</em> after registration,  as this is an effective and efficient mechanism for initialization.</p>
<p>Would it be possible to define only a temporary &#8216;model&#8217; class and put a single <em>Controller</em> class in charge of updates?  Sure.  I think that would make more sense in a dynamically typed language like Javascript than it does in Java or C#,  since it would be hard for such a <em>Controller</em> to enforce type-safety.  Could we call <em>CategoryList</em> a <em>Controller</em>?  Perhaps,  but I think <em>CategoryList</em> is a logical place to locate methods that manipulate the <em>categoryList</em> &#8212; it really is a representation of a persistent object.</p>
<h2>What next?</h2>
<p>This is a good start,  but we haven&#8217;t entirely solved the RIA architecture problem.  Let&#8217;s talk about some of the issues we&#8217;d face if we generalized this approach:</p>
<ol>
<li>What if there was more than one type of dropdown list?  We ought to have an inheritance hierarchy from which we can derive multiple types of dropdown lists.  This could include mutable lists such as <em>ContributorTypeListBox</em> as well as immutable lists such as <em>USStateListBox</em>.</li>
<li>There is just one <em>CategoryList</em> in the application:  in some sense it&#8217;s globally scoped.  What if we want to represent a <em>BlogPost</em> or a <em>Contributor? </em>Simple,  use a <a href="http://en.wikipedia.org/wiki/Multiton">Multiton</a> instead of a Singleton.  Rather than writing <em>CategoryList.Instance</em>,  you might write <em>BlogPost.Instance[25]</em>,  where <em>25</em> is the primary key of the blog post.  The logic behind <em>Instance[] </em>is responsible for maintaining one and only one instance of <em>BlogPost</em> per actual blog post.</li>
<li>Isn&#8217;t the updating logic in the <em>CategoryList</em> and <em>CategoryListBox</em> repetitive?  It is.  A mature framework will either push this logic up into superclasses (kind of an embedded controller),  or push it out into a <em>Controller</em>.  The best approach will depend on the characteristics of the environment and the application.</li>
</ol>
<p>I&#8217;ll be elaborating on these issues in future postings:  subscribe to my <a href="http://feeds.feedburner.com/Generation5">RSS feed</a> to keep up to date!</p>
<h2>Conclusion</h2>
<p>It&#8217;s simple to initialize and update data in the simplest RIA&#8217;s,  but asynchronous communications makes it increasingly difficult as applications grow in complexity.  A simple approach to data updating that is reliable and maintainable is to create a set of persistent model classes that maintain:</p>
<ol>
<li>A cache of the latest data value,  and</li>
<li>A list of dependent view objects</li>
</ol>
<p>Model objects are responsible for updating View objects,  which in turn,  are responsible for registering themselves with the Model.  The result of this is that View objects can be used composably in the UI:  View objects can be added to the user interface without explicitly writing code to manage data updates.</p>
<p>Although this pattern can be applied immediately,  we&#8217;ll get the most of it when it (or a similar pattern) is incorporated in client-side RIA frameworks.  There are only a few client-side frameworks today (for instance, <a href="http://www.techper.net/2008/06/09/patterns-of-gui-architecture-in-cairngorm-and-puremvc/">Cairngorn and PureMVC</a>) but I think we&#8217;ll see exciting developments in the next year:  subscribe to the <a href="http://feeds.feedburner.com/Generation5">Gen5 RSS feed</a> to keep up with developments.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f18%2fthe-role-of-the-model-in-silverlight-gwt-and-javascript%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f18%2fthe-role-of-the-model-in-silverlight-gwt-and-javascript%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting back to the UI Thread in Silverlight 2 Beta 2</title>
		<link>http://gen5.info/q/2008/06/25/getting-back-to-the-ui-thread-in-silverlight-2/</link>
		<comments>http://gen5.info/q/2008/06/25/getting-back-to-the-ui-thread-in-silverlight-2/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 20:54:24 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=33</guid>
		<description><![CDATA[The problem Silverlight 2 Beta 2 has changed the concurrency model for asynchronous communications.  In Silverlight 2 Beta 1,  asynchronous requests always returned on the UI Thread.  This was convenient,  since updates to the user interface can only be done via the UI thread.  As of Silverlight 2 Beta 2,  asynchronous callbacks are fired in [...]]]></description>
			<content:encoded><![CDATA[<h2>The problem</h2>
<p>Silverlight 2 Beta 2 has changed the concurrency model for asynchronous communications.  In Silverlight 2 Beta 1,  asynchronous requests always returned on the UI Thread.  This was convenient,  since updates to the user interface can <em>only</em> be done via the UI thread.  As of Silverlight 2 Beta 2,  asynchronous callbacks are fired in worker threads that come from a thread pool:  although this potentially allows for better performance via concurrency,  it increases the risk for race conditions between callbacks &#8211;  more importantly,  some mechanism is necessary to make code that updates the user interface run in the UI thread.</p>
<h2>A solution</h2>
<p>It&#8217;s straightforward to execute a function in the UI thread by using the <em>Dispatcher</em> property of any <em>ScriptObject</em> The tricky part is that <em>ScriptObjects</em> are part of the user interface,  so you can only access the<em> Dispatcher</em> property from the UI thread.  At first this seems like a chicken-and-egg situation:  you need a<em> Dispatcher </em>to get to the UI thread,  but you need to be in the UI thread to get a <em>Dispatcher</em>.</p>
<p>This dilemma can be resolved by accessing a<em> Dispatcher</em> in your App.xaml.cs file and stashing it away in a static variable on application startup:</p>
<pre>private void Application_Startup(object sender, StartupEventArgs e) {
    ...
    UIThread.Dispatcher = RootVisual.Dispatcher;
}</pre>
<p>UIThread is a simple static class:</p>
<pre>public static class UIThread {
    public static Dispatcher Dispatcher {get; set;}
    public static void Run(Action a) {
        Dispatcher.BeginInvoke(a);
    }
}</pre>
<p>At some point in the future,  you can transfer execution to the UIThread by scheduling a function to run in it.</p>
<pre>public class ProcessHttpResponse(...) {
   ...
   UIThread.Run(UpdateUserInterface);
}</pre>
<p>The parameter of <em>Run</em> is an <em>Action</em> delegate,  which is a function that returns void and takes no parameters.  That&#8217;s fine and good,  but what if you want to pass some parameters to the function that updates the UI.  The usual <a href="http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/">three choices for passing state in asynchronous applications</a> apply,  but it&#8217;s particularly easy and fun to use a closure here:</p>
<pre>public class ProcessHttpResponse(...) {
    ...
    var elementToUpdate=...;
    var updateWithValue=...;

    UIThread.Run(delegate() {
        UpdateUserInterface(elementToUpdate,updateWithValue)
    });
}</pre>
<h2>When to return?</h2>
<p>If your application is complex,  and you have nested asynchronous calls,  you&#8217;re left with an interesting question:  where is the best place to switch execution to the UI thread?  You <strong>can</strong> switch to the UI Thread as soon as you get back from an HttpRequest or a WCF call and you <strong>must </strong>switch to the UI Thread before you access any methods or properties of the user interface.  What&#8217;s best?</p>
<p>It is simple and safe to switch to the UI Thread immediately after requests return from the server.  If you&#8217;re consistent in doing this,  you&#8217;ll never have trouble accessing the UI thread,  and you&#8217;ll never have trouble with race conditions between returning communication responses.  On the other hand,  you&#8217;ll lose the benefit of processing responses concurrently,  which can improve speed and responsiveness on today&#8217;s multi-core computers.</p>
<p>It&#8217;s straightforward to exploit concurrency when a requests can be processed independently.  For instance,  imagine a <a href="http://en.wikipedia.org/wiki/VRML">VRML</a> viewer written in Silverlight.  Displaying a VRML would require the parsing of a file,  the construction of the scene graph and the initialization of a 3-d engine,  which may require building data structures such as a BSP Tree.  Doing all of this work in the UI Thread would make the application lock up while a model is loading &#8212; it would be straightforward,  instead,  to construct all of the data structures required by the 3-d engine,  and attach the fully initialized 3-d engine to the user interface as the last step.  Since the data structures would be independent of the rest of the application,  thread safety and liveness is a nonissue.</p>
<p>Matters can get more complicated,  however,  if the processing of a request requires access to application-wide data;  response handlers running in multiple threads will probably corrupt shared data structures unless careful attention is paid to thread safety.  One simple approach is to <strong>always</strong> access shared data from the UI Thread,  and to transfer control to the UI Thread with <em>UIThread.Run</em> before accessing shared variables.</p>
<h2>Conclusion</h2>
<p>Silverlight 2 Beta 2 introduces a major change in the concurrency model for asynchronous communication requests.  Unlike SL2B1,  where asynchronous requests executed on the user interface thread,  SL2B2 launches asynchronous callbacks on multiple threads.  Although this model offers better performance and responsiveness,  it requires Silverlight programmers to explicitly transfer execution to the UI thread before accessing UI objects:  most SL2B1 applications will need to be reworked.</p>
<p>This article introduces a simple static class, <em> UIThread</em>,  which makes it easy to schedule execution in the UI Thread.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f06%2f25%2fgetting-back-to-the-ui-thread-in-silverlight-2%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f06%2f25%2fgetting-back-to-the-ui-thread-in-silverlight-2%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/06/25/getting-back-to-the-ui-thread-in-silverlight-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Keeping Track Of State In Asynchronous Callbacks</title>
		<link>http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/</link>
		<comments>http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/#comments</comments>
		<pubDate>Mon, 02 Jun 2008 17:13:43 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=27</guid>
		<description><![CDATA[When you&#8217;re writing applications that use asynchronous callbacks (i.e. Silverlight, AJAX, or GWT) you&#8217;ll eventually run into the problem of keeping track of the context that a request is being done in. This isn&#8217;t a problem in synchronous programming, because local variables continue to exist after one function calls another function synchronously: int AddToCount(int amount,string [...]]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re writing applications that use asynchronous callbacks (i.e. Silverlight, AJAX, or GWT) you&#8217;ll eventually run into the problem of keeping track of the context that a request is being done in.   This isn&#8217;t a problem in synchronous programming,  because local variables continue to exist after one function calls another function synchronously:</p>
<pre>int AddToCount(int amount,string countId)  {
   int countValue=GetCount(countId);
   return countValue+amount;
}</pre>
<p>This doesn&#8217;t work if the <em>GetCount</em> function is asynchronous,  where we need to write something like</p>
<pre>int AddToCountBegin(int amount,string countId,CountCallback outerCallback) {
     GetCountBegin(countId,AddToCountCallback);
}

void AddToCountCallback(int countValue) {
    ... some code to get the values of amount and outerCallback ...
    outerCallback(countValue+amount);
}</pre>
<p>Several things change in this example:  (i) the <em>AddToCount</em> function gets broken up into two functions:  one that does the work before the <em>GetCount</em> invocation,  and one that does the work after <em>GetCount</em> completes.   (ii) We can&#8217;t return a meaningful value from AddToCountCallback,  so it needs to &#8216;return&#8217; a value via a specified callback function.   (iii) Finally,  the values of <em>outerCallback</em> and <em>amount</em> aren&#8217;t automatically shared between the functions,  so we need to make sure that they are carried over somehow.<br />
There are three ways of passing context from a function that calls and asynchronous function to the callback function:</p>
<ol>
<li>As an argument to the callback function</li>
<li>As an instance variable of the class of which the callback function is a class</li>
<li>Via a closure</li>
</ol>
<p>Let&#8217;s talk about these alternatives:</p>
<h3>1. Argument to the Callback Function</h3>
<p>In this case,  a context object is passed to the asynchronous function,  which passes the context object to the callback.  The advantage here is that there aren&#8217;t any constraints on how the callback function is implemented,  other than by accepting the context object as a callback.  In particular,  the callback function can be static.  A major disadvantage is that the asynchronous function has to support this:  it has to accept a state object which it later passes to the callback function.</p>
<p>The implementation of <em>HttpWebRequest.BeginGetResponse(AsyncCallback a,Object state) </em>in the Silverlight libraries is a nice example.  If you wish to pass a context object to the <em>AsyncCallback</em>,  you can pass it in the second parameter, <em>state</em>.  Your callback function will implement the <em>AsyncCallback</em> delegate,  and will get something that implements <em>IAsyncResult</em> as a parameter.  The state that you passed into <em>BeginGetResponse</em> will come back in the <em>IAsyncResult.AsyncState</em> property. For example:</p>
<pre>class MyHttpContext {
	public HttpWebRequest Request;
        public SomeObject FirstContextParameter;
        public AnotherObject AnotherContextParameter;
}

protected void myHttpCallback(IAsyncResult abstractResult) {
	MyHttpContext context = (MyHttpContext) abstractResult.AsyncState;
	HttpWebResponse Response=(HttpWebResponse) context.Request.EndGetResponse(abstractResult);
}

public doHttpRequest(...) {
	...
        MyHttpContext context=new MyHttpContext();
	context.Request=Request;
	context.FirstContextParameter = ... some value ...;
	context.AnotherContextParameter = .. another value ...;
	Request.BeginGetResponse();
	Request.Callback(myHttpCallback,context);
}</pre>
<p>Note that,  in this API,  the <em>Request</em> object needs to be available in <em>myHttpCallback </em>because <em>myHttpCallbacks</em> get the response by calling the <em>HttpWebResponse.EndGetResponse()</em> method.  We could simply pass the Request object in the <em>state</em> parameter,  but we&#8217;re passing an object we defined, <em>myHttpCallback</em>,  because we&#8217;d like to carry additional state into <em>myHttpCallback</em>.</p>
<p>Note that the corresponding method for doing XMLHttpRequests in GWT,   the use of a <em>RequestBuilder</em> object doesn&#8217;t allow using method (1) to pass context information &#8212; there is no <em>state</em> parameter.   in GWT you need to use method (2)  or (3) to pass context at the <em>RequestBuilder</em> or GWT RPC level.  You&#8217;re free,  of course, to use method (1) when you&#8217;re chaining asynchronous callbacks:  however,  method (2) is more natural in Java where,  instead of a delegate,  you need to pass an object reference to designate a callback function.</p>
<h3>2. Instance Variable Of The Callback Function&#8217;s Class</h3>
<p>Functions (or Methods) are always attached to a class in C# and Java:  thus,  the state of a callback function can be kept in either static or instance variables of the associated class.  I don&#8217;t advise using static variables for this,  because it&#8217;s possible for more than one asynchronous request to be flight at a time:  if two request store state in the same variables,  you&#8217;ll introduce race conditions that will cause a world of pain. (see <a href="http://gen5.info/q/2008/05/02/how-asynchronous-execution-works-in-rias/">how race conditions arise in asynchronous communications</a>.)</p>
<p>Method 2 is particularly effective when both the calling and the callback functions are methods of the same class.  Using objects whose lifecycle is linked to a single asynchronous request is an effective way to avoid conflicts between requests (see the <a href="http://gen5.info/q/2008/04/11/the-asynchronous-command-pattern/">asynchronous command pattern</a> and <a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">asynchronous functions</a>.)</p>
<p>Here&#8217;s an example,  lifted from the <a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">asynchronous functions</a> article:</p>
<pre>    public class HttpGet : IAsyncFunction&lt;String&gt;
    {
        private Uri Path;
        private CallbackFunction&lt;String&gt; OuterCallback;
        private HttpWebRequest Request;

        public HttpGet(Uri path)
        {
            Path = path;
        }

        public void Execute(CallbackFunction&lt;String&gt; outerCallback)
        {
            OuterCallback = outerCallback;
            try
            {
                Request = (HttpWebRequest)WebRequest.Create(Path);
                Request.Method = "GET";
                Request.BeginGetRequestStream(InnerCallback,null);
            }
            catch (Exception ex)
            {
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
            }
        }

        public void InnerCallback(IAsyncResult result)
        {
            try
            {
                HttpWebResponse response = (HttpWebResponse) Request.EndGetResponse(result);
                TextReader reader = new StreamReader(response.GetResponseStream());
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateOk(reader.ReadToEnd()));
            } catch(Exception ex) {
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
            }
        }
    }</pre>
<p>Note that two pieces of context are being passed into the callback function:  an <em>HttpWebRequest</em> object named <em>Request</em> (necessary to get the response) and a <em>CallbackFunction&lt;String&gt;</em> delegate named <em>OuterCallback</em> that receives the return value of the asynchronous function.</p>
<p>Unlike Method 1,  Method 2 makes it possible to keep an unlimited number of context variables that are unique to a particular case in a manner that is both typesafe and oblivious to the function being called &#8212; you don&#8217;t need to cast an <em>Object</em> to something more specific,  and you don&#8217;t need to create a new class to hold multiple variables that you&#8217;d like to pass into the callback function.</p>
<p>Method 2 comes into it&#8217;s own when it&#8217;s used together with polymorphism,  inheritance and initialization patterns such as the factory pattern:  if the work done by the requesting and callback methods can be divided into smaller methods,  a hierarchy of asynchronous functions or commands can reuse code efficiently.</p>
<h3>3. Closures</h3>
<p>In both C# and Java,  it&#8217;s possible for a method defined inside a method to have access to variables in the enclosing method.  In C# this is a matter of creating an anonymous delegate,  while in Java it&#8217;s necessary to create an anonymous class.</p>
<p>Using closures results in the shortest code,  if not the most understandable code.  In some cases,  execution proceeds in a straight downward line through the code &#8212;  much like a synchronous version of the code.  However,  people sometimes get confused the indentation,  and,  more seriously,  parameters after the closure definition and code that runs immediately after the request is fired end up in an awkward place (after the definition of the callback function.)</p>
<pre>    public class HttpGet : IAsyncFunction&lt;String&gt;
    {
        private Uri Path;

        public HttpGet(Uri path)
        {
            Path = path;
        }

        public void Execute(CallbackFunction&lt;String&gt; outerCallback)
        {
            OuterCallback = outerCallback;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Path);
                Request.Method = "GET";
                Request.BeginGetRequestStream(delegate(IAsyncResult result) {
	            try {
                        response = request.EndGetResponse(result);
                        TextReader reader = new StreamReader(response.GetResponseStream());
                        outerCallback(CallbackReturnValue&lt;String&gt;.CreateOk(reader.ReadToEnd()));
                    } catch(Exception ex) {
                        outerCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
                    }</pre>
<pre>            },null); <span style="color: #800000;">// &lt;--- note parameter value after delegate definition</span></pre>
<pre>            }
            catch (Exception ex)
            {
                outerCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
            }
        }
    }</pre>
<p>The details are different in C# and Java:  anonymous classes in Java can access local,  static and instance variables from the enclosing context that are declared <em>final</em> &#8212;  this makes it impossible for variables to be stomped on while an asynchronous request is in flight.  C# closures,  on the other hand,  can access only local variables:  <em>most</em> of the time this prevents asynchronous requests from interfering with one another,  unless a single method fires multiple asynchronous requests,  in which case  <a href="http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx">counter-intuitive things can happen</a>.</p>
<h3>Conclusion</h3>
<p>In addition to receiving return value(s),  callback functions need to know something about the context they run in:  to write reliable applications,  you need to be conscious of where this information is;  better yet,  a strategy for where you&#8217;re going to put it.  Closures,  created with anonymous delegates (C#) or classes (Java) produce the shortest code,  but not necessarily the clearest.  Passing context in an argument to the callback function requires the cooperation of the called function,  but it makes few demands on the calling and callback functions:  the calling and callback functions can both be static.  When a single object contains both calling and callback functions,  context can be shared in a straightforward and typesafe manner;  and when the calling and callback functions can be broken into smaller functions,  opportunities for efficient code reuse abound.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f06%2f02%2fkeeping-track-of-state-in-asynchronous-callbacks%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f06%2f02%2fkeeping-track-of-state-in-asynchronous-callbacks%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How Asynchronous Execution Works in RIAs</title>
		<link>http://gen5.info/q/2008/05/02/how-asynchronous-execution-works-in-rias/</link>
		<comments>http://gen5.info/q/2008/05/02/how-asynchronous-execution-works-in-rias/#comments</comments>
		<pubDate>Fri, 02 May 2008 16:55:27 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/2008/05/02/how-asynchronous-execution-works-in-rias/</guid>
		<description><![CDATA[CORRECTION:  The threading model in Silverlight has changed as of Silverlight 2 Beta 2.  It is now possible to initiate asynchronous communication from any thread,  however,  asynchronous callbacks now run in &#8220;new&#8221; threads that come from a thread pool.  The issues in this article still apply,  with two additions:  (1) the possibility of race conditions [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #800000;">CORRECTION:  The threading model in Silverlight has changed as of Silverlight 2 Beta 2.  It is now possible to initiate asynchronous communication from any thread,  however,  asynchronous callbacks now run in &#8220;new&#8221; threads that come from a thread pool.  The issues in this article still apply,  with two additions:  (1) the possibility of race conditions and deadlocks between asynchronous callback threads and (2) all updates to user interface components must be done from the user interface thread.  (Fortunately,  it&#8217;s easy to <a href="http://gen5.info/q/2008/06/25/getting-back-to-the-ui-thread-in-silverlight-2/">get back to the UI thread</a>.)  Subscribe to our <a href="http://feeds.feedburner.com/Generation5">RSS Feed</a> to keep informed of breaking developments in Silverlight development.<br />
</span></p>
<p>There&#8217;s a lot of confusion about how asynchronous communication works in RIA&#8217;s such as Silverlight, GWT and Javascript.  When I start talking about the problems of concurrency control,  many people tell me that there aren&#8217;t any concurrency problems since everything runs in a single thread.  [1]</p>
<p>It&#8217;s important to understand the basics of what is going on when you&#8217;re writing asynchronous code,  so I&#8217;ve put together a simple example to show how execution works in RIA&#8217;s and how race conditions are possible.  This example applies to Javascript,  Silverlight,  GWT and Flex,  as well as a number of other environments based on Javascript.  This example doesn&#8217;t represent best practices,  but rather what can happen when you&#8217;re not using a proactive strategy that eliminates concurrency problems:</p>
<p><img src="http://gen5.info/q/wp-content/uploads/2008/05/asyncttimelineexport.png" alt="Asynchronous Execution" /></p>
<p>In the diagram above,  execution starts when the user pushes a button (a).  This starts the user interface thread by invoking an onClick handler.  The user interface thread starts two XmlHttpRequests,  (b) and (c).  The event handler eventually returns,  so execution stops in the user interface thread.</p>
<p>In the meantime,   the browser still has two XmlHttpRequests running.  Callbacks from http requests,  timers and user interfaces go into a queue &#8212; they get executed right away if the user interface thread is doing nothing,  but get delayed if the user interface thread is active.</p>
<p>Http request (b) completes first,  causing the http callback for request (b) to start.  Had something been a little different with the web browser,  web server or network,  request (c) could have returned first,  causing the callback for request (c) to start.  If the result of the program depends on the order that the callbacks for (b) and (c) run,  we have a race condition.  The callback for http request (b) starts a new http request (d),  which runs for a long time.</p>
<p>In the meantime,  the user is moving the mouse and triggers a mouseover event while the request (b) callback is running.  Right after the request (b) callback completes,  the web browser starts the UI thread,  which causes a mouseover event handler (e) to run.   Note that the user can trigger user interface events while XmlHttpRequests are running,  causing event handlers to run in an unpredictable order:  if this causes your program to malfunction,  your program has a bug.</p>
<p>While the event handler (e) is running,  request (c) completes:  like the mouseover event,  this event is queued and runs once event handler (e) completes.  Before (e) completes,  it starts a new http request (f).  The browser looks into the event queue when (e) completes,  and starts the callback for (c).  Http request (f) completes while callback (c) is running,  gets queued,  and runs after (c) is running.</p>
<p>At the end of this example,  the callback for (f) completes,  causing the UI thread to stop.  The http request (c) is still in flight &#8212; it completes in the future,  somewhere off the end of the page.</p>
<p>This example did not include any timers,  or any mechanism of deferred execution such as <em>DeferredCommand</em> in GWT or <em>Dispatcher.Invoke()</em> in Silverlight.  This is but another mechanism to add callback references to the event queue.</p>
<p>As you can see,  there&#8217;s a lot of room for mischief:  http requests can return in an arbitrary order and users can initiate events at arbitrary times.  The order that things happen in can depend on the browser,  it&#8217;s settings,  on the behavior of the server,  and everything in between.  Some users might use the application in a way that avoids certain problems (they&#8217;ll think it&#8217;s wonderful) and others might consistently or occasionally trigger an event that causes catastrophe.  These kind of bugs can be highly difficult to reproduce and repair.</p>
<p>Asynchronous RIAs have problems with race conditions that are similar to threaded applications,  but not exactly the same.  Today&#8217;s languages and platforms have excellent and well documented mechanisms for dealing with threads,  but today&#8217;s RIAs do not have mature mechanisms for dealing with concurrency.  Over time we&#8217;ll see libraries and frameworks that help,  but asynchronous safety isn&#8217;t something that can be applied like deodorant:  it involves non local interactions between distant parts of the program.  The simplest applications can dodge the bullet,  but applications beyond a certain level of complexity require an understanding of asynchronous execution and the consistent use of patterns that avoid trouble.</p>
<p><em>[1] Although it is possible to create new threads in Silverlight,  all communication and user interface access must be done from the user interface thread &#8212; many Silverlight applications are single-threaded,  and adding multiple threads complicates the issue.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/05/02/how-asynchronous-execution-works-in-rias/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Once Asynchronous,  Always Asynchronous</title>
		<link>http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/</link>
		<comments>http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/#comments</comments>
		<pubDate>Mon, 21 Apr 2008 13:58:27 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/</guid>
		<description><![CDATA[Oliver Steele writes an excellent blog about coding style,  and has written some good articles on asynchronous communications with a focus on Javascript. Minimizing Code Paths In Asynchronous Code,  a recent post of his,  is about a lesson that I learned the hard way with GWT that applies to all RIA systems that use asynchronous [...]]]></description>
			<content:encoded><![CDATA[<p>Oliver Steele writes an <a href="http://osteele.com/blog/1">excellent blog about coding style</a>,  and has written some good articles on asynchronous communications with a focus on Javascript.</p>
<p><a href="http://osteele.com/archives/2008/04/minimizing-code-paths-asychronous-code ">Minimizing Code Paths In Asynchronous Code</a>,  a recent post of his,  is about a lesson that I learned the hard way with GWT that applies to all RIA systems that use asynchronous calls.  His example is the same case I encountered,  where a function might return a value from a cache or might query the server to get the value:   an obvious way to do this in psuedocode is:</p>
<pre>function getData(...arguments...,callback) {
   if (... data in cache...) {
      callback(...cached data...);
   }
  cacheCallback=anonymousFunction(...return value...) {
     ... store value in cache...
     callback(...cached data...);
  }</pre>
<pre>   getDataFromServer(...arguments...,cacheCallback)</pre>
<pre>}</pre>
<p>At first glance this code looks innocuous,  but there&#8217;s a major difference between what happens in the cached and uncached case.  In the cached case,  the callback() function gets called before getData() returns &#8212; in the uncached case,  the opposite happens.  What happens in this function has a global impact on the execution of the program,  opening up two code paths that complicate concurrency control and introduce bugs that can be frustrating to debug.</p>
<p>This function can be made more reliable if it schedules callback() to run after the thread it is running in completes.  In Javascript,  this can be done with setTimeout().   In Silverlight use <a href="http://www.wilcob.com/Wilco/Silverlight/threading-in-silverlight.aspx"><span class="inlineCode">System.Windows.Threading.Dispatcher.</span></a><span class="inlineCode">  to schedule the callback to run in the UI thread.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Asynchronous Functions</title>
		<link>http://gen5.info/q/2008/04/18/asynchronous-functions/</link>
		<comments>http://gen5.info/q/2008/04/18/asynchronous-functions/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 20:27:21 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/2008/04/18/asynchronous-functions/</guid>
		<description><![CDATA[Asynchronous Commands are a useful way to organize asynchronous activities, but they don&#8217;t have any way to pass values or control back to a caller. This post contains a simple Asynchronous Function library that lets you do that. In C# you call an Asynchronous Function like: void CallingMethod(...) { ... do some things ... IAsyncFunction&#60;String&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Asynchronous Commands are a useful way to organize asynchronous activities,  but they don&#8217;t have any way to pass values or control back to a caller.  This post contains a simple Asynchronous Function library that lets you do that.  In C# you call an Asynchronous Function like:</p>
<pre> void CallingMethod(...) {
    ... do some things ...
    IAsyncFunction&lt;String&gt; httpGet=new HttpGet(... parameters...);
    anAsynchronousFunction.Execute(CallbackMethod);
}

void CallbackMethod(CallbackReturnValue&lt;String&gt; crv) {
    if (crv.Error!=null) { ... handle Error,  which is an Exception ...}
    String returnValue=crv.Value;
    ... do something with the return value ...
}</pre>
<p>We&#8217;re using generics so that return values can be passed back in a type safe manner.  The type of the return value of the asynchronous function is specified in the type parameter of IAsyncFunction and CallbackReturnValue.</p>
<p>Asynchronous functions catch exceptions and pass them back in  in the CallbackReturnValue.  This makes it possible to propagate exceptions back to the caller,  as in synchronous functions.  The code to do this must has to be manually replicated in each asynchronous function,  however,  the code can be put into a wrapper delegate.</p>
<p>You could do the same thing in Java,  but the CallbackMethod would need to be a class that implements an interface rather than a delegate.</p>
<p><span id="more-21"></span> In C# it takes one class,  one interface and one delegate to make this work:</p>
<pre>     public delegate void CallbackFunction&lt;ReturnType&gt;(CallbackReturnValue&lt;ReturnType&gt; value);

    public class CallbackReturnValue&lt;ReturnType&gt; {
        public ReturnType Value {get; private set; }
        public Exception Error {get; private set; }

        protected CallbackReturnValue() { }

        public static CallbackReturnValue&lt;ReturnType&gt; CreateOk(ReturnType value) {
            CallbackReturnValue&lt;ReturnType&gt; crv=new CallbackReturnValue&lt;ReturnType&gt;();
            crv.Value=value;
            return crv;
        }

        public static CallbackReturnValue&lt;ReturnType&gt; CreateError(Exception error) {
            CallbackReturnValue&lt;ReturnType&gt; crv = new CallbackReturnValue&lt;ReturnType&gt;();
            crv.Error = error;
            return crv;
        }
    }

    public interface IAsyncFunction&lt;ReturnType&gt;
    {
        void Execute(CallbackFunction&lt;ReturnType&gt; callback);
    }</pre>
<p>Here&#8217;s a simple example of an asynchronous function implementation:</p>
<pre>    public class HttpGet : IAsyncFunction&lt;String&gt;
    {
        private Uri Path;
        private CallbackFunction&lt;String&gt; OuterCallback;
        private HttpWebRequest Request;

        public HttpGet(Uri path)
        {
            Path = path;
        }

        public void Execute(CallbackFunction&lt;String&gt; outerCallback)
        {
            OuterCallback = outerCallback;
            try
            {
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Path);
                Request.Method = "GET";
                Request.BeginGetRequestStream(InnerCallback,null);
            }
            catch (Exception ex)
            {
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
            }
        }

        public void InnerCallback(IAsyncResult result)
        {
            try
            {
                HttpWebResponse response = (HttpWebResponse) Request.EndGetResponse(result);
                TextReader reader = new StreamReader(response.GetResponseStream());
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateOk(reader.ReadToEnd()));
            } catch(Exception ex) {
                OuterCallback(CallbackReturnValue&lt;String&gt;.CreateError(ex));
            }
        }
    }</pre>
<p>Asynchronous Functions provide a simple and typesafe way to build asynchronous functions by composing them out of simpler asynchronous functions,  and it provides a reasonable way to emulate the usual bubbling of exceptions that allows callers to catch exceptions thrown inside a callee.  (Without this kind of intervention,  exceptions in the callback functions propagate in the reverse of the usual direction!)   Over the next few posts,  we&#8217;ll talk about how asynchronous execution really works,  which is essential for getting good results with Asynchronous Functions.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/04/18/asynchronous-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
