<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xhtml="http://www.w3.org/1999/xhtml" version="2.0">
  <channel>
    <lastBuildDate>Wed, 02 Jul 2008 13:34:59 GMT</lastBuildDate>
    <copyright>Copyright (c) 2005, Nikhil Kothari</copyright>
    <description>Contains all posts from my weblog.</description>
    <generator>Nikhil's Blog Engine v1.1 (http://www.nikhilk.net)</generator>
    <link>http://www.nikhilk.net/Category.aspx?id=1</link>
    <managingEditor>nikhilk@winisp.net</managingEditor>
    <title>Nikhil Kothari's Weblog</title>
    <webMaster>nikhilk@winisp.net</webMaster>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>If you're developing a web site, especially a public facing site, search and indexability are probably high on your list of requirements and priorities. Yesterday, searchability of rich internet applications got extra attention with Adobe's announcement that it is providing technology to search engines to improve indexability of swf/flash-based applications.</p>
        <p>This is particularly interesting to me as I think getting the right SEO behavior for RIAs is based on looking at end-to-end solutions that involve complementary server-side techniques (guess that is not totally unexpected from someone like me who has been working on asp.net). I've also been presenting on Search and RIA and enabling indexability for Silverlight and Ajax apps for a couple of years at various conferences... links to those below.</p>
        <p>There has always been a question mark around indexability of RIAs, whether they're built in Flash, or Silverlight, or even Ajax. The fundamental problem is that static indexing of a RIA is likely to turn up only the user interface of the application, and not the interesting and meaningful data fetched by application logic and presented dynamically to the user. Indexing an application binary or script is akin to having desktop search index winword.exe instead of your documents... not very useful. Most folks are now seeing indexing something like a raw swf binary as less and less useful, as applications become more and more dynamic.</p>
        <p>The two key things around improving SEO (besides various general techniques like URL canonicalization, friendly URLs and search-engine friendly URL rewriting) are ensuring <b>indexability</b> and facilitating <b>relevance</b>. Indexability is created through addressing the <i>what</i> content is visible to the crawler, as well as <i>where</i> the crawler should look. Relevance is primarily addressed through creating deep linkable content and interesting content (so folks actually link to it).</p>
        <break />
        <p>The Adobe/Google announcement takes indexing one a step further beyond indexing static binary content, by attempting to simulate human behavior and interacting with the application to extract textual content and links from the application. I can see how automated clicks and the like might allow the crawler to cause an application to execute some partial logic, but a lot of application interaction is driven off of actual meaningful text input (eg. keywords in a search input box) where meaningful often depends on the specific application in question. The announcement does not go into any details... somewhat strange, I think, so there is naturally some guessing going on. The comment stream also contains a good mix of folks questioning whether the approach will even work? (for example <a href="http://googlewebmastercentral.blogspot.com/2008/06/improved-flash-indexing.html?showComment=1214893680000#c5568205730681616419" target="_new">here</a> and <a href="http://googlewebmastercentral.blogspot.com/2008/06/improved-flash-indexing.html?showComment=1214911380000#c3436625983016746150" target="_new">here</a>)</p>
        <p>It is interesting to see the buzz - it is good to see search engines at least begin to think beyond indexing static HTML. Technically speaking, this sort of approach to indexability lends itself to Silverlight apps as well pretty easily. First a Silverlight application packaged in a xap file is easily cracked open without a special SDK - it is simply a zip file after all. Any static textual xaml content is easily parsed by virtue of being XML. Second it is easy to embed and extract metadata via an additional file within the zip archive. Third, the Silverlight DOM itself can be easily walked and inspected programmatically to detect all text, links and images that are being visualized by the control. Finally, it is possible to automate the application thanks to the extensible API that Silverlight offers for enabling accessibility and screen reader capabilties. Additionally, Silverlight apps can also support deep linking which is also important for facilitating relevance. Essentially, Silverlight provides simple APIs to allow the app to easily consume the URL it was loaded from, and use information on the URL query string to load and display appropriate data.</p>
        <p>All that said, it will be interesting to see how well this approach pans out, as there are a number of challenges in simulating a user realistically, especially without any hints provided by the application developer. In the mean time, this is as good as any a time to share my slide deck on building indexable Silverlight applications that I used in my presentation at <a href="http://searchmarketingexpo.com/" target="_new">SMX</a>, a search conference that took place last month here in Seattle.</p>
        <p>
          <!-- <div style="width:425px;"><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=searchfriendlywebapps-1214981655393056-8"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=searchfriendlywebapps-1214981655393056-8" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object></div> -->
          <script src="/App_Assets/Modules/Lightbox/Lightbox.js">
          </script>
          <link rel="stylesheet" type="text/css" href="/App_Assets/Modules/Lightbox/Lightbox.css" />
          <a href="Content/Posts/Search/Slide1.png" rel="lightbox[1]" title="Search Friendly Web Apps" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
            <img src="Content/Posts/Search/Slide1.png" border="0" />
          </a>
          <div style="display: none">
            <a href="Content/Posts/Search/Slide2.png" rel="lightbox[1]" title="Application Types" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide2.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide3.png" rel="lightbox[1]" title="Practices" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide3.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide4.png" rel="lightbox[1]" title="Indexability Problem" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide4.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide5.png" rel="lightbox[1]" title="Restoring Indexability" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide5.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide6.png" rel="lightbox[1]" title="Demo" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide6.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide7.png" rel="lightbox[1]" title="Page Source Code" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide7.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide8.png" rel="lightbox[1]" title="Browser View" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide8.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide9.png" rel="lightbox[1]" title="Search Crawler View" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide9.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide10.png" rel="lightbox[1]" title="Why this Pattern?" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide10.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide11.png" rel="lightbox[1]" title="Why this Pattern?" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide11.png" border="0" />
            </a>
            <a href="Content/Posts/Search/Slide12.png" rel="lightbox[1]" title="Key Takeaways" style="border: solid 1px #E0E0E0; padding: 3px; text-decoration: none; margin-bottom: 2px; display: block; width: 480px;">
              <img src="Content/Posts/Search/Slide12.png" border="0" />
            </a>
          </div>
        </p>
        <p>The deck above illustrates the pattern for supplying alternate content with sample markup. At a high-level, the approach can be summarized as combining client-side logic with server-side rendering and sitemaps to address the "what" and "where" of indexability. The specific implementation of the pattern is interesting in how it achieves alternate content without requiring the developer to implement two applications and do double work.</p>
        <p>I especially like the pattern because it works today, across search engines, applies to Silverlight/Flash apps as well as Ajax apps, and has a number of side-benefits around networking optimization and graceful degradation in script-less environments as listed in the deck above. Its always nice to pick a single pattern that can help solve multiple problems that Web developers encounter regularly. I first <a href="AjaxSEO.aspx">blogged</a> about this approach back in 2007 right after MIX07. I had a chance to present it once more at MIX08, and you can actually check out the presentation and demo in the <a href="http://sessions.visitmix.com/?selectedSearch=T16" target="_new">session video</a> (skip ahead about 42 minutes into the talk for the part on indexability).</p>
        <p>Any questions on the approach? Feel free to ask below. Also, I am curious what are your thoughts on the alternate content approach, or on the overall subject of search for RIAs?</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/search" rel="tag">search</a>  | <a href="http://www.nikhilk.net/tags/ria" rel="tag">ria</a>  | <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/ajax" rel="tag">ajax</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=200#Comments</comments>
      <description>Thoughts on search for RIAs, along with pointers to my latest slides as well as MIX session on ensuring indexability (esp. for Silverlight and Ajax apps)...</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=200</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=200</link>
      <pubDate>Wed, 02 Jul 2008 13:34:59 GMT</pubDate>
      <title>Search for Rich Internet Applications</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>In my last post, I posted an implementation of the <a href="Silverlight-ViewModel-Pattern.aspx">ViewModel or M-V-VM pattern</a> for use in Silverlight applications. This pattern allows you to decouple your view presentation logic and data from the view, thereby facilitating independent development/design of your app as well as easier unit testing of your application code. I will highly recommend you check out that post for the more detailed description and intro sample if you haven't already done so, as this post will build further on that.</p>
        <p>Now that I've done some additional exploration, and prototyping, I think the syntax used to define the glue between the View and the ViewModel as first presented was a bit suboptimal, and could be re-done to be much more intuitive. Read on to find out more.</p>
        <p>
          <b>Amazon Search Sample</b>
          <br />
          <span style="float:right; margin-left: 10px; margin-bottom: 10px">
            <a href="Content/Posts/SilverlightViewModel/AmazonSearch.htm" title="Click to Run" style="text-decoration:none;border:none">
              <img src="Content/Posts/SilverlightViewModel/AmazonSearchThumbnail.png" border="0" />
            </a>
          </span>In that post, I had a simple <a href="Content/Posts/SilverlightViewModel/AmazonSearch.htm">Amazon Search</a> app to demonstrate the view model pattern. Focusing on the search aspect of the scenario, here are the relevant snippets of code and XAML forming the view model and the view respectively:</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> SearchViewModel : Model {
    ...

    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">void</span> Search(<span style="color: #0000ff;">string</span> keyword) {
    ...
    }
}

<span style="color: #0000ff;">&lt;</span><span style="color: #800000;">vm:View</span><span style="color: #ff0000;">xmlns</span><span style="color: #0000ff;">="..."</span><span style="color: #ff0000;">xmlns:x</span><span style="color: #0000ff;">="..."</span><span style="color: #ff0000;">xmlns:vm</span><span style="color: #0000ff;">="clr-namespace:Silverlight.FX.ViewModel;assembly=Silverlight.FX"</span><span style="color: #ff0000;">xmlns:app</span><span style="color: #0000ff;">="clr-namespace:AmazonSearch.Views"</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">vm:View.Model</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">app:SearchViewModel</span><span style="color: #0000ff;">/&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">vm:View.Model</span><span style="color: #0000ff;">&gt;</span>

  ...

  <span style="color: #0000ff;">&lt;</span><span style="color: #800000;">Button</span><span style="color: #ff0000;">Content</span><span style="color: #0000ff;">="Search"</span><span style="color: #ff0000;">IsEnabled</span><span style="color: #0000ff;">="{Binding CanSearch}"</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">vm:ButtonEvents.Click</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">vm:InvokeMethod</span><span style="color: #ff0000;">MethodName</span><span style="color: #0000ff;">="Search"</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">vm:ElementParameter</span><span style="color: #ff0000;">ElementName</span><span style="color: #0000ff;">="searchTextBox"</span><span style="color: #ff0000;">ElementProperty</span><span style="color: #0000ff;">="Text"</span><span style="color: #0000ff;">/&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">vm:InvokeMethod</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">vm:ButtonEvents.Click</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">Button</span><span style="color: #0000ff;">&gt;</span>

  ...
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">vm:View</span><span style="color: #0000ff;">&gt;</span></pre>
        <p>Action behaviors were used to implement the glue that allows a View to invoke some operation defined on the View Model in response to an event. As you can see in the example above, an InvokeMethod action has been associated with the Button's Click event and it is set up to invoke the Search method on the ViewModel passing in the Text in the specified TextBox.</p>
        <p>
          <b>InvokeMethod Shortcomings in Associating View to ViewModel</b>
          <br />The first issue with this approach is that it isn't super-friendly. The XAML to define a list of parameters gets verbose very quickly. Secondly it doesn't allow for a number of scenarios, around passing in arbitrary data into the view model. I noted in the post that I might want to do something like this instead:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <span style="color: #ff0000;">Click</span>
          <span style="color: #0000ff;">="{Action InvokeMethod Search(searchTextBox.Text)}"</span>
          <span style="color: #ff0000;">IsEnabled</span>
          <span style="color: #0000ff;">="{Binding CanSearch}"</span>
          <span style="color: #0000ff;"> /&gt;</span>
        </pre>
        <p>I got to thinking about this after writing and re-reading the post myself, and what occurred to me is that this is quite a slippery slope, eventually leading to a full expression language. Not wanting to create such a thing, I started reflecting on what could be repurposed.</p>
        <p>I realized the Dynamic Language Runtime (DLR) would be a perfect fit. It is just the right designer-friendly glue that can be used to call into the bulk of the logic that is itself developed using statically compiled code that exists in the view model and the rest of the app. I could scope the use of the script down to a minimum by hosting the DLR to execute just script expressions. The DLR would also give me the benefit of using something like JavaScript, and potentially on any another scripting engine created to run on the DLR.</p>
        <break />
        <p>
          <b>DLR-based InvokeScript</b>
          <br />So I got to work, and created an InvokeScript action (leveraging the extensibility of actions), and got this working:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <span style="color: #ff0000;">IsEnabled</span>
          <span style="color: #0000ff;">="{Binding CanSearch}"</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:ButtonEvents.Click</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:InvokeScript</span>
            <span style="color: #ff0000;">Script</span>
            <span style="color: #0000ff;">="$model.Search(searchTextBox.Text)"</span>
            <span style="color: #0000ff;"> /&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">vm:ButtonEvents.Click</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>The verbose XAML for defining parameters was gone, and I didn't have to create my own mini-language. However this is still too much XAML for me. With a bit more work, I was able to get the following syntax to work:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <b>
            <span style="color: #ff0000;">vm:ButtonEvents</span>.<span style="color: #ff0000;">Click</span><span style="color: #0000ff;">="$model.Search(searchTextBox.Text)"</span></b>
          <span style="color: #0000ff;">/&gt;</span>
        </pre>
        <p>The InvokeScript does its work by hosting the DLR. As a DLR host the InvokeScript action is able to resolve things like $model to the current ViewModel instance. It also resolves "searchTextBox" when the script engine hits that. To do so, it first looks to see if it's a property of the Button (which it isn't, so it continues to search). Next it looks to see if it can find it in the visual tree using FindName or in the resources dictionary via a recursive FindResource (and it does find it in the tree). The bottom line is the script expression is simple and intuitive. And the DLR host does all the work through an intuitive set of rules, rather than have those be spelt out in a verbose form in XAML.This has me pretty satisfied.</p>
        <p>As an aside, the script expression can also reference a variable named $event that represents the current event. This is useful if there is some interesting data in the event argument that you want to send across to the ViewModel operation (eg. mouse coordinates in a mouse event) or some property on the event argument you want to set by using the return value of the operation itself (eg. Canceled on a CancelEventArgs).</p>
        <p>Essentially the InvokeScript action creates a little data flow pipe as shown below that flows event information and pieces of data from the View into the operation in the ViewModel. The pipe is also able to flow back the return value from the operation for use in the View, even though it hasn't been depicted here.</p>
        <p style="text-align:center">
          <img src="Content/Posts/SilverlightViewModel/DataFlow.png" />
        </p>
        <p>You might be wondering how the script engine is instantiated. This gives me a chance to introduce my framework's derived Application type that is used in App.xaml - XApplication. Amongst various other pieces of functionality, XApplication provides the semantics of being a global service container. The application developer can write this markup in App.xaml to declaratively define the instance of a ScriptService that will be used in their application. At runtime, the InvokeScript action looks for the current XApplication instance, and queries for the ScriptService service and uses the ScriptEngine that the service is responsible for instantiating and managing based on the specified language.</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">fxa:XApplication</span>
          <span style="color: #ff0000;">xmlns</span>
          <span style="color: #0000ff;">="..."</span>
          <span style="color: #ff0000;">xmlns:x</span>
          <span style="color: #0000ff;">="..."</span>
          <span style="color: #ff0000;">xmlns:fxa</span>
          <span style="color: #0000ff;">="clr-namespace:Silverlight.FX.Applications;assembly=Silverlight.FX"</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">fxa:XApplication.Services</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">fxa:ScriptService</span>
            <span style="color: #ff0000;">ScriptLanguage</span>
            <span style="color: #0000ff;">="JavaScript"</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">fxa:XApplication.Services</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">fxa:XApplication</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>Note that you'll need to package the DLR assemblies (Microsoft.Scripting.*.dll) and the language specific ones (such as Microsoft.Jscript.*.dll for JavaScript)  into your application's xap package. These are part of the Silverlight 2 SDK. Just add a reference to those dlls in your application project in Visual Studio and the XAP packager will do the right thing to include them in as part of the build process.</p>
        <p>
          <b>Code and Summary</b>
          <br />As usual you can <a href="Content/Posts/SilverlightViewModel/ViewModelDLR.zip">download the all of the code, sample, and framework</a> to play with this to your heart's content. Do you think the use of DLR here helps signficantly simplify the view model pattern?</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/prototype" rel="tag">prototype</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=199#Comments</comments>
      <description>More fun with the ViewModel or M-V-VM pattern - using the Dynamic Language Runtime in Silverlight to create a better glue between the View and its ViewModel.</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=199</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=199</link>
      <pubDate>Fri, 20 Jun 2008 15:34:11 GMT</pubDate>
      <title>ViewModel Pattern extended with the Dynamic Language Runtime</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>The <a href="http://en.wikipedia.org/wiki/Model-view-controller" target="_new">MVC pattern</a> is quite widespread, and lots has been written about it. Clearly, it is a popular addition to ASP.NET. MVC works especially well for request/response style web apps as well as in navigation-based client apps.</p>
        <p>The ViewModel pattern, or more accurately said, the Model-View-ViewModel (M-V-VM) pattern on the other hand hasn't been discussed a whole lot as a formal pattern. However, it is a really nice pattern that is very well suited to client apps that generally feature interactive or dynamic user interfaces that are data-bound and implemented declaratively, for example, most Silverlight apps.</p>
        <p>
          <b>Introduction to ViewModel</b>
          <br />
This is a very brief description of the pattern, and how it is both similar and dissimilar from the code-behind pattern that is in vogue.</p>
        <dl>
          <dt>Model/DataModel</dt>
          <dd>This is somewhat analogous to the model in MVC. It basically represents the data that the application operates over, as well as the data access mechanism. This might be reused for different parts of the application. This might be partially defined declaratively, and/or code-gen'd.</dd>
          <dt>View</dt>
          <dd>This represents the user interface, displays data, and enables user interaction. This is typically defined declaratively - XAML, HTML etc. No surprises here.</dd>
          <dt>ViewModel</dt>
          <dd>This can also be read as "The View's Model" which is a bit more representative of its function. This sits in between the View and the Model and surfaces data in a form that is more suited for viewing or editing. It also defines operations that can be invoked to perform some work, often times resulting in changes to the data that the View is bound to. While it doesn't depend on the View, it is logically associated with one in a one-to-one manner. This might be partially code-gen'd as well, but for the most part this is authored in code.</dd>
        </dl>
        <p>
          <img src="Content/Posts/SilverlightViewModel/CodeBehind.png" alt="Code-behind Pattern" style="float: right; margin-left: 10px; margin-bottom: 10px" />You've probably been doing something quite close all along. I am sure you've written some piece of UI that is associated with some code-behind that is responsible for loading in data, and implementing logic to handle user input and interaction in the form of event handlers. The figure on the right illustrates the mechanics of the code-behind pattern. One of the big problems with code-behind is that it mixes your logic with presentation and couples it deeply, which gets in the way of testability. Another problem is that it leads to co-mingling of designer-centric parts of the app with developer-focused parts of the app. Often times these implications may be ok for quick-and-dirty prototyping but would be nice to avoid for real apps.</p>
        <p>
          <img src="Content/Posts/SilverlightViewModel/ViewModel.png" alt="ViewModel Pattern" style="float: left; margin-right: 10px; margin-bottom: 10px" />The ViewModel pattern attempts to address these problems by encouraging separation of logic from the presentation. The data being presented is implemented as properties on the ViewModel, that the View consumes via data-binding. Secondly, most of the backing logic and operations are implemented as methods on the ViewModel that the view invokes via commanding. The key constraint is that the ViewModel is not dependent on View concepts such as choice of controls. The figure on the left illustrates this pattern. It is not a fundamentally different world, but rather something closer to a rearrangement and refactoring of the same pieces.</p>
        <p>Some folks might argue that all of code-behind is to be removed. I tend to think that some may remain, specifically, to facilitate view-to-view interactions that cannot be expressed declaratively in XAML easily, hence the sliver of code-behind in the view.</p>
        <p>This is simply one amongst many patterns that encourage discipline over what code goes where, how it is related to other code etc. The goal here is to think about how to get both long-term benefits from practicing discipline, as well as make it suitable for those smaller apps and quick-and-dirty experimental apps, by making this pattern emerge naturally from tooling guidance. I won't cover tooling today; perhaps another blog post on this down the road.</p>
        <p>
          <b>ViewModel In Action</b>
          <br />
Enough theory! Onto a running app... I've built a simple Amazon Search application using the ViewModel pattern, and the Silverlight.FX framework I've built to support it on top of Silverlight 2. You can play with it here, as well as <a href="Content/Posts/SilverlightViewModel/ViewModel.zip">download the entire solution</a> containing code for the sample, associated sampling of unit tests, and the framework it builds upon.</p>
        <break />
        <p style="text-align: center">
          <a href="Content/Posts/SilverlightViewModel/AmazonSearch.htm" style="text-decoration:none;border:none" title="Click to Run AmazonSearch">
            <img src="Content/Posts/SilverlightViewModel/AmazonSearch.png" border="0" />
          </a>
        </p>
        <p>
          <b>Implementing ViewModel via Action Behaviors</b>
          <br />
Both <a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx" target="_new">John Gossman</a> and <a href="http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx" target="_new">Dan Crevier</a> have blogged about this pattern in the context of WPF, where their approach builds on data-binding and commanding. Silverlight supports a subset of data-binding features, but doesn't currently provide a commanding mechanism. Instead of commanding, I'll build the glue between the view and the operations defined in the view model via Actions (as you'll see in a moment) that are then hooked up via my <a href="Silverlight-Behaviors.aspx">behaviors</a> framework.</p>
        <p>
          <img src="Content/Posts/SilverlightViewModel/Project.png" alt="AmazonSearch Sample in Solution Explorer" style="float:left; margin-right: 10px; margin-bottom: 10px" />Lets take a brief look at the implementation. I won't cover all the details, as you have the code and can step through as deeply as you'd prefer. On the right is my application's project structure.</p>
        <p>I have my data model defined in the Data namespace. The Product class is an entity that has properties like Title, ImageUrl, ASIN etc. The Catalog class provides data access logic built by consuming the Amazon ECS REST APIs and the WebClient object that supports cross-domain networking. This code is pretty straightforward and commonplace. The catalog class implements the ICatalog interface. This has been defined so that the data access functionality can be mocked in a straightforward way for unit testing (more on that at the end).</p>
        <p style="clear: both">The ViewModel is where it starts to get interesting. Being a developer, I'll start with that. It is defined in SearchView.model.cs as follows:</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> SearchViewModel : Model {
    <span style="color: #0000ff;">private</span> IEnumerable&lt;Product&gt; _products;
    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">string</span> _keyword;
    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">bool</span> _searching;

    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">bool</span> CanSearch {
        get {
            <span style="color: #0000ff;">return</span> !IsSearching;
        }
    }

    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">bool</span> IsSearching {
        get { <span style="color: #0000ff;">return</span> _searching; }
        <span style="color: #0000ff;">private</span> set {
             _searching = <span style="color: #0000ff;">value</span>;
             RaisePropertyChanged(<span style="color: #006080;">"IsSearching"</span>, <span style="color: #006080;">"CanSearch"</span>);
        }
    }

    <span style="color: #0000ff;">public</span> IEnumerable&lt;Product&gt; Products {
        get { <span style="color: #0000ff;">return</span> _products; }
        <span style="color: #0000ff;">private</span> set { _products = <span style="color: #0000ff;">value</span>; RaisePropertyChanged(<span style="color: #006080;">"Products"</span>); }
    }

    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">void</span> Search(<span style="color: #0000ff;">string</span> keyword) {
        _keyword = keyword;
        Searching = <span style="color: #0000ff;">true</span>;

        Catalog catalog = <span style="color: #0000ff;">new</span> Catalog();
        catalog.SelectProducts(keyword, OnCatalogProductsSelected);
    }

    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">void</span> OnCatalogProductsSelected(<span style="color: #0000ff;">string</span> keyword, Ienumerable&lt;Products&gt; products) {
        <span style="color: #0000ff;">if</span> (keyword != _keyword) { <span style="color: #0000ff;">return</span>; }

        Products = catalog.Products;
        Searching = <span style="color: #0000ff;">false</span>;
    }
}
</pre>
        <p>The first thing to notice is that this class is completely independent from the UI. As such it can be tested quite easily. It simply represents a list of products, and the ability to perform a search that populates that list of products. It does this by consuming the data model.</p>
        <p>This class derives from a class called Model from my framework, which supplies a default implementation of INotifyPropertyChange. The Model class also does some other nice things like cache PropertyChangedEventArg instances, and make sure change events are raised on the appropriate thread.</p>
        <p>The next thing to implement is the view. Here you might imagine its is something that is worked upon predominantly and independently by a designer in Blend. The designer is free to choose the controls, lay them out, add animations and other subtle visual polish. As the UI comes together it might then be declaratively bound to the properties and methods that the developer has made available in the view model.</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">vm:View</span>
          <span style="color: #ff0000;">xmlns</span>
          <span style="color: #0000ff;">="..."</span>
          <span style="color: #ff0000;">xmlns:x</span>
          <span style="color: #0000ff;">="..."</span>
          <span style="color: #ff0000;">xmlns:vm</span>
          <span style="color: #0000ff;">="clr-namespace:Silverlight.FX.ViewModel;assembly=Silverlight.FX"</span>
          <span style="color: #ff0000;">xmlns:app</span>
          <span style="color: #0000ff;">="clr-namespace:AmazonSearch.Views"</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:View.Model</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">app:SearchViewModel</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">vm:View.Model</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Grid</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="searchTextBox"</span>
          <span style="color: #0000ff;">/&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <b>
            <span style="color: #ff0000;">IsEnabled</span>
            <span style="color: #0000ff;">="{Binding CanSearch}"</span>
          </b>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:ButtonEvents.Click</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:InvokeMethod</span>
            <span style="color: #ff0000;">MethodName</span>
            <span style="color: #0000ff;">="Search"</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:ElementParameter</span>
            <span style="color: #ff0000;">ElementName</span>
            <span style="color: #0000ff;">="searchTextBox"</span>
            <span style="color: #ff0000;">ElementProperty</span>
            <span style="color: #0000ff;">="Text"</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">vm:InvokeMethod</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">vm:ButtonEvents.Click</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">ItemsControl</span>
          <span style="color: #ff0000;">ItemsSource</span>
          <span style="color: #0000ff;">="{Binding Products}"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">ItemsControl.ItemTemplate</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">DataTemplate</span>
          <span style="color: #0000ff;">&gt;&lt;</span>
          <span style="color: #800000;">app:ProductView</span>
          <span style="color: #0000ff;">/&gt;&lt;/</span>
          <span style="color: #800000;">DataTemplate</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">ItemsControl.ItemTemplate</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">ItemsControl</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">Grid</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">vm:View</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>The view is implemented by deriving from View, which is in turn derived from UserControl. This is just for convenience. It adds the concrete notion of an associated Model that is assigned to the DataContext property so it is inherited by the contained controls.</p>
        <p>The ItemsControl is bound to the list of products via vanilla data-binding already present in Silverlight.</p>
        <p>The equivalent of commands are implemented using Actions. Actions are simply behaviors that can be attached to an element, via an attached property that provides event trigger semantics. In the sample, the ViewModel exposes a CanSearch property and a Search method that provide commanding-like semantics in a simple manner. The search button's IsEnabled property is bound to CanSearch, and its Click event is bound to the Search method.</p>
        <p>I am not completely thrilled with the syntax, but this is perhaps the best that is doable, until the ability to define markup extensions becomes available in some future Silverlight version, and I might  eventually be able to declare something like this instead:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Button</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <b>
            <span style="color: #ff0000;">Click</span>
            <span style="color: #0000ff;">="{Action InvokeMethod Search(searchTextBox.Text)}"</span>
          </b>
          <span style="color: #ff0000;">IsEnabled</span>
          <span style="color: #0000ff;">="{Binding CanSearch}"</span>
          <span style="color: #0000ff;">/&gt;</span>
        </pre>
        <p>Actions are actually quite expressive since they are extensible and can encapsulate stock behaviors (the equivalent of stock commands). In the framework I have actions that work against storyboards (eg. PlayStoryboard), set properties etc. Here is another example of an action to perform the navigation whenever a search result is clicked.</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">Image</span>
          <span style="color: #ff0000;">Source</span>
          <span style="color: #0000ff;">="{Binding ImageUrl}"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">vm:MouseEvents.MouseLeftButtonDown</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">vm:Navigate</span>
            <span style="color: #ff0000;">NavigateUrl</span>
            <span style="color: #0000ff;">="{Binding ItemUrl}"</span>
            <span style="color: #ff0000;">Target</span>
            <span style="color: #0000ff;">="Amazon"</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">vm:MouseEvents.MouseLeftButtonDown</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">Image</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>
          <b>Unit Testing the View Model</b>
          <br />
One of the benefits of separation of concerns is easier testing of a greater portion of the application's code and functionality. Specifically, as the ViewModel is itself independent of the user interface, I should be able to easily unit test it.</p>
        <p>Here I am going to leverage the <a href="http://www.jeff.wilcox.name/2008/06/06/unit-testing-templates-for-microsoft-silverlight-2-beta-2/" target="_new">Silverlight Unit Testing Framework</a> to author tests for my ViewModel and then run them. This is also the place where I am going to leverage the fact that I defined an ICatalog interface earlier to represent my data access layer. For the unit tests, I am going to create a mock catalog implementation, that doesn't rely on making calls to the Amazon service.</p>
        <p>Here is one of my mock catalog implementations that returns a dummy product.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> TestCatalog : ICatalog {
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">void</span> SelectProducts(<span style="color: #0000ff;">string</span> keyword,
                               Action&lt;<span style="color: #0000ff;">string</span>, IEnumerable&lt;Product&gt;&gt; productsCallback) {
        DispatcherTimer timer = <span style="color: #0000ff;">new</span> DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(2);
        timer.Tick += <span style="color: #0000ff;">delegate</span>(<span style="color: #0000ff;">object</span> sender, EventArgs e) {
            Product testProduct =
                <span style="color: #0000ff;">new</span> Product {
                    ASIN = <span style="color: #006080;">"1"</span>,
                    By = <span style="color: #006080;">"TestAuthor"</span>,
                    ImageUrl = <span style="color: #006080;">"http://www.example.com"</span>,
                    ItemUrl = <span style="color: #006080;">"http://www.example.com"</span>,
                    Title = <span style="color: #006080;">"Test Title"</span>
                };

            productsCallback(keyword, <span style="color: #0000ff;">new</span> Product[] { testProduct });
        };
    }
}
</pre>
        <p>And here is one of the tests defined in my test class. Note that I am using the ability to write async tests.</p>
        <pre>
[TestClass]
<span style="color: #0000ff;">public</span><span style="color: #0000ff;">class</span> SearchViewModelTest : SilverlightTest {

    [TestMethod]
    [Asynchronous]
    [Description(<span style="color: #006080;">"Test a typical search result."</span>)]
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">void</span> TestSearchResult() {
        ICatalog mockCatalog = <span style="color: #0000ff;">new</span> TestCatalog();
        <span style="color: #0000ff;">bool</span> productsChanged = <span style="color: #0000ff;">false</span>;

        SearchViewModel viewModel = <span style="color: #0000ff;">new</span> SearchViewModel(mockCatalog);
        ((INotifyPropertyChanged)viewModel).PropertyChanged +=
            <span style="color: #0000ff;">delegate</span>(<span style="color: #0000ff;">object</span> sender, PropertyChangedEventArgs e) {
                <span style="color: #0000ff;">if</span> (e.PropertyName == <span style="color: #006080;">"Products"</span>) {
                    productsChanged = <span style="color: #0000ff;">true</span>;
                }
            };

        viewModel.Search(<span style="color: #006080;">"xyz"</span>);

        EnqueueConditional(() =&gt; productsChanged);
        EnqueueCallback(() =&gt; Assert.AreNotEqual(viewModel.Products, <span style="color: #0000ff;">null</span>,
                        <span style="color: #006080;">"Expected non-null products list."</span>));
        EnqueueCallback(() =&gt; Assert.AreNotEqual(viewModel.Products.Count(), 0,
                        <span style="color: #006080;">"Expected non-empty products list."</span>));
        EnqueueTestComplete();
    }
}
</pre>
        <p>Using the Unit Testing engine to execute my tests in the browser, i.e. running in the context of the Silverlight CLR, I see the following result, indicating goodness...</p>
        <p style="text-align: center">
          <img src="Content/Posts/SilverlightViewModel/UnitTesting.png" alt="Unit Test Run Screenshot" />
        </p>
        <p>
          <b>Summary</b>
          <br />
Hopefully this sample gave a good flavor of what the ViewModel pattern is all about, and how action behaviors can help create the bridge between the View and the ViewModel in Silverlight today. There are various other interesting discussion points and further exploration that relate to this, so stay tuned, but in the mean time I am curious what people think, and what questions arise as well, to help guide both the discussion, and the feature as its worked in into the framework.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/prototype" rel="tag">prototype</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=198#Comments</comments>
      <description>This post describes the ViewModel aka M-V-VM pattern, and presents a prototype Silverlight 2 framework for implementing this pattern using Action Behaviors (which provide the equivalent of commands)</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=198</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=198</link>
      <pubDate>Tue, 17 Jun 2008 19:35:20 GMT</pubDate>
      <title>ViewModel Pattern in Silverlight using Behaviors</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>A couple of weeks back, StyleCop, which used to be an internal tool was rebranded and publicly released as <a href="http://code.msdn.microsoft.com/sourceanalysis" target="_new">Microsoft Source Analysis</a>. Right around that time, we were having an internal discussion within the team around what sort of coding style guidelines we should put in place for a new project.</p>
        <p>Such discussions are always fun, and can serve as fodder for ongoing back and forth unless someone just gives in. If design guidelines are debatable (eg. Id vs ID), style guidelines are at least an order of magnitude more debatable; everyone has an opinion and a set of preferences around source code. I think what we really need is a system around how code is a model, not just text, and the editor is simply a view over that model that reflects a user's choice. In the meantime, we have guidelines, and tools such as StyleCop to help enforce them.</p>
        <p>Speaking about debatable guidelines, it seems one of the big point of debates was around the tool's default rule that tabs should not be used for indentation. I personally agree with that one, but I'll throw in an even more debatable rule that is a preference of mine (which unfortunately the tool doesn't default to): <a href="http://en.wikipedia.org/wiki/Bracing_style#K.26R_style" target="_new">K&amp;R bracing style</a>. You've already seen me use it in blog posts that contains code snippets. Ultimately, independent of specific stylistic choices, a consistent and predictable code base is a first step toward facilitating readability and discoverability. Definitely check out the tool if you haven't already.</p>
        <p>For those curious, I actually have a <a href="Content/Posts/Guidelines/CodingGuidelines.docx">coding guidelines document</a> I use that is mostly based on what we agreed on for the ASP.NET code base some years back. I tried to tweak the settings offered by the tool to create a <a href="Content/Posts/Guidelines/Settings.SourceAnalysis">matching set</a>, though I think I'll need to write some custom rules around ordering and spacing if I want the tool to exactly match my preferences.</p>
        <p>On a related note, this tool completely works as expected with <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> projects, as I expected. So, if you're using Script# to build an Ajax app or component, you too can now benefit from this tool. This just shows how a good chunk of both new and existing .NET tooling can be repurposed without much work.</p>
      </body>
      <category>Projects/Programming</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=197#Comments</comments>
      <description>A bit about code style guidelines, my own preferences and a pointer to StyleCop.</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=197</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=197</link>
      <pubDate>Fri, 06 Jun 2008 04:00:42 GMT</pubDate>
      <title>Microsoft Source Analysis aka StyleCop</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <img src="Content/Posts/Images/EEAward.jpg" style="float:right;margin-left:10px;margin-bottom:10px" />Every year, Microsoft holds an Engineering Excellence Conference. This is that week. In addition to a variety of conference sessions around engineering practices and trustworthy computing, a number of awards are handed out during the opening keynote.</p>
        <p>One of the awards that is handed out recognizes innovation in tools and practices that promote better engineering and have broad impact, and adoption. I am glad to share that this year, <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> was presented this award. :-)</p>
        <p>In terms of impact and adoption, a number of product teams across Microsoft are using Script# to implement their Ajax-based Web experiences. It is always fun to see folks adopting something you've worked on and creating some amazing applications, but more importantly, the award helps make a case for the productivity wins and the engineering discipline that Script# can bring to Ajax development by leveraging the .NET programming model and tools. In addition to <a href="Embeddable-IM-Control.aspx">Live Messenger</a> and <a href="Live-Mesh.aspx">Live Mesh</a>, there are others that are in the works (that I don't think I can share publicly just yet), but as always, I'll share as and when they do become public.</p>
        <p>I'd like to say thanks to those who helped champion the technology early on beyond just a personal project, and help improve the project - folks like <a href="http://blogs.msdn.com/messenger/archive/2008/02/28/welcome-to-the-windows-live-messenger-developer-blog.aspx" target="_new">Steve Gordon</a>, Shaofeng Zhu and <a href="http://blogs.msdn.com/jrock/" target="_new">Justin Rockwood</a> from Microsoft, and Wei Zhu, who is now at Facebook, as well as the many others, internal and external, who have shared feedback, bug reports and enthusiasm over the course of the last couple of years.</p>
        <p>I've been a bit on the busy side recently, but still to come is sharing sources over on the <a href="http://www.codeplex.com/ScriptSharp">CodePlex</a> site in addition to the ongoing discussion forums.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/script#" rel="tag">script#</a>  | <a href="http://www.nikhilk.net/tags/projects" rel="tag">projects</a> ]</div>
      </body>
      <category>Script#</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=196#Comments</comments>
      <description>Microsoft Engineering Excellence Award presented to Script#!</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=196</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=196</link>
      <pubDate>Thu, 05 Jun 2008 05:23:50 GMT</pubDate>
      <title>Engineering Excellence Award for Script#</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Yesterday I blogged about using and creating <a href="Silverlight-Behaviors.aspx">behaviors in Silverlight</a>. This post will walk you through an autocomplete behavior that will hopefully furher crystallize the behavior concept.</p>
        <p>To recap, a behavior is simply an object that can be declaratively attached to another component to extend the built in functionality of that component. Typically a behavior will encapsulate some event handling logic. This event handling logic could have been written by the app developer in their code-behind, but moving it into a behavior makes it much more encapsulated and suited for reuse. It has the nice side-effect of making things a bit more designer-friendly by cleaning up the code-behind and turning things into a more XAML-friendly form.</p>
        <p>
          <span style="border: solid 1px #EEEEEE; padding:3px; margin-right: 10px; margin-bottom: 10px; float: left">
            <img src="Content/Posts/SilverlightBehaviors/AutoComplete.png" />
          </span>Remember <a href="http://www.google.com/webhp?complete=1" target="_blank">Google Suggest</a>? That kicked off a spree of auto-complete implementations for use in Ajax apps including the one we did for ASP.NET Ajax (and later in the Ajax Control Toolkit). The AutoComplete behavior is very similar. It can be used to suggest various completions based on the text that a user has entered so far. This behavior allows extending the standard Silverlight TextBox control (as well as the WatermarkTextBox control). This post will cover various scenarios accomodated by the behavior I've put together.</p>
        <p>The screenshot above illustrates the type of experience you can add to any TextBox. You can see and play with a live demo by scrolling toward the end of this post (this requires Silverlight 2). Of course, all of the <a href="Content/Posts/SilverlightBehaviors/SilverlightFX.zip">code</a> is available as well, so you can include this into your own app.</p>
        <p style="clear: both">
          <b>Scenario 1: Basic completion scenario</b>
          <br />
Lets assume I've got a TextBox on a form that allows your user to enter in the name of a city, and I also have a service on the server that accepts a string prefix and returns a set of matching city names as an array of strings (serialized using the JSON format). I'd like to hook the two of them together to improve the user experience of the form, by offering a list of suggestions.</p>
        <p>Here's the most basic use of the AutoComplete behavior in XAML as a way to get started.</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="cityTextBox"</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">f:Form.AutoComplete</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">f:AutoComplete</span>
            <span style="color: #ff0000;">ServiceUri</span>
            <span style="color: #0000ff;">="/App_Services/Cities.ashx"</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">f:Form.AutoComplete</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>Done... no code required! The AutoComplete instance assigned to the Form.AutoComplete attached property listens the TextBox events and in the background fetches city suggestions, displays a dropdown list with the cities, and allows the user to pick one. The AutoComplete does all sorts of fancy things by default like not fire off a web request per keystroke, cache results etc. As you can see the declarative XAML-based usage model makes the scenario quite simple to implement.</p>
        <break />
        <p>Here's the corresponding server-side code implementing the service in Cities.ashx:</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> CityCompletionService : CompletionService&lt;<span style="color: #0000ff;">string</span>&gt; {

    <span style="color: #0000ff;">protected</span><span style="color: #0000ff;">override</span> IEnumerable&lt;<span style="color: #0000ff;">string</span>&gt; GetItems(<span style="color: #0000ff;">string</span> prefix) {
        <span style="color: #0000ff;">string</span>[] matchingCities = ...;
        <span style="color: #0000ff;">return</span> matchingCities;
    }
}
</pre>
        <p>
          <b>Scenario 2: Styling the user interface</b>
          <br />
One of the most compelling aspects of XAML and Silverlight is the ability to create compelling user interfaces by restyling and reskinning controls to match the overall look and feel of your application. The AutoComplete behavior supports this by allowing you to specify a template for the dropdown used by the behavior. If I've got some customized look and feel defined in the myCustomListBox style, I can reference it as follows:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="cityTextBox"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:Form.AutoComplete</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:AutoComplete</span>
          <span style="color: #ff0000;">ServiceUri</span>
          <span style="color: #0000ff;">="/App_Services/Cities.ashx"</span>
          <span style="color: #0000ff;">&gt;</span>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">f:AutoComplete.DropDownTemplate</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">DataTemplate</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">ListBox</span>
            <span style="color: #ff0000;">Style</span>
            <span style="color: #0000ff;">="{StaticResource myCustomListBox}"</span>
            <span style="color: #0000ff;">/&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">DataTemplate</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <b>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">f:AutoComplete.DropDownTemplate</span>
            <span style="color: #0000ff;">&gt;</span>
          </b>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">f:AutoComplete</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">f:Form.AutoComplete</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>
          <b>Scenario 3: Going beyond strings</b>
          <br />
So far the service backing the completion experience has been returning an array of strings. I actually want to use a service that returns something more than just a string (you'll see why in the next step). For example, in this scenario, I want to return an array of CityInfo objects that contain Name, State and ZipCode properties.</p>
        <p>Here is the updated service implementation on the server.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> CityInfo {
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> ZipCode { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
}

<span style="color: #0000ff;">public</span><span style="color: #0000ff;">class</span> CityCompletionService : CompletionService&lt;CityInfo&gt; {

    <span style="color: #0000ff;">protected</span><span style="color: #0000ff;">override</span> IEnumerable&lt;CityInfo&gt; GetItems(<span style="color: #0000ff;">string</span> prefix) {
        CityInfo[] matchingCities = ...;
        <span style="color: #0000ff;">return</span> matchingCities;
    }
}
</pre>
        <p>In order to implement this scenario on the client I need to do a couple of things. First I need to provide a client-side type that the AutoComplete behavior uses to deserialize the JSON into. Next I'll want to customize the ItemTemplate of the ListBox to display the additional fields. Finally, I'll want to handle the Completed event to convert a CityInfo object into text that is used to put into the TextBox once a user selects a particular city.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> CityInfo {
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> Name { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> State { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> ZipCode { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> Location {
        <span style="color: #0000ff;">get</span> {
            <span style="color: #0000ff;">return</span><span style="color: #006080;">" ("</span> + State + <span style="color: #006080;">", "</span> + ZipCode + <span style="color: #006080;">")"</span>;
        }
    }
}

<span style="color: #0000ff;">&lt;</span><span style="color: #800000;">TextBox</span><span style="color: #ff0000;">x:Name</span><span style="color: #0000ff;">="cityTextBox"</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">f:Form.AutoComplete</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">f:AutoComplete</span><span style="color: #ff0000;">ServiceUri</span><span style="color: #0000ff;">="/App_Services/Cities.ashx"</span><b><span style="color: #ff0000;">ServiceResultType</span><span style="color: #0000ff;">="CityInfo"</span></b><b><span style="color: #ff0000;">Completed</span><span style="color: #0000ff;">="OnCityCompleted"</span></b><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">f:AutoComplete.DropDownTemplate</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">DataTemplate</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">ListBox</span><span style="color: #0000ff;">&gt;</span><b><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">ListBox.ItemTemplate</span><span style="color: #0000ff;">&gt;</span></b><b><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">DataTemplate</span><span style="color: #0000ff;">&gt;</span></b><b><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">StackPanel</span><span style="color: #0000ff;">&gt;</span></b><b><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">TextBlock</span><span style="color: #ff0000;">Text</span><span style="color: #0000ff;">="{Binding Name}"</span><span style="color: #0000ff;">/&gt;</span></b><b><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">TextBlock</span><span style="color: #ff0000;">Text</span><span style="color: #0000ff;">="{Binding Location}"</span><span style="color: #0000ff;">/&gt;</span></b><b><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">StackPanel</span><span style="color: #0000ff;">&gt;</span></b><b><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">DataTemplate</span><span style="color: #0000ff;">&gt;</span></b><b><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">ListBox.ItemTemplate</span><span style="color: #0000ff;">&gt;</span></b><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">ListBox</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">DataTemplate</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">f:AutoComplete.DropDownTemplate</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">f:AutoComplete</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">f:Form.AutoComplete</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">TextBox</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">private</span><span style="color: #0000ff;">void</span> OnCityCompleted(<span style="color: #0000ff;">object</span> sender, AutoCompleteCompletedEventArgs e) {
    <span style="color: #008000;">// This event handler is optional. By default e.SelectedItem.ToString()</span><span style="color: #008000;">// is used by the AutoComplete.</span><b>e.SelectedItem = ((CityInfo)e.SelectedItem).Name;</b>
}
</pre>
        <p>
          <b>Scenario 4: Filling dependent TextBoxes</b>
          <br />
There was a reason to return CityInfo objects instead of simply city names. Lets say my form also has a TextBox for entering ZipCode. If the user selects a city from the auto-complete dropdown, I'd also like to fill the zip code for added convenience.</p>
        <p>I can simply update my Completed event handler above to extract the ZipCode and populate the ZipCode TextBox accordingly.</p>
        <pre>
          <span style="color: #0000ff;">private</span>
          <span style="color: #0000ff;">void</span> OnCityCompleted(<span style="color: #0000ff;">object</span> sender, AutoCompleteCompletedEventArgs e) {
    <b>zipCodeTextBox.Text = ((CityInfo)e.SelectedItem).ZipCode;</b>
    e.SelectedItem = ((CityInfo)e.SelectedItem).Name;
}
</pre>
        <p>
          <b>Scenario 5: Using local computed values</b>
          <br />
So far I've been showing scenarios where the AutoComplete behavior makes a web request to get at the list of the completion items to show in its dropdown. Some times, an app might want to show a list of values computed in client-side logic. Or you may have already loaded data from a web service call, and just want to plug in that data, rather than making a separate call.</p>
        <p>This scenario is implementable by handling the Completing event of the AutoComplete behavior which allows you to either plug in your items, or to suppress the dropdown altogether for the particular prefix text that the user has entered. For example:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="cityTextBox"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:Form.AutoComplete</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:AutoComplete</span>
          <b>
            <span style="color: #ff0000;">Completing</span>
            <span style="color: #0000ff;">="OnCityCompleting"</span>
          </b>
          <span style="color: #0000ff;">/&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">f:Form.AutoComplete</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">private</span>
          <span style="color: #0000ff;">void</span> OnCityCompleting(<span style="color: #0000ff;">object</span> sender, AutoCompleteCompletingEventArgs e) {
    <span style="color: #0000ff;">string</span> prefix = e.Prefix;

    <span style="color: #0000ff;">string</span>[] cities = ...; <span style="color: #008000;">// code to lookup some local data using prefix</span><b>e.SetCompletionItems(cities);</b>
}
</pre>
        <p>
          <b>Live Demo</b>
          <br />
Finally, here is a demo of the AutoComplete behavior. To experiment, type in something "San" in the city TextBox to see a list of cities pop up. Select a city (such as San Francisco) to see both the city and the zip code TextBoxes get filled.</p>
        <p align="center">
          <iframe src="Content/Posts/SilverlightBehaviors/AutoComplete.htm" frameborder="0" style="border: solid 1px #CDCDCD; width: 600px; height:150px">
          </iframe>
        </p>
        <p>
          <b>Yet another behavior... TextFilter</b>
          <br />
Actually, I've slipped in another behavior as well into the mix, just for some more fun. This is the TextFilter behavior that can also be associated with a TextBox to restrict input to say numeric characters.</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="zipCodeTextBox"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:Form.Filter</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:TextFilter</span>
          <span style="color: #ff0000;">Filter</span>
          <span style="color: #0000ff;">="Numbers"</span>
          <span style="color: #0000ff;">/&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">f:Form.Filter</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #0000ff;">&gt;</span>
        </pre>
        <p>Hopefully these examples really start making the behavior concept more concrete, and clear.</p>
        <p>You can <a href="Content/Posts/SilverlightBehaviors/SilverlightFX.zip">download the code</a>, which includes the behavior framework, all the behaviors I've written about so far, as well as a sample app that demonstrates using them. Enjoy!</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/prototype" rel="tag">prototype</a>  | <a href="http://www.nikhilk.net/tags/xaml" rel="tag">xaml</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=195#Comments</comments>
      <description>An implementation of AutoComplete functionality that you can add to your TextBoxes in XAML... ala Google Suggest and the ASP.NET AutoComplete control extender (built on top of the behavior framework).</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=195</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=195</link>
      <pubDate>Wed, 07 May 2008 00:19:41 GMT</pubDate>
      <title>AutoComplete for Silverlight TextBoxes</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>In the past, I've written about behaviors and control extenders in the context of Ajax and HTML-based UI. This post introduces a similar behavior semantics for Silverlight and XAML-based UI as well.</p>
        <p>The mini-behavior framework I have prototyped allows you to write and use behavior as a combination of a component + an attached property. The framework provides the logic to attach/detach behaviors for behavior authors. The rest of this post demonstrates using and writing a simple behavior based on this framework. Over the next few posts, I'll discuss a few more behaviors as a way to further experiment and demonstrate the behavior concept.</p>
        <p>
          <b>Using the DefaultCommit Behavior</b>
          <br />
Lets say you're implementing a typical form with a TextBox and a search Button. You'll probably want to allow users to press the Enter key after typing in some search keywords to kick off the search rather than force them to click the button explicitly. What you'd normally do is write a couple of event handlers to handle both the Click event from the Button and the KeyDown event from the TextBox (to look for the Enter key) in your code-behind, and trigger the search logic from each of them. This is more complicated and messy than it needs to be.</p>
        <p>Ideally you simply want to handle a single event - the button's Click event. In fact, in HTML forms, this is built in into the notion of a Form with a submit button. However, it isn't so in Silverlight, where a Form concept is baked in. This is where this behavior comes in. Once this behavior is available, I can author the following XAML:</p>
        <pre>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="searchTextBox"</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:Form.Commit</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:DefaultCommit</span>
          <span style="color: #ff0000;">ButtonName</span>
          <span style="color: #0000ff;">="searchButton"</span>
          <span style="color: #0000ff;">/&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">f:Form.Commit</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;/</span>
          <span style="color: #800000;">TextBox</span>
          <span style="color: #0000ff;">&gt;</span>
          <span style="color: #0000ff;">&lt;</span>
          <span style="color: #800000;">f:Button</span>
          <span style="color: #ff0000;">x:Name</span>
          <span style="color: #0000ff;">="searchButton"</span>
          <span style="color: #ff0000;">Content</span>
          <span style="color: #0000ff;">="Search"</span>
          <span style="color: #ff0000;">Click</span>
          <span style="color: #0000ff;">="OnSearchButtonClick"</span>
          <span style="color: #0000ff;">/&gt;</span>
        </pre>
        <break />
        <p>Essentially the DefaultCommit behavior is attached to the TextBox using the XAML syntax above. For those new to XAML and Silverlight, f:Form.Commit refers to the Commit attached property offered by the Form class. This is similar to Canvas.Left, which you've probably encountered. The only difference is that the type of the Canvas.Left attached property is a simple double value, whereas the type of the Form.Commit property is a DefaultCommit.</p>
        <p>Underneath the covers, the DefaultCommit behavior does the same thing you'd do in code-behind, but does so in a way that the logic is now encapsulated and is easily reusable. You can instantiate as many of these as you want, especially across multiple forms/pages without duplicating the event handling logic all over.</p>
        <p>Here is a live demo (if you've got Silverlight installed) - simply type in something and press Enter. The app behaves as if you had clicked the button. There is no really search hooked up though.</p>
        <p align="center">
          <iframe src="Content/Posts/SilverlightBehaviors/Search.htm" frameborder="0" style="border: solid 1px #CDCDCD; width: 600px; height:125px">
          </iframe>
        </p>
        <p>You might have noticed the use of &lt;f:Button&gt; instead of a regular Button. Unfortunately, unlike WinForms and HTML buttons, the Silverlight Button control currently doesn't have any way to programmatically invoke the Click event, so I had to add that functionality in a derived class.</p>
        <p>
          <b>Implementing the DefaultCommit Behavior</b>
          <br />
The behavior framework I have put together introduces two classes Behavior and BehaviorManager.</p>
        <p>The first step is to implement a behavior by deriving from the Behavior class. The Behavior class is a generic class, to allow indicating the type of objects that behavior can be associated with.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> DefaultCommit : Behavior&lt;TextBox&gt; {
}
</pre>
        <p>The next step is to add any properties exposed by the behavior itself.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> DefaultCommit : Behavior&lt;TextBox&gt; {

    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">string</span> _buttonName;
    
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">string</span> ButtonName {
        <span style="color: #0000ff;">get</span> { <span style="color: #0000ff;">return</span> _buttonName; }
        <span style="color: #0000ff;">set</span> { _buttonName = <span style="color: #0000ff;">value</span>; }
    }
}
</pre>
        <p>The behavior base class holds the reference to the associated object as  its AssociatedObject property. It defines a couple of abstract methods to manage the lifetime of a behavior instance: OnAttach, and OnDetach. The derived behavior class implements these to perform associated logic, such as setup and cleanup including subscribing and unsubscribing to events raised by the associated object.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">class</span> DefaultCommit : Behavior&lt;TextBox&gt; {

    <span style="color: #0000ff;">protected</span><span style="color: #0000ff;">override</span><span style="color: #0000ff;">void</span> OnAttach() {
        AssociatedObject.KeyDown += OnTextBoxKeyDown;
    }
    
    <span style="color: #0000ff;">protected</span><span style="color: #0000ff;">override</span><span style="color: #0000ff;">void</span> OnDetach() {
        AssociatedObject.KeyDown -= OnTextBoxKeyDown;
    }
    
    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">void</span> OnTextBoxKeyDown(<span style="color: #0000ff;">object</span> sender, KeyEventArgs e) {
        <span style="color: #0000ff;">if</span> ((e.Key == Key.Enter) &amp;&amp; (AssociatedObject.Text.Length != 0)) {
            Button button = AssociatedObject.FindName(_buttonName) <span style="color: #0000ff;">as</span> Button;
            <span style="color: #0000ff;">if</span> (button != <span style="color: #0000ff;">null</span>) {
                button.PerformClick();
            }
        }
    }
}
</pre>
        <p>The final step is to define an attached property that can be used to declaratively create an instance of this behavior and have it be associated with a TextBox. This is where the BehaviorManager class will come into play. It provides a set of utility methods that correctly attach/detach behaviors.</p>
        <pre>
          <span style="color: #0000ff;">public</span>
          <span style="color: #0000ff;">static</span>
          <span style="color: #0000ff;">class</span> Form {

    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">static</span><span style="color: #0000ff;">readonly</span> DependencyProperty CommitProperty =
        DependencyProperty.RegisterAttached(<span style="color: #006080;">"Commit"</span>, <span style="color: #0000ff;">typeof</span>(Form), <span style="color: #0000ff;">typeof</span>(DefaultCommit),
            OnCommitPropertyChanged);
    
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">static</span> DefaultCommit GetCommit(TextBox textBox) {
        <span style="color: #0000ff;">return</span> BehaviorManager.GetBehavior&lt;DefaultCommit&gt;(textBox);
    }
    
    <span style="color: #0000ff;">public</span><span style="color: #0000ff;">static</span><span style="color: #0000ff;">void</span> SetCommit(TextBox textBox, DefaultCommit commitBehavior) {
        BehaviorManager.SetBehavior(textBox, commitBehavior);
    }
    
    <span style="color: #0000ff;">private</span><span style="color: #0000ff;">void</span> OnCommitPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) {
        BehaviorManager.UpdateBehavior(o, CommitProperty,
                                       (DefaultCommit)e.OldValue,
                                       (DefaultCommit)e.NewValue);
    }
}
</pre>
        <p>There you go... writing a basic behavior is quite straightforward.</p>
        <p>
          <b>Concepts and Next Steps</b>
          <br />
One rough analogy to behaviors is that of extension methods in C# 3.0. Those are at the method level. Behaviors are similar, but are live components. More specifically, a behavior is a component that encapsulates some functionality and can be attached to another component to extend its built-in functionality, without creating a derived class. A couple of example behaviors that can be attached to a TextBox besides the one implemented above include auto-complete and input filtering.</p>
        <p>The fact that behaviors are attached components that implies a composition-like metaphor, offers two advantages whenever derivation is non-essential:
<ul><li>Allows "extending" multiple component types - in the TextBox example, the behaviors can be attached not only to TextBox but also to WatermarkTextBox.</li><li>A single TextBox can be associated with multiple behaviors as needed, rather than requiring the developer to build and use a kitchen-sink style control that has to anticipate every possible feature.</li></ul></p>
        <p>Almost all behaviors handle events and encapsulate a set of event handlers into a reusable component that can then be instanced declaratively. Often this leads to a more declarative style of programming (something I love) and reduced code-behind clutter.</p>
        <p>I chose a simple behavior scenario to introduce the concept. In a future post, I'll demonstrate some more interesting behaviors, including AutoComplete , and some animation scenarios. Stay tuned. Over time, I'll continue to experiment with this. I have some ideas on implementing declarative views that are enabled via this concept.</p>
        <p>I'd love to hear ideas you might have for behaviors that would be useful additions for Silverlight and XAML-based UI, and especially for RIA scenarios.</p>
        <p>You can also <a href="Content/Posts/SilverlightBehaviors/SilverlightFX.zip">download the code</a> which contains the behavior framework, the sample behavior, and a sample app that makes use of them.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/xaml" rel="tag">xaml</a>  | <a href="http://www.nikhilk.net/tags/prototype" rel="tag">prototype</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=194#Comments</comments>
      <description>A framework for creating reusable and attachable behaviors in Silverlight, and a sample behavior that demonstrates using and building them... along with all the code.</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=194</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=194</link>
      <pubDate>Mon, 05 May 2008 14:46:49 GMT</pubDate>
      <title>Silverlight Behaviors</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <img src="http://projects.nikhilk.net/ScriptSharp/Content/Showcase/Mesh.png" style="float: right; margin-left; 10px; margin-bottom: 10px" />
          <a href="http://www.mesh.com" target="_blank">Live Mesh</a> is finally public - it was announced earlier today at the Web 2.0 conference. We’ve had the <i>social graph</i> buzzword bantered around for some time in the context of Facebook. Will <i>mesh</i> become the next one to go around? Check out the <a href="http://dev.live.com/blogs/devlive/archive/2008/04/22/279.aspx" target="_blank">intro post</a>. Live Mesh is all about software + services, and connecting and bringing devices together into your own personal "mesh" enabling them to work in a connected way.</p>
        <p>Ray Ozzie alluded to the Web as the Hub of the social mesh and the device mesh earlier at MIX08. Over on the <a href="http://blogs.msdn.com/livemesh/archive/2008/04/21/live-mesh-as-a-platform.aspx" target="_blank">Live Mesh blog</a>, Mike Zintel alludes to a bunch of concepts around the Live Mesh platform, such as <i>mesh object</i>, and a data synchronization platform. I am particularly excited about the prospect of seeing a new generation of Web apps that leverage the platform in all sorts of interesting ways, not just for local storage, but also synchronized local storage of application data and personal data, and offline execution, as a means to differentiate and cater to new user experiences on the Web. The APIs that emerge around this platform will be something to keep an eye on.</p>
        <p>On another personal note, I am super excited to see and run the Web version of Live Mesh, which simulates a Vista desktop and Explorer folders right within your Web browser for anywhere access to your devices and a data. While it will be interesting to see the user reactions around this UI metaphor in the browser as shown in the screenshot, the Ajax code behind the scenes is pretty much written in <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> (I've worked with the team for a while), and now that the site is public, I’ve added it to the new <a href="http://projects.nikhilk.net/ScriptSharp/Showcase.aspx">showcase</a> page on my project site.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/mesh" rel="tag">mesh</a>  | <a href="http://www.nikhilk.net/tags/ajax" rel="tag">ajax</a>  | <a href="http://www.nikhilk.net/tags/script#" rel="tag">script#</a> ]</div>
      </body>
      <category>(All)</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=193#Comments</comments>
      <description>Live Mesh announced...</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=193</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=193</link>
      <pubDate>Wed, 23 Apr 2008 05:34:19 GMT</pubDate>
      <title>Live Mesh</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>This is a quick post on the latest release of <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> (Build 0.5). I'll be following up with subsequent posts with more details on some of the specific feature additions, but here is a list of whats new (besides bug fixes, and improved compiler error reporting):
<ul><li>Support for localization based on .resx files - now you can generate localized script files while using strongly typed resources using .resx tooling available in Visual Studio and other localization tools.</li><li>Support for generating script doc-comments - now XML doc-comments are automatically transformed into ASP.NET Ajax-style doc-comments, which are useful for driving intellisense in Visual Studio, if you're creating script libraries that will be used by others.</li><li>Updated compat layer to abstract browser differences now works for not just Mozilla but also WebKit-based (Safari, iPhone), and Opera browsers.</li><li>Support for creating overloaded APIs, and creating and invoking functions dynamically (these were limitations in the past).</li><li>Support for creating Silverlight 2 plugin instances.</li></ul></p>
        <p>Also, Script# is now on <a href="http://www.codeplex.com/ScriptSharp">CodePlex</a> (actually it has been on there for a month or so, but this is the first release since). The forums associated with the CodePlex project should significantly improve the experience around sending feedback, and having discussions around the technology and using it. Several folks have asked me in the past about open sourcing it. My plan is to eventually have the source out there as the project approaches its v1 status, starting the with the core framework and runtime, and subsequently the compiler itself. Stay tuned on that front for more in the next few months.</p>
        <p>There are a couple of related CodePlex projects to call out:
<ul><li><a href="http://www.codeplex.com/messenger" target="_blank">Messenger Developer Samples</a> - contains MIX08 Messenger samples including how you can use Messenger APIs using Script#</li><li><a href="http://www.codeplex.com/AJAXCodeGeneration" target="_blank">Script# proxy generator</a> - Think wsdl.exe for Script#. A number of you have sent me mail about this feature. This project basically takes care of generating C# proxies for ASP.NET Ajax-enabled Web services.</li></ul></p>
        <p>Finally, I've updated my <a href="http://projects.nikhilk.net/ScriptSharp">project</a> site as well with more introduction to Script#, release notes, and a high-level roadmap. I will also be transitioning the documentation that is currently available in pdf form to the site over time.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/script#" rel="tag">script#</a>  | <a href="http://www.nikhilk.net/tags/ajax" rel="tag">ajax</a>  | <a href="http://www.nikhilk.net/tags/projects" rel="tag">projects</a>  | <a href="http://www.nikhilk.net/tags/codeplex" rel="tag">codeplex</a> ]</div>
      </body>
      <category>Script#</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=192#Comments</comments>
      <description>Some words about the latest release of script#, now on CodePlex, and with support for localization, doc-comments and more.</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=192</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=192</link>
      <pubDate>Mon, 21 Apr 2008 21:02:15 GMT</pubDate>
      <title>Script# 0.5 Update and Associated CodePlex Project</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>Just over a month ago, at MIX08, I presented a talk on Real-World Ajax. One of the demos I included was an Ajax templating technique to demonstrate separation of presentation and content from behavior to help manage script complexity, and to help facilitate designer/developer workflow.</p>
        <p>The demo was based on early thoughts around what we need to do in this area. What is presented here is still quite simplistic in terms of the range of options it provides to developers. The demo worked well with the audience, and I'd love to hear any feedback people have in this area that can be fed into the design process at this early stage (I alluded to this work in comments to my <a href="Ajax-vs-Silverlight-and-NET.aspx">Ajax vs. Silverlight</a> post).</p>
        <p>Here is my scenario - in my Ajax app, script issues a web request to fetch a list of data, in this case a list of bookmarks, and constructs HTML to visualize the results. This is often implemented as follows:</p>
        <p>
          <pre>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">div</span>
            <span style="color: #ff0000;">id</span>
            <span style="color: #0000ff;">="bookmarkList"</span>
            <span style="color: #0000ff;">&gt;&lt;/</span>
            <span style="color: #800000;">div</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">script</span>
            <span style="color: #ff0000;">type</span>
            <span style="color: #0000ff;">="text/javascript"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">function</span> fetchBookmarks() { 
    <span style="color: #008000;">// Issue an XMLHTTP request to retrieve user's bookmarks.</span>
}
<span style="color: #0000ff;">function</span> onBookmarksAvailable(bookmarks) {
    <span style="color: #008000;">// Update display using retrieved bookmarks. Each boomark has Url and Title properties.</span><span style="color: #0000ff;">var</span> sb = <span style="color: #0000ff;">new</span> Sys.StringBuilder();
    sb.append(<span style="color: #006080;">"&lt;ul&gt;"</span>);
    <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> i = 0; i &lt; bookmarks.length; i++) {
        sb.append(<span style="color: #006080;">"&lt;li&gt;"</span>);
        sb.append(<span style="color: #006080;">"&lt;a href=\""</span>);
        sb.append(bookmarks[i].Url);
        sb.append(<span style="color: #006080;">"\"&gt;"</span>);
        sb.append(bookmarks[i].Title);
        sb.append(<span style="color: #006080;">"&lt;/li&gt;"</span>);
    }
    sb.append(<span style="color: #006080;">"&lt;/ul&gt;"</span>);
    $get(<span style="color: #006080;">'bookmarkList'</span>).innerHTML = sb.toString();
}
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">script</span><span style="color: #0000ff;">&gt;</span></pre>
        </p>
        <p>This works. However, there is a problem. The definition of the UI is now embedded in script. Its hard to design and change it. And its hard to preview it without running the page. The problem is worse if the structure of each item is more complicated than what the sample tries to do.</p>
        <p>Here is where templating comes into the picture. Templates have been super common in server-side frameworks like ASP.NET, and are now popping up in client-side script frameworks, as Ajax apps start becoming more client-centric. With templating the developer or designer can define the structure of an item in regular markup, and the templating engine is then responsible for generating the script equivalent.</p>
        <break />
        <p>In the demo, I wrote a simple template engine, which I can use by to rewrite the script as follows:</p>
        <p>
          <pre>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">div</span>
            <span style="color: #ff0000;">id</span>
            <span style="color: #0000ff;">="bookmarkList"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">ul</span>
            <span style="color: #ff0000;">id</span>
            <span style="color: #0000ff;">="itemContainer"</span>
            <span style="color: #0000ff;">&gt;&lt;/</span>
            <span style="color: #800000;">ul</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;/</span>
            <span style="color: #800000;">div</span>
            <span style="color: #0000ff;">&gt;</span>
            <b>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">div</span>
              <span style="color: #ff0000;">id</span>
              <span style="color: #0000ff;">="bookmarkTemplate"</span>
              <span style="color: #ff0000;">style</span>
              <span style="color: #0000ff;">="display: none"</span>
              <span style="color: #0000ff;">&gt;</span>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">ul</span>
              <span style="color: #ff0000;">id</span>
              <span style="color: #0000ff;">="itemContainer"</span>
              <span style="color: #0000ff;">&gt;</span>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">li</span>
              <span style="color: #0000ff;">&gt;&lt;</span>
              <span style="color: #800000;">a</span>
              <span style="color: #ff0000;">href</span>
              <span style="color: #0000ff;">="{Url}"</span>
              <span style="color: #0000ff;">&gt;</span>{Title}<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">a</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">ul</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">div</span><span style="color: #0000ff;">&gt;</span></b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">script</span>
            <span style="color: #ff0000;">type</span>
            <span style="color: #0000ff;">="text/javascript"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">function</span> fetchBookmarks() {
    <span style="color: #008000;">// Issue an XMLHTTP request to retrieve user's bookmarks.</span>
}
<span style="color: #0000ff;">function</span> onBookmarksAvailable(bookmarks) {
    <span style="color: #008000;">// Update display using retrieved bookmarks. Each boomark has Url and Title properties.</span><b><span style="color: #0000ff;">var</span> template = <span style="color: #0000ff;">new</span> Templating.Template($get(<span style="color: #006080;">'boomarkTemplate'</span>));</b><span style="color: #0000ff;">var</span> itemContainer = $get(<span style="color: #006080;">'itemContainer'</span>, $get(<span style="color: #006080;">'bookmarkList'</span>));

    <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">var</span> i = 0; i &lt; bookmarks.length; i++) {
        <b><span style="color: #0000ff;">var</span> item = template.createInstance(bookmarks[i]);</b>
        itemContainer.appendChild(item);
    }
}
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">script</span><span style="color: #0000ff;">&gt;</span></pre>
        </p>
        <p>The interesting lines are in bold. The template is defined using regular XHTML markup representing how items should appear. This can be independently edited/designed and previewed. You simply embed atomic tokens such {Url} etc. into the markup.</p>
        <p>The script is responsible for creating the template, which effectively generates the script equivalent, (this is done once), and then as the script loops over the list of bookmarks, it uses the template to create new instances of the list items and anchors, and adds them into the DOM to generate the display.</p>
        <p>With this we have a client-side templating mechanism. However web development is all about balancing and meeting several requirements (at once). In particular here are some of the things I also want to tackle as a developer.
<ul><li><b>Search Engine Optimization</b>: Ideally the page rendered by the server isn't blank from the perspective of the search engine. I demonstrated a solution in my <a href="AjaxSEO.aspx">Ajax and SEO</a> post over year ago.</li><li><b>Optimizing Networking</b>: I don't want to spend one connection downloading a blank page, and then immediately having the script turn around to issue another connection to fetch the first page worth of data.</li><li><b>Reducing Page Load Time</b>: Sending a blank page implies some delay as scripts are downloaded, loaded and data is loaded and processed to show data to the user. This should be avoided if at all possible.</li><li><b>Script-disabled browsers</b>: If targeting an audience that might have script disabled (this is perhaps a shrinking number), then being able to still deliver a degraded but functional experience is nice.</li></ul></p>
        <p>These can be addressed through some form of server-side rendering, sort of how you've been doing using server-side data-bound controls for years. The goal however, in the context of Ajax, is to leverage a single template definition for both server-side and client-side processing. This is where server controls really shine. They allow you to do Ajax better by providing end-to-end solutions.</p>
        <p>I've written an AjaxRepeater server control as part of the prototype. It does server-side data-binding (using the same token format we've seen above), renders the list on the server, but also generates a client-side Repeater control (using the ASP.NET Ajax UI pattern for writing controls). The client-side Repeater control consumes the same template definition, and provides the ability to dynamically add rows on the client, or reset the list of items to be displayed. The sample below illustrates using this control, along with both server-side code and client-side script working against it.</p>
        <p>
          <pre>
            <b>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">n:AjaxRepeater</span>
              <span style="color: #ff0000;">runat</span>
              <span style="color: #0000ff;">="server"</span>
              <span style="color: #ff0000;">id</span>
              <span style="color: #0000ff;">="bookmarkList"</span>
              <span style="color: #0000ff;">&gt;</span>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">ul</span>
              <span style="color: #ff0000;">id</span>
              <span style="color: #0000ff;">="itemContainer"</span>
              <span style="color: #0000ff;">&gt;</span>
              <span style="color: #0000ff;">&lt;</span>
              <span style="color: #800000;">li</span>
              <span style="color: #0000ff;">&gt;&lt;</span>
              <span style="color: #800000;">a</span>
              <span style="color: #ff0000;">href</span>
              <span style="color: #0000ff;">="{Url}"</span>
              <span style="color: #0000ff;">&gt;</span>{Title}<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">a</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">ul</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">n:AjaxRepeater</span><span style="color: #0000ff;">&gt;</span></b>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">script</span>
            <span style="color: #ff0000;">runat</span>
            <span style="color: #0000ff;">="server"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">void</span> Page_Load() {
    bookmarkList.DataSource = <span style="color: #0000ff;">new</span> Bookmark[] {
            <span style="color: #0000ff;">new</span> Bookmark { Title=<span style="color: #006080;">"..."</span>, Url=<span style="color: #006080;">"..."</span> }, ...
        };
    bookmarkList.DataBind();
}
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">script</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">script</span><span style="color: #ff0000;">type</span><span style="color: #0000ff;">="text/javascript"</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">function</span> addBookmark(title, url) {
    <span style="color: #0000ff;">var</span> bookmark = { Title: title, Url: url };
    $find(<span style="color: #006080;">'bookmarkList'</span>).addDataItem(bookmark);
}
<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">script</span><span style="color: #0000ff;">&gt;</span></pre>
        </p>
        <p>The current implementation is pretty much based on what can be done via String.Format to perform substitutions of tokens in the template with actual data (I used a tweaked version of James' <a href="http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx" target="_new">FormatWith</a> code). Eventually the hope is to productize this feature, and at that point we'd like you to be able add expressions in the template as well as express conditional segments within the template. For example, one might be able to write this:</p>
        <p>
          <pre>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">n:AjaxRepeater</span>
            <span style="color: #ff0000;">runat</span>
            <span style="color: #0000ff;">="server"</span>
            <span style="color: #ff0000;">id</span>
            <span style="color: #0000ff;">="bookmarkList"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">ul</span>
            <span style="color: #ff0000;">id</span>
            <span style="color: #0000ff;">="itemContainer"</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">li</span>
            <span style="color: #0000ff;">&gt;</span>
            <span style="color: #0000ff;">&lt;</span>
            <span style="color: #800000;">a</span>
            <span style="color: #ff0000;">href</span>
            <span style="color: #0000ff;">="{Url}"</span>
            <span style="color: #ff0000;">class</span>="{ <span style="color: #ff0000;">IsShared</span> ? <span style="color: #0000ff;">'bookmark shared'</span><span style="color: #ff0000;">:</span><span style="color: #0000ff;">'bookmark'</span> }"<span style="color: #0000ff;">&gt;</span>{Title}<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">a</span><span style="color: #0000ff;">&gt;</span><span style="color: #008000;">&lt;!--- if (!IsShared) { ---&gt;</span><span style="color: #0000ff;">&lt;</span><span style="color: #800000;">button</span><span style="color: #ff0000;">type</span><span style="color: #0000ff;">="button"</span><span style="color: #ff0000;">onclick</span><span style="color: #0000ff;">="..."</span><span style="color: #0000ff;">&gt;</span>Share<span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">button</span><span style="color: #0000ff;">&gt;</span><span style="color: #008000;">&lt;!--- } ---&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">li</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">ul</span><span style="color: #0000ff;">&gt;</span><span style="color: #0000ff;">&lt;/</span><span style="color: #800000;">n:AjaxRepeater</span><span style="color: #0000ff;">&gt;</span></pre>
        </p>
        <p>As we extend the functionality of those templates, it is important to preserve the server-side rendering capabilities. One way to accomplish this is to use the DLR and JavaScript on the server. This can actually be done quite efficiently by doing the script-generation and compilation using the DLR at page parse time, once for the lifetime of the application, in much the same way that regular ASP.NET template markup is parsed and compiled once into a delegate that can be invoked multiple times. For ongoing prototyping at this moment, I am starting to look at JScript.NET, until the DLR is part of the framework.</p>
        <p>One key realization here is that targeting the mainline scenarios that Ajax developers encounter all the time keeps the overall solution simple and elegant for both the developer and the framework. Combining that with the right server-side support makes the solution much more interesting, as it starts to address the end-to-end scenarios with a single set of concepts and a consistent approach.</p>
        <p>I'll reiterate that this is a prototype that I partly demo'd at MIX, and isn't meant to represent exactly what might eventually make it into the product (as we all know, things change as we iterate on ideas, and put together feature plans)... but as I mentioned earlier, if you do have thoughts you'd like to share, then go ahead, and post them below.</p>
        <p>For those who are interested at poking around in the code for either the templating engine (which is really quite small), or the server-side control, you can <a href="Content/Posts/AjaxTemplates/AjaxTemplates.zip">download the prototype</a> as it exists today. If you delve in deeper, you might also notice that the included script was generated using <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a> (as you might have come to expect of me by now) and comes along with the originating C# source as well. If you haven't installed Script#, then simply ignore the 2nd project in the solution when it prompts you. I am hoping to get a client-side templating engine added to Script# as well a little further down the road.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/ajax" rel="tag">ajax</a>  | <a href="http://www.nikhilk.net/tags/asp.net" rel="tag">asp.net</a>  | <a href="http://www.nikhilk.net/tags/prototype" rel="tag">prototype</a> ]</div>
      </body>
      <category>ASP.NET</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=191#Comments</comments>
      <description>This post describes a prototype for an Ajax templating solution, combined with an Ajax-friendly server-side solution that hints at what is coming down the road in ASP.NET Ajax.</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=191</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=191</link>
      <pubDate>Sun, 13 Apr 2008 05:44:49 GMT</pubDate>
      <title>Ajax Templates</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>I get the Silverlight vs. Ajax question all the time, whether it is at a conference, over email, or over on discussion forums. In the interest of seeding a broader discussion, and hearing what other people think, I thought this would be an interesting blog post, along with the side benefit of having a ready-made answer the next time the topic comes up.</p>
        <p>There have been a number of blog posts pitching Ajax vs. RIA (whether its Flash or Silverlight) such as this one <a href="http://www.tbray.org/ongoing/When/200x/2008/01/01/Predictions" target="_new">here</a>. Personally, I think Ajax and Silverlight complement each other, and the "vs." is a bit misplaced.  Furthermore, the way I see it, there is a continuum, with a number of sweet spots representing specific classes of applications. This perspective is perhaps directly reflected in the makeup of the UIFX team that I work on at Microsoft - the team is spread across ASP.NET, Ajax, Silverlight and RIA frameworks all at once actively working on cool stuff in each of these areas (i.e. lots to look forward to).</p>
        <p align="center">
          <br />
          <img src="Content/Posts/AjaxSilverlight/AppContinuum.png" alt="User-facing Application Spectrum" />
          <br />
        </p>
        <break />
        <p>
          <b>Reach and Rich</b>
          <br />The diagram represents a spectrum of application development approaches and technologies/platforms with increasing reach on one end, and increasing capabilities on the other. Applications have distinct scenarios and correspondingly gravitate toward a sweet spot. Some apps lie squarely on the left, with the need to first and foremost prioritize universal reach. At the same time,  some apps have experience or functionality as the high order bit, where it is necessary to leverage a more capable platform, even if it means somewhat reduced reach. Still, the best apps will probably be those that leverage multiple front-end options to follow the user, with a common back-end (sort of a <a href="http://www.microsoft.com/presspass/exec/ozzie/04-30-07MIX.mspx" target="_new">software <i>and</i> a service</a> model).</p>
        <p>One thing is sure - users are expecting more, and apps are trying to differentiate by meeting them. For example, the Ajax hype has given way to broad mainstream and pragmatic use of the technology (hence I call the older style of Web apps as "Classic" in the diagram).</p>
        <p>
          <b>RIA Islands</b>
          <br />At the same time, the reality is a number of applications are no longer "pure" Ajax, i.e. just HTML and Script-based. Ajax applications are increasingly relying on plugins such as Silverlight, Google Gears, and Flash to incrementally enrich the experience they can offer (ideally, in a manner such that they gracefully degrade). These plugins let Ajax applications do interesting things like use local storage, access user's files, integrate rich media and vector graphics, background processing etc. Just like ASP.NET server controls make it quite easy to incorporate Ajax functionality, they are also nicely positioned to simplify the "Islands of Silverlight" scenario. Imagine a data-bound server control that renders a Silverlight chart, and degrades to a static image dynamically rendered on the server without requiring the app developer to learn several new technologies. I've spoken on this at recent conferences, and will be blogging more on this end. Wilco blogged about <a href="http://www.wilcob.com/wilco/News/silverlight-interoperability.aspx" target="_new">Silverlight Interop</a> to cover the use of Silverlight to implement HTML code-behind and creating a better file uploader for Ajax apps.</p>
        <p>
          <b>Trends</b>
          <br />The second thing that is also interesting about the diagram are the trends in effect. The reach platform, starting to be referred to as the <a href="http://codinginparadise.org/weblog/2008/04/whats-open-web-and-why-is-it-important.html" target="_new">Open Web</a> by some, is bound to get richer in terms of the execution engine, the presentation stack, and its framework capabilities. HTML 5 promises to improve some core pieces of the browser-based platform, and all the browsers (yes, that includes <a href="http://blogs.msdn.com/ie/archive/2008/03/07/internet-explorer-8-beta-1-for-developers-standards-highlights.aspx" target="_new">IE</a>) are already stepping up to improving the state of the art in their next versions. The interesting question is when we will see ubiquity around the next batch of incremental improvements like the ubiquity of XMLHTTP that fueled the Ajax wave a couple or so years ago. RIA technologies are becoming more ubiquitous, and starting to become a viable or required choice for development in the next generation of Web apps. Over time as what is considered "rich" today gets commoditized by the reach platform, the platforms on the right need to constantly redefine themselves by finding new ways and value offerings in order to differentiate, which always keeps them interesting and in the forefront. It's a constant tug-of-war ... and it doesn't seem like either Ajax or the RIA approach is going to all out win any time soon.</p>
        <p>
          <b>A .NET Theme</b>
          <br />So if you agree, the world isn't Ajax vs. RIA, but is rather Ajax and RIA (and Desktop), and there is room for them to co-exist, the final thing I'll point out is how the Microsoft platform plays out in this space. Clearly, the consistent theme across the board is .NET and managed code, which allows developer skills, as well as in many cases, common code that can be shared and leveraged as apps transition or grow. Ray Ozzie spoke to this when referring to <a href="http://www.microsoft.com/Presspass/exec/ozzie/03-05-08MIX.mspx" target="_new">connected development</a> at MIX 08. We have .NET on the server providing that common backend, .NET on Web/Ajax front with ASP.NET and even . NET-flavored scripting with technologies like <a href="http://projects.nikhilk.net/ScriptSharp">Script#</a>, and of course, .NET on the client with WPF. Silverlight 2 brings .NET to the RIA space. In fact, the simple introduction of managed code into the browser is perhaps one of the most eagerly anticipated feature.</p>
        <p>The fun, and simultaneously challenging thing, is working on the multiple sweet spots along the current application platform spectrum, balancing the feature set, and making sure we have messaging for how they evolve, complement, and differentiate to address specific scenarios at the same time.</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/ajax" rel="tag">ajax</a>  | <a href="http://www.nikhilk.net/tags/silverlight" rel="tag">silverlight</a>  | <a href="http://www.nikhilk.net/tags/.net" rel="tag">.net</a>  | <a href="http://www.nikhilk.net/tags/thoughts" rel="tag">thoughts</a> ]</div>
      </body>
      <category>Silverlight</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=190#Comments</comments>
      <description>My thoughts on questions along the lines of Ajax vs. Silverlight, and independent of the debate, how .NET spans the gamut of application development platforms...</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=190</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=190</link>
      <pubDate>Tue, 08 Apr 2008 16:03:06 GMT</pubDate>
      <title>Ajax vs. Silverlight and .NET</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>While developing <a href="http://www.codeplex.com/FacebookNET" target="_blank">Facebook.NET</a>, it was on the back of my mind to create a script library equivalent in script# for client-side only interaction with the Facebook REST API using the existing JSONP interface to their REST service. I didn't do it yet for security reasons, as it would require sending down both the application key and secret to the client (something that existing Flash and Silverlight examples unfortunately and incorrectly show). Instead I opt'd for creating a Facebook Proxy service that allows your client code to talk to facebook via your service in an almost transparent manner. Those of you who have downloaded Facebook.NET can see a sample of this.</p>
        <p>Now Facebook is offering a client-side SDK. Wei Zhu blogged about the <a href="http://developers.facebook.com/news.php?blog=1&amp;story=73" target="_blank">JavaScript Client Library for the Facebook API</a> on the official developer blog last Friday. If you're a Facebook application developer, you'll want to check this out.</p>
        <p>Wei Zhu has been a long-time supporter of Script#, and it makes me super excited to see that the library itself was coded in <a href="http://projects.nikhilk.net/Projects/ScriptSharp.aspx">Script#</a>, and also uses the Script# runtime as part of its implementation. I am sure Script# usage resulted in some substantial productivity gains, and makes me hopeful that this will spike some more interest in the technology. Its also exciting to see the potential for a number of Facebook apps built on top of this. I am hopeful that Facebook will eventually release the .dll version of the script, so other downstream users of Script# will be able to directly reference these APIs in their C# code, without having to create a stub metadata dll</p>
        <p>I also chatted with Wei during the weekend about possible security implications. It looks like they've thought through the implications. Specifically, you only need to publish the API key (which is public anyway), and the client library connects with Facebook to generate a temporary user-session scoped secret using some new services, so you don't have to publish your actual secret. Nice!</p>
        <div class="Tags">
          <br />[ Tags: <a href="http://www.nikhilk.net/tags/script#" rel="tag">script#</a>  | <a href="http://www.nikhilk.net/tags/facebook" rel="tag">facebook</a> ]</div>
      </body>
      <category>Script#</category>
      <comments>http://www.nikhilk.net/Entry.aspx?id=189#Comments</comments>
      <description>Facebook's latest offering to application developers - a client-side script API, built on Script#!</description>
      <guid isPermaLink="true">http://www.nikhilk.net/Entry.aspx?id=189</guid>
      <link>http://www.nikhilk.net/Entry.aspx?id=189</link>
      <pubDate>Mon, 28 Jan 2008 16:28:35 GMT</pubDate>
      <title>Facebook Client Library built on Script#</title>
    </item>
    <item>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>A couple of days back I blogged about some first impressions while skimming through the HTML 5 spec, and I made a note about its length, which partly stems for a whole slew of new tags such as <a href="http://www.w3.org/TR/2008/WD-html5-20080122/#the-dialog" target="_blank">&lt;dialog&gt;</a>, &lt;figure&gt; etc.</p>
        <p>I can certainly see them being useful in creating a somewhat featured vocabulary for creating semantic markup. Here is the example from the draft spec:
<pre>
&lt;dialog&gt;
  &lt;dt&gt;Costello
  &lt;dd&gt;Look, you gotta first baseman?
  &lt;dt&gt;Abbott
  &lt;dd&gt;Certainly.