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

<channel>
	<title>Southworks Blogs &#187; Code</title>
	<atom:link href="http://blogs.southworks.net/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.southworks.net</link>
	<description>Powered by Southworks</description>
	<lastBuildDate>Tue, 14 May 2013 19:36:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Using JSON payloads to improve modern ASP.NET MVC applications</title>
		<link>http://blogs.southworks.net/geoff/2012/03/20/using-json-payloads-to-improve-modern-asp-net-mvc-applications/</link>
		<comments>http://blogs.southworks.net/geoff/2012/03/20/using-json-payloads-to-improve-modern-asp-net-mvc-applications/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 22:39:36 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://65.286</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2012/03/20/using-json-payloads-to-improve-modern-asp-net-mvc-applications/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<h2>Getting Started: An ASP.NET MVC site that lists customers</h2>
<p><em>Download all the code </em><a href="http://dl.dropbox.com/u/22279119/PayloadDemo.zip">here</a><em>.</em></p>
<p>This section is the vanilla MVC to set the stage for talking about AJAX and JSON payloads later on.  This should all be very familiar to ASP.NET MVC developers.</p>
<p>1. First, wel add a very simple customer model.</p>
<pre>public class Customer
{
    public string Name { get; set; }
}</pre>
<p>2. The we add a very simple home page model.</p>
<pre>public class HomePageModel
{
    public IEnumerable&lt;Customer&gt; Customers { get; set; }
}</pre>
<p>3. We write an Index action in the Home controller.</p>
<pre>public ActionResult Index()
{
    var model = new HomePageModel();
    model.Customers = LoadCustomers();
    return View(model);
}</pre>
<p>4. We write a LoadCustomers method to get the data. For demo purposes just returns a static list of customers sorted by name. This would likely be factored into a data access layer in a real application.</p>
<pre>private static Customer[] customers = new Customer[]
{
    new Customer() { Name = "John"},
    new Customer() { Name = "Bill"},
    …
};</pre>
<pre>private static IEnumerable&lt;Customer&gt; LoadCustomers()
{
    return customers.OrderBy(x =&gt; x.Name);
}</pre>
<p>5. We write a Index view in the Home folder to list the customers.</p>
<pre>@model PayloadDemo.Models.HomePageModel
@{
    ViewBag.Title = "Payload Demo";
}
&lt;h2&gt;
    @ViewBag.Title&lt;/h2&gt;
&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th style="text-align:left; margin:0"&gt;
                Name
            &lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
    @foreach (var item in Model.Customers)
    {
        &lt;tr&gt;
            &lt;td&gt;
                @Html.DisplayFor(modelItem =&gt; item.Name)
            &lt;/td&gt;
        &lt;/tr&gt;
    }
    &lt;/tbody&gt;
&lt;/table&gt;</pre>
<h2>PART 1: Traditional Pagination</h2>
<p>That customer list could get pretty long, so we next we will want to add pagination.  We can start by doing using traditional request/response to page through the data.</p>
<p>1. Wel update Index action in the Home controller to support pagination.  Notice that it sets the previous and next page numbers in the ViewBag.  Our view will use these later on.</p>
<pre>private const int pageSize = 5;
public ActionResult Index(int pageNumber)
{
    ViewBag.PreviousPageNumber = Math.Max(1, pageNumber + -1);
    ViewBag.NextPageNumber = pageNumber + 1;
    var model = new HomePageModel();
    model.Customers = LoadCustomers((pageNumber - 1) * pageSize, pageSize);
    if (pageNumber != 1 &amp;&amp; model.Customers.FirstOrDefault() == null)
    {
        ViewBag.NextPageNumber = -1;
    }
    return View(model);
}</pre>
<p>2. We update the LoadCustomers method to supports skip and top parameters.</p>
<pre>private static IEnumerable&lt;Customer&gt; LoadCustomers(int skip, int top)
{
    return customers.OrderBy(x =&gt; x.Name).Skip(skip).Take(top);
}</pre>
<p>3. We update the route entry in Global.asax.cs to support the pageNumber parameter.</p>
<pre>routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{pageNumber}", // URL with parameters
new { controller = "Home", action = "Index", pageNumber = 1 } // Parameter defaults
);</pre>
<p>4. We add a div with action links to the Home/Index view.  The action links  use the ViewBag properties to navigate to the previous or next page.</p>
<pre>&lt;div style="margin:5px"&gt;
    @Html.ActionLink("Previous", "Index", new { pageNumber = ViewBag.PreviousPageNumber })
    @if (ViewBag.NextPageNumber != -1)
    {
        @Html.ActionLink("Next", "Index", new { pageNumber = ViewBag.NextPageNumber })
    }
&lt;/div&gt;</pre>
<p>Now the user can page through data.  Notice the URL reflects the current page number.</p>
<p><a href="http://blogs.southworks.net/geoff/files/2012/03/Part1.png"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border: 0px" src="http://blogs.southworks.net/geoff/files/2012/03/Part1_thumb.png" border="0" alt="Part1" width="494" height="251" /></a></p>
<h2>Part 2: Pagination using AJAX and JSON</h2>
<p>The traditional MVC approach works, but the user is forced to refresh the entire page each time they navigate to the previous or next set of customers.  Modern web applications make an asynchronous AJAX request to populate the customer list with the paged data.</p>
<p>1. We keep the changes we made to the Index action, LoadCustomers method, and routing table to support pagination for requests to the server.</p>
<pre>public ActionResult Index(int pageNumber)</pre>
<p>2. Wel add a new method to support returning paged customer data as JSON. Here is the new GetCustomers action method in the Home controller.</p>
<pre>[HttpPost]
public JsonResult GetCustomers(int pageNumber)
{
    return Json(LoadCustomers((pageNumber - 1) * pageSize, pageSize));
}</pre>
<p>2. We replace the links in the Home/Index view with buttons.</p>
<pre>&lt;div style="margin:5px"&gt;
    &lt;button id="previous-page" style="width: 80px; height: 25px; display: inline;" &gt;Previous&lt;/button&gt;
    &lt;button id="next-page" style="width: 80px; height: 25px; display: inline;" &gt;Next&lt;/button&gt;
&lt;/div&gt;</pre>
<p>3. We also add a data attribute and and ID to the Home/Index view.  This will help us call back using AJAX.</p>
<pre>&lt;table id="customers" data-url="@Url.Action("GetCustomers", "Home")"&gt;</pre>
<p>4. We add a new JavaScript file called payload-demo.js to the project.</p>
<p>Here is the payload-demo.js code.  This code tracks the current page number.  When the user clicks one of the buttons, we make an AJAX request and then repopulate the customer list with the data.</p>
<pre>$(function () {
    var currentPageNumber = 1;

    var populateCustomers = function(data) {
        var $customerList = $('#customers tbody');
        $customerList.children().detach();
        $.each(data, function (i, customer) {
            $('&lt;td&gt;&lt;/td&gt;').text(customer.Name)
            .appendTo($('&lt;tr&gt;&lt;/tr&gt;'))
            .parent()
            .appendTo($customerList);
        });
    };

   $("#next-page").click(function (event) {
        currentPageNumber += 1;
        var $customers = $('#customers');
        var url = $customers.data('url');
        url = url + '/' + currentPageNumber.toString();
        $.ajax({
            url: url,
            context: document.body,
            type: 'POST',
            success: function (data) {
                if ($(data).length == 0)
                {
                    currentPageNumber -= 1;
                    return;
                }
                populateCustomers(data);
            }
        });
    });

    $("#previous-page").click(function (event) {
        if (currentPageNumber == 1)
        {
            return;
        }

        currentPageNumber -= 1;
        var $customers = $('#customers');
        var url = $customers.data('url');
        url = url + '/' + currentPageNumber.toString();
        $.ajax({
            url: url,
            context: document.body,
            type: 'POST',
            success: function (data) {
                populateCustomers(data);
            }
        });
    });
});</pre>
<p>5. We add a reference to payload-demo.js to _Layout.cshtml so that each page gets the script.</p>
<pre>&lt;script src="@Url.Content("~/Scripts/payload-demo.js")" type="text/javascript"&gt;&lt;/script&gt;</pre>
<p>Now the user can navigate paged customer data without leaving the page. Notice that we’re on page 2, but the URL hasn’t changed.</p>
<p><a href="http://blogs.southworks.net/geoff/files/2012/03/Part2.png"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border: 0px" src="http://blogs.southworks.net/geoff/files/2012/03/Part2_thumb.png" border="0" alt="Part2" width="571" height="283" /></a></p>
<h2>Part 3: Pagination with AJAX and a JSON payload</h2>
<p>At this point, we’ve done the same work twice.</p>
<blockquote><p>To produce the initial page, we created a model for the home page, an action that loaded the data into the model and invoked the view, and the Razor syntax in the view to produce the table with rows and columns.</p>
</blockquote>
<blockquote><p>To update the page, we created a JSON model, an action to return the JSON, and jQuery code to update the table with new rows and columns.</p>
</blockquote>
<p><span>We could decide to do everything with AJAX and JSON and get rid of the initial page code.  We could leave the customer table empty on the initial page response, and as soon as the page loads make a request for the first page of customer data. </span></p>
<p><span>This works OK, but there can be a delay as the request is made.  The customer may see an empty customer list for a moment.  You could add a wait indicator, but this further delays getting data in front of the user and makes the application feel less responsive. </span></p>
<p><span style="font-style: italic">Note: I never liked those pages where it loads and then a hundred wait spinners go nuts as I wait and wait for the data to show up. </span><span style="font-style: italic">I forgive the spinners on Mint.com because they are asynchronously connecting to my bank accounts and they provide the most recent data immediately.</span></p>
<p><em> </em></p>
<p><strong>You don’t have to make that extra web request! </strong>In this section, I&#8217;ll show you how to send down initial JSON data with the page as a payload and let the same script that populates the table with the results of the AJAX request, immediately populate the customer list.</p>
<p>1. We update our Index action in the Home controller to put the JSON data into the ViewBag.  This uses the JavaScriptSerializer to turn the JsonResult from GetCustomers into a string.  Warning: Be sure to remember the .Data or it won’t serialize the right data.</p>
<pre>public ActionResult Index(int pageNumber)
{
    ViewBag.CustomersPayload = new JavaScriptSerializer().Serialize(GetCustomers(pageNumber).Data);
    return View();
}</pre>
<p>2. We can delete the HomePageModel and simplify our Home/Index view.  Notice the table is empty. We add a hidden div with a data attribute to the end of the page.  We put it at the end of the page so that the browser can doesn&#8217;t have to parse it as it is working to render the visible elements and so that we can delete it after we&#8217;ve used the data.</p>
<pre>@{
  ViewBag.Title = "Payload Demo";
}
&lt;h2&gt;@ViewBag.Title&lt;/h2&gt;
&lt;table id="customers" data-url="@Url.Action("GetCustomers", "Home")"&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style="text-align:left; margin:0"&gt;Name&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
&lt;div style="margin:5px"&gt;
  &lt;button id="previous-page" style="width: 80px; height: 25px; display: inline;" &gt;Prev&lt;/button&gt;
  &lt;button id="next-page" style="width: 80px; height: 25px; display: inline;" &gt;Next&lt;/button&gt;
&lt;/div&gt;
&lt;div id="payload" style="display:none" data-customers="@ViewBag.CustomersPayload"&gt;</pre>
<p>3. We update our payload-demo.js script to use the payload.  We delete the div once we have used it to ensure we won&#8217;t apply stale data later when the user clicks a navigation button.</p>
<pre>var $payload = $('#payload');
    if ($payload != null) {
        populateCustomers($payload.data('customers'));
        $payload.detach();
}</pre>
<p>Now we get the initial page populated and only have a single code path to write, debug, and maintain.</p>
<p><a href="http://blogs.southworks.net/geoff/files/2012/03/Part3.png"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border: 0px" src="http://blogs.southworks.net/geoff/files/2012/03/Part3_thumb.png" border="0" alt="Part3" width="512" height="300" /></a></p>
<h2>Wrap-Up</h2>
<p>If you inspect the client/server traffic in Fiddler or IE F12, you will see that the DNS resolution, proxy routing and connection negotiation are more expensive than the a few extra Kb of downloaded data.  This is even more true if your users are in other countries or on lower bandwidth connections.</p>
<p>By including JSON payloads in your page, you can get the best of both worlds: Dynamic applications built using jQuery and AJAX and and immediate display of data with fewer asynchronous requests.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flyweight M-V-VM: Decorator revision</title>
		<link>http://blogs.southworks.net/geoff/2011/10/19/mvvm-decorator/</link>
		<comments>http://blogs.southworks.net/geoff/2011/10/19/mvvm-decorator/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 12:54:28 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Decorator]]></category>
		<category><![CDATA[Flyweight]]></category>
		<category><![CDATA[M-V-VM]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.244</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/10/19/mvvm-decorator/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<h2>Revision: Behavior problems</h2>
<p>In my original post I provided a behavior (ViewModelBehavior) for provding a view model for the given DataContext.  The behavior saved away the original DataContext as the model, set DataContext of the AssociatedObject to the view model,  and passed the model to the view model.</p>
<p>This worked in 90% of the basic data binding scenarios.  However, it fails to work properly when the DataContext contains a relative data binding expression.  The root source of the problem is that the behavior is a child of the AssociatedObject (from a data binding perspective).</p>
<p><span style="font-weight: normal">Changing the DataContext causes problems when the original DataContext binding expression is relative.  When the behavior saves the original DataContext to a dependency property it owns, two things break:</span></p>
<p><span style="font-weight: normal">First, the relative position of the DataContext on the behavior is one level deeper than the DataContext at the AssociatedObject level.  This means any relative binding will be starting from the wrong point in the tree and won&#8217;t get the right value.</span></p>
<p><span style="font-weight: normal">Second, when the AssociateObject&#8217;s DataContext is set to the view model, this affects the binding evaluation from the original DataContext.  This corrupts the saved DataContext value and the view model never gets the model.</span></p>
<h3>Attempt: Attached property</h3>
<p>To solve the first problem, I attempted to use an attached property on the AssociatedObject to make a copy of the DataContext.  This would mean the data binding statement of the copy would start at the same point as the original DataContext.</p>
<p>I had to write some ugly code to clone the binding and to set the initial value of the attached property to force an attachment at run-time.  Unfortunately, the attached property was still affected by the change to the DataContext.  This is because WPF follows the ordering of attributes.  I attempted to clear the DataContext, set the original DataContext, and then re-apply the DataContext. This didn&#8217;t work either as WPF has some special affinity for the DataContext property and always gives it priority.</p>
<h3>Attempt: Cloned Binding</h3>
<p>To try and solve the second problem, I did a whole bunch of ugly code for making a smart clone of the data binding.  However, the inherited nature of the DataContext made this approach unworkable. The copy couldn&#8217;t participate in the same inheritance chain as the DataContext property.</p>
<h2>Analogy: Variable swap</h2>
<p>After the failed attempts to solve the problem, I realized it was like  trying to swap two variables without having a temp variable.  A good interview question, but not a great WPF behavior.  By adding another control (like a Grid, Border, etc), I could add another level and separate the DataContext binding expression away from the AssociatedObject control.  This provides the temp variable for making the swap.</p>
<p>I considered not allowing (or restricting) the DataBinding expression on the AssociatedObject.  This isn&#8217;t a good choice though because it would interfere with other behaviors, prevent normal XAML development, and favors a run-time exception for a design-time error.</p>
<h2>Solution: Decorator</h2>
<p>Given that I need to ensure a level in the XAML where the DataContext could be changed, I decided to use a Decorator as a base class rather than a behavior.  The decorator could have it&#8217;s DataContext set and could modify the DataContext of its only child.  I thought this would make more sense to the developer than the behavior; everything within the decorator would have the view model as the DataContext.</p>
<p>The improved simplicity of understanding the data binding scope comes as the cost that the developer has to add a new XAML element.  This sacrifices on of my goals for  M-V-VM: &#8220;The library does not require to change how you build your XAML hierarchy&#8221;.  I thought a lot about these tradeoffs and after using it for a bit, the decorator approach seems worth it.</p>
<p>The ViewModelScope class inherits from Decorator.  It has the same ViewModelType and static ViewModelFactory properties as the behavior.  To use it, you just add it to your XAML like you would a Border:</p>
<pre>&lt;bellacode:ViewModelScope ViewModelType="{x:Type local:MyViewModel}" &gt;
    ...
&lt;/bellacode:ViewModelScope&gt;</pre>
<p>Because ViewModelScope is a Decorator which derives from FrameworkElement, you can set the DataContext just like any other FrameworkElement.</p>
<p>I&#8217;ve included the updated Flyweight M-V-VM library <a href="http://www.bellacode.com/code/mvvm/BellaCode.Mvvm2.zip">here</a>.  The HelloWorld sample application is updated and it includes the POCO library from commands from my previous post.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flyweight M-V-VM: POCO commands</title>
		<link>http://blogs.southworks.net/geoff/2011/10/12/mvvm-commands/</link>
		<comments>http://blogs.southworks.net/geoff/2011/10/12/mvvm-commands/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 15:33:02 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Behavior]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[Flyweight]]></category>
		<category><![CDATA[ICommand]]></category>
		<category><![CDATA[M-V-VM]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.199</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/10/12/mvvm-commands/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<h2><span style="font-weight: normal">M-V-VM encourages POCO view models</span></h2>
<p>M-V-VM is one of the design patterns that help separate concerns between presentation and data:</p>
<ul>
<li>The model is concerned with data and knows nothing of the view or view model.</li>
<li>The  view is concerned with presentation.  It only knows about the view model or model through data binding.</li>
<li>The view model is concerned with data although it is designed to provide functionality for the view.  The view model knows about the model, but not about the view.</li>
</ul>
<p>By keeping the view model unaware of the view, M-V-VM distinguishes itself from patterns like Model-View-Presenter (M-V-P) which allows the presenter to have knowledge of  the view.</p>
<p>Because the view model does not know about or rely on the view, it encourages the view model to be built as a Plain Old CLR object (POCO) class just like the model.  Many consider the view model an example of the adapter pattern as  it wraps the model to make it consumable by the view.</p>
<h2><span style="font-weight: normal">POCO view models are deceptively challenging</span></h2>
<p>How hard could it be to write a POCO view model?  It is just a regular class right?</p>
<p>Writing a view model that isn&#8217;t polluted by view concerns is harder than it first appears.  This is due to how the WPF/Silverlight data binds to the view model.</p>
<p>WPF/Silverlight data binding was designed to bind to dependency properties, not to call methods, or respond to events. To handle calling methods, WPF/Silverlight use the ICommand interface.  By encapsulating a method call in an object, WPF can data bind to it. Event and data triggers allow the view to respond to changes in the view model.</p>
<p>So lots of view model authors choose to expose ICommand, RoutedCommand, or RoutedUICommand properties.  Several WPF/SL libraries provide a class that can relay or delegate the CanExecute and Execute implementation from the command to methods in  the view model.  This way, view model authors write some extra ICommand properties, wire-up the delegation class, and then write methods to implement the commands.</p>
<p>This works, but  doesn&#8217;t get the full power WPF/SL offers with commanding.  Custom controls (like TextBox) register themselves for commands directly with the CommandManager.  This leverages the structure of the XAML tree, to let the control intercept commands as they bubble up.  Controls like Button and MenuItem that support a Command property can bind to x:Static commands or use the built in ApplicationCommands, ComponentCommands, and MediaCommands.  The standard commands can also be easily associated with input gestures (i.e. keyboard shortcuts) in XAML.</p>
<h2><span style="font-weight: normal">BindCommandBehavior</span></h2>
<p>I&#8217;ve never liked exposing ICommand properties from my view models.  It feels like the first step to knowing too much about the view.  I also don&#8217;t like adding command delegation classes to my view model; it seemed like a lot of extra work.</p>
<p>I  decided that a behavior could do a better job of delegating commands while still getting the full power of WPF/SL commanding.  You can download it <a href="www.bellacode.com/code/mvvm/bellacode.mvvm.poco.zip">here</a>.</p>
<p>The download is the Flyweight M-V-VM solution from my previous post with the addition of the Poco library and the HelloPocoWorld sample application.  Check out the readme.txt in the sample app.</p>
<h2><span style="font-weight: normal">How to use it</span></h2>
<p>Attach the BindCommandBehavior to any control in your XAML.  The control&#8217;s data context should point at class that implements the method you want to call when the command is executed.  Just like any other behavior, you can drag-and-drop the BindCommandBehavior on a control when using Expression Blend.</p>
<p>Once you do that, just set the CommandProperty just like you would on a Button control.</p>
<p>Here is a snippet from the HelloPocoWorld sample application.</p>
<pre>    &lt;Window.Resources&gt;
        &lt;local:Stopwatch x:Key="theStopwatch" /&gt;        
    &lt;/Window.Resources&gt;
    &lt;Grid DataContext="{Binding Source={StaticResource theStopwatch}}"&gt;
        &lt;i:Interaction.Behaviors&gt;
            &lt;bellacode:BindCommandBehavior Command="{x:Static local:StopwatchCommands.Start}" /&gt;
            ...</pre>
<div>
<ul>
<li>The Stopwatch implements the Start method.</li>
<li>The Grid has the Stopwatch instance as its DataContext and has the BindCommandBehavior attached.</li>
<li>The Start command is a RoutedCommand static property defined in the StopwatchCommand static class.</li>
</ul>
</div>
<p>That&#8217;s it!  By using the BindCommandBehavior, your view models don&#8217;t need to know anything about ICommand. You just write plain old methods in your view model.</p>
<h2><span style="font-weight: normal">How it works</span></h2>
<p>Just like a button uses the Command property to determine the command to execute when the button is clicked, the BindCommandBehavior button uses the Command property to determine the command to handle.  When the command is executed, the behavior delegates by calling a method on the data context.</p>
<p>You can also write a property or method that determines if the command can execute.  If no &#8220;CanExecute&#8221; property or method is found, the behavior allows the command to execute.  When your class fires an INotifyPropertyChanged.PropertyChanged event for any of your CanExecute properties, the CommandManager.InvalidateRequerySuggested is called for you.</p>
<p>If the properties or methods in your view model are named differently than your command, you can set the ExecuteMethodName and either the CanExecutePropertyName or CanExecuteMethodName attributes on the behavior.  By default, the behavior follows a convention that uses the command name to look for the appropriate properties and methods.</p>
<p>The BindCommandBehavior will try to pass the CommandParameter to your method if possible.  Because the CommandParameter arrives as an object, the behavior will  determine the parameter type of your method and try to convert the object to that type.  If it can&#8217;t convert it, it just passes the object and hopes for the best.</p>
<p>There are a couple of limitations on your view model imposed by the behavior (for now):</p>
<ul>
<li>You can&#8217;t have overloads of the method.  The behavior isn&#8217;t sure which one to call.</li>
<li>Your execute and can execute methods can&#8217;t take more than one parameter.</li>
</ul>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flyweight M-V-VM</title>
		<link>http://blogs.southworks.net/geoff/2011/09/28/mvvm/</link>
		<comments>http://blogs.southworks.net/geoff/2011/09/28/mvvm/#comments</comments>
		<pubDate>Wed, 28 Sep 2011 20:31:21 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Behavior]]></category>
		<category><![CDATA[Flyweight]]></category>
		<category><![CDATA[M-V-VM]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.117</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/09/28/mvvm/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<h2>A better M-V-VM library</h2>
<p>There are several existing libraries that support the Model-View-ViewModel (M-V-VM) pattern. They each have some nice features. However, I didn&#8217;t find any that were just M-V-VM. Some required me to fundamentally restructure my XAML. Others required me to use dependency injection or implement a view model locator pattern. A few required me to use a heavy base class full of complex helpers or depend on a whole set of additional infrastructure. While I appreciate the help writing Plain Old CLR Objects (POCO) view models, I kept wishing there was a library requiring less buy-in to all those &#8220;extras&#8221;.</p>
<p>So I started building a library that just does M-V-VM. I ended up with something that is easy to use, lightweight, and powerful.</p>
<p><span style="color: #ff0000">I&#8217;ve revised the approach from using a Behavior to using a Decorator.  You can download the updated version and read about it at <a href="http://blogs.southworks.net/geoff/2011/10/19/mvvm-decorator/">http://blogs.southworks.net/geoff/2011/10/19/mvvm-decorator/</a>.</span></p>
<p>You can download it <a href="http://www.bellacode.com/code/mvvm/bellacode.mvvm.zip">here</a>. It contains the library project and a HelloWorld sample application. Both have complete ReadMe.txt files.</p>
<h2>Tenants</h2>
<h3>M-V-VM only</h3>
<p style="padding-left: 30px">The library has no dependencies outside WPF/.NET. All the classes are related strictly to M-V-VM.</p>
<h3>Normal XAML development</h3>
<p style="padding-left: 30px">The library does not require to change how you build your XAML hierarchy.</p>
<h3>No POCO glue</h3>
<p style="padding-left: 30px">The library does not provide commanding or property changed helpers or patterns. Another library might, but not this one.</p>
<h3>No additional patterns required</h3>
<p style="padding-left: 30px">The library can support dependency injection and view model locator, but nothing is required on behalf of the developer.</p>
<h2>How to use it</h2>
<p>These are the two classes you&#8217;ll use 99% of the time.</p>
<h3>ViewModel&lt;TModel&gt;</h3>
<p style="padding-left: 30px">This is a base class for your view model classes.</p>
<h3>ViewModelBehavior</h3>
<p style="padding-left: 30px">This is a behavior that you can drag and drop onto your controls (in Expression Blend). Just set the ViewModelType property to the type of your view model.</p>
<p>You can review the <a href="http://www.bellacode.com/code/mvvm/readme.txt">readme</a> to learn about the other classes.</p>
<h2>How it works</h2>
<div>When the behavior attaches to the control:</div>
<div>
<ol>
<li>It instantiates a view model using the ViewModelType property.</li>
<li>It sets the view model&#8217;s Model property = DataContext</li>
<li>It sets the view model&#8217;s View property = control</li>
<li>It sets the control&#8217;s DataContext = view model</li>
</ol>
</div>
<p><strong>Example 1: Basic ViewModel</strong></p>
<p>This example shows the most basic creation of a view model.</p>
<p>In this example and the following examples the is a Customer is the model. The Customer class has basic properties like FirstName and LastName. The view model provides additional properties like FullName.</p>
<pre>&lt;Grid DataContext="{Binding Customer}"&gt;
  &lt;i:Interaction.Behaviors&gt;
<strong>    &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:CustomerViewModel}"/&gt;</strong>
  &lt;/i:Interaction.Behaviors&gt;
  &lt;TextBlock Text="{Binding FullName}" /&gt;
&lt;/Grid&gt;</pre>
<p><em>Yes the example is contrived as you could easily do this with a ValueConverter. Some consider the M-V-VM pattern eliminates the need for ValueConverters and ValidationRules. Others find those classes continue to be helpful and are better encapsulated for re-use.</em></p>
<h2>Example 2: Bind to ViewModel and Model</h2>
<p>This example shows the you can also bind directly against the model.</p>
<p><em>It is up to you if your view model follows a strict Facade pattern when wrapping your model. There are some nice benefits to the Facade pattern because then your data-binding statements don&#8217;t have any knowledge that there is a view model containing a model. However, if your model already implements INotifyPropertyChanged, it can often be a massive time saver to bind directly to the model.</em></p>
<pre>
<div>&lt;Grid DataContext="{Binding Customer}"&gt;
  &lt;i:Interaction.Behaviors&gt;
    &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:CustomerAccountViewModel}"/&gt;
  &lt;/i:Interaction.Behaviors&gt;
  &lt;StackPanel&gt;
<strong>    &lt;TextBlock Text="{Binding Model.CreditCard.AccountHolderName}" /&gt;
    &lt;TextBlock Text="{Binding AccountStatus}" /&gt;
</strong>  &lt;/StackPanel&gt;
&lt;/Grid&gt;</div>
</pre>
<h2>Example 3: Hierarchy of ViewModels</h2>
<p>This example shows how to create view models at different levels for a hierarchy of views.</p>
<p><em>Any part of the view model &#8211; the model, part of the model, or a property &#8211; can be passed as the data context for a nested control. The behavior can then use that data context as a model for the nested control&#8217;s view model. View models naturally follow the same hierarchy as your views. The behavior is easy to use because it leverages the natural XAML hierarchy.</em></p>
<pre>&lt;Grid&gt;
  &lt;i:Interaction.Behaviors&gt;
    &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:CustomerViewModel}"/&gt;
  &lt;/i:Interaction.Behaviors&gt;
  &lt;Grid.ColumnDefinitions&gt;
    &lt;ColumnDefinition Width="Auto" /&gt;
    &lt;ColumnDefinition /&gt;
  &lt;/Grid.ColumnDefinitions&gt;
  &lt;Grid.RowDefinitions&gt;
    &lt;RowDefinition Height="Auto" /&gt;
    &lt;RowDefinition Height="Auto" /&gt;
    &lt;RowDefinition Height="Auto" /&gt;
  &lt;/Grid.RowDefinitions&gt;
  &lt;Label Content="Name" /&gt;
  &lt;TextBlock Text="{Binding FullNameWithSalutation}" Grid.Column="1" /&gt;
  &lt;Label Content="Shipping Address" Grid.Row="1"/&gt;
  <strong>&lt;Grid DataContext="{Binding Model.ShippingAddress}" Grid.Row="1" Grid.Column="1"&gt;</strong>
    &lt;i:Interaction.Behaviors&gt;
<strong>      &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:AddressViewModel}"/&gt;</strong>
    &lt;/i:Interaction.Behaviors&gt;
    &lt;TextBlock Text="{Binding FullAddress}" /&gt;
  &lt;/Grid&gt;
  &lt;Label Content="Billing Address" Grid.Row="2"/&gt;
<strong>  &lt;Grid DataContext="{Binding Model.BillingAddress}" Grid.Row="2" Grid.Column="1"&gt;</strong>
    &lt;i:Interaction.Behaviors&gt;
<strong>      &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:AddressViewModel}"/&gt;</strong>
    &lt;/i:Interaction.Behaviors&gt;
    &lt;TextBlock Text="{Binding FullAddress}" /&gt;
  &lt;/Grid&gt;
  &lt;Label Content="Account Status" Grid.Row="3"/&gt;
<strong>  &lt;Grid DataContext="{Binding Model}" Grid.Row="2" Grid.Column="3"&gt;</strong>
    &lt;i:Interaction.Behaviors&gt;
<strong>      &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:CustomerAccountViewModel}"/&gt;</strong>
    &lt;/i:Interaction.Behaviors&gt;
    &lt;TextBlock Text="{Binding FullAddress}" /&gt;
  &lt;/Grid&gt;
&lt;/Grid&gt;</pre>
<h2>Example 4: Lists and Data Templates</h2>
<p>This example shows how a data template can easily create a view model for each item when used in a list control.</p>
<p><em>Your view models should not generally expose other view models as properties. This would mean that one view model is responsible for creating instances of other view models. You would lose the loose coupling the view model behavior provides and the flexible type-agnostic nature of data binding.</em></p>
<pre>
<div>&lt;Grid&gt;
<strong>  &lt;ListBox ItemsSource="{Binding Customers}"&gt;</strong>
    &lt;ListBox.ItemTemplate&gt;
<strong>      &lt;DataTemplate&gt;</strong>
        &lt;Grid&gt;
          &lt;i:Interaction.Behaviors&gt;
<strong>            &lt;bellacode:ViewModelBehavior ViewModelType="{x:Type local:CustomerViewModel}"/&gt;</strong>
          &lt;/i:Interaction.Behaviors&gt;
          &lt;Grid.ColumnDefinitions&gt;
            &lt;ColumnDefinition /&gt;
            &lt;ColumnDefinition /&gt;
          &lt;/Grid.ColumnDefinitions&gt;
          &lt;TextBlock Text="{Binding Customer.Name}" /&gt;
          &lt;TextBlock Text="{Binding MostRecentPurchaseDate}" Grid.Column="1" /&gt;
        &lt;/Grid&gt;
      &lt;/DataTemplate&gt;
    &lt;/ListBox.ItemTemplate&gt;
  &lt;/ListBox&gt;
&lt;/Grid&gt;</div>
</pre>
<h2>Up Next: POCO</h2>
<p>Plain Old CLR Objects (POCO) view models feel much less UI-bound than those that expose RoutedCommand, ICommand, RoutedEvents, or ICollectionView. I&#8217;m in progress working on a behavior that make command-binding for a control just as easy as the view model. It will be a separate library so you can choose to use if it works for you.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modularity with Prism (Boise 2011)</title>
		<link>http://blogs.southworks.net/geoff/2011/06/29/modularity-with-prism/</link>
		<comments>http://blogs.southworks.net/geoff/2011/06/29/modularity-with-prism/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 20:25:52 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Boise]]></category>
		<category><![CDATA[Modularity]]></category>
		<category><![CDATA[ModuleCatalog]]></category>
		<category><![CDATA[ModuleManager]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.93</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/06/29/modularity-with-prism/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>As part of the talk I gave on Modularity with Prism today, I created a very small modular application.</p>
<h2>The Simplest Modular Application</h2>
<p>This WPF application allow you to type different commands into a text box and see the result in a textbox below.  The app has just has 1 module &#8211; the MathModule &#8211; which provides add (+), subtract (-), multiply (*), and divide (/) in RPN style notation.</p>
<p>The application went through several stages:</p>
<ol>
<li>Non-Modular application that just defines the ICommand interface and command processing classes.</li>
<li>A non-modular application that uses the most basic Prism bootstrapper possible.</li>
<li>A modular application that uses the standard ModuleCatalog and add the MathModule by direct assembly type reference.</li>
</ol>
<p>I then walked through both the Modularity Quickstart (Desktop and Silverlight) to show UnityBootstrapper.Run() method diving down into the ModuleManager, ModuleCatalog, ModuleInitializer, and ModuleTypeLoaders (configuration, directory, and XAP).</p>
<p>You can download the Cmdlet program <a href="http://www.bellacode.com/code/ModularityExamples.zip">here</a>.</p>
<p>During the demo, I had put project references to Prism.Desktop and Prism.Desktop.UnityExtensions.  However, to make this download more consumable, I reverted to assembly references.</p>
<p>If you unzip so that the Examples folder it a sibling to Prism, you shouldn&#8217;t need to update any assembly references.</p>
<h2>Takeways</h2>
<ul>
<li><strong>There isn&#8217;t any magic to Prism&#8217;s Modularity.</strong> While some aspects of loading assemblies into the application domain during directory sweep or XAP download are sophisticated, you can debug through the entire module discovery, loading, and initialization process.</li>
</ul>
<ul>
<li><strong>Prism provides rich module management &#8211; don&#8217;t roll your own.</strong> At first glance, it seems easy enough to discover and load assemblies.  However, the ModuleManager provides a state machine for modules loading, cyclic graph and duplicate detection of dependencies, and support for events for both synchronous and asynchronous loading.</li>
</ul>
<ul>
<li><strong>Modules are logical divisions</strong>.  You don&#8217;t have to partition your application only on assembly boundaries,  you can register a group of assemblies in a single module.  Partition your application into modules based on expected logical usages of the application.</li>
</ul>
<h2>A couple of things I forgot to mention</h2>
<ul>
<li>For Silverlight developers, you can leverage the asynchronous download and progress modules in XAPs to keep your start-up time very short and on-demand load features as they are needed.  This can make a big difference for applications where some expensive features are used rarely.</li>
</ul>
<ul>
<li>You can group ModuleInfo in configuration/XAML catalogs into groups and then specify dependencies between groups.  This can make configuring dependencies simpler.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing and MOQ (Boise 2011)</title>
		<link>http://blogs.southworks.net/geoff/2011/06/29/unit-testing-and-moq/</link>
		<comments>http://blogs.southworks.net/geoff/2011/06/29/unit-testing-and-moq/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 16:04:47 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Boise]]></category>
		<category><![CDATA[Dispatcher]]></category>
		<category><![CDATA[MOQ]]></category>
		<category><![CDATA[MSTest]]></category>
		<category><![CDATA[Prism]]></category>
		<category><![CDATA[Sample]]></category>
		<category><![CDATA[SFChallenge]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.77</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/06/29/unit-testing-and-moq/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>Yesterday I got the opportunity to talk about Unit Testing and MOQ at a WPF/Prism <a href="http://karlshifflett.wordpress.com/2011/05/12/registration-open-for-prism-unity-wpf-mvvm-boise-training-event/">conference in Boise</a> put on by <a href="http://karlshifflett.wordpress.com/">Karl Shifflett</a> (Microsoft).  I had a great time and appreciate how the attendees were so engaged in the talk even at the end of day.</p>
<h2>Unit Testing Scenarios</h2>
<p>I covered the following unit testing scenarios:</p>
<ul>
<li>Concrete classes using MSTest (built into Visual Studio Pro and higher)</li>
<li>Classes that use XML (like XML serializers)</li>
<li>Entity Framework &amp; SQL Server Compact</li>
<li>Repositories (by being able to abstract Entity Framework)</li>
<li>Basic usage of <a href="http://code.google.com/p/moq/wiki/QuickStart">Moq</a></li>
<li>Advanced usage of Moq</li>
<li>Classes that are concurrent and use Dispatcher</li>
</ul>
<h2>About the Sample</h2>
<p>The SFChallenge sample is a dice-roll fighting simulator between the Hall of Justice and the Legion of Doom.  It uses Entity Framework with SQL Server Compact to load each super person and their characteristics.  On top of Entity Framework is a simple repository pattern.  The fights run asynchronously and follow the Async Events Pattern using the WPF Dispatcher.</p>
<p>The Model, Data, and Core components have 100% unit test coverage.  Note: This sample does not unit test the user interface layer, but you should unit test your view models when applying the M-V-VM pattern.</p>
<p>You can download the completed project <a href="http://www.bellacode.com/code/sfchallenge.zip">here</a>.</p>
<p>The sample also includes TestDataLoader and AssertXml classes that can be freely re-used for unit testing.  Note, the DispatcherAssist was borrowed from the WPF Application Framework for example purposes and licensing terms are <a href="http://waf.codeplex.com/">here</a>.</p>
<h2>How to build the sample</h2>
<p><span style="color: #ff0000">Please read! </span></p>
<p>This sample does not ship with Entity Framework, Moq, or SQL Server Compact.  You will need to add packages to several projects (listed below).  To do this click the &#8216;View&#8217; menu, &#8216;Other Windows&#8217; sub-menu, and &#8216;Package Manager Console&#8217;.  Many packages must be installed using the console.  Type the following into the console and ensure each is successful.</p>
<p>If you haven&#8217;t used the Package Manager Console, you can find help <a href="http://docs.nuget.org/docs/start-here/using-the-package-manager-console">here</a>.</p>
<p><strong>Entity Framework Package</strong></p>
<pre>install-package EntityFramework -ProjectName SFChallenge.Storage
install-package EntityFramework -ProjectName SFChallenge.Controls
install-package EntityFramework -ProjectName SFChallenge
install-package EntityFramework -ProjectName SFChallenge.Storage.UnitTests</pre>
<p><strong>SQL Server Compact Package</strong></p>
<pre>install-package EntityFramework.SqlServerCompact -ProjectName SFChallenge.Storage
install-package EntityFramework.SqlServerCompact -ProjectName SFChallenge
install-package EntityFramework.SqlServerCompact -ProjectName SFChallenge.Storage.UnitTests</pre>
<p><strong>MOQ Package</strong></p>
<pre>install-package Moq -ProjectName SFChallenge.Core.UnitTests
install-package Moq -ProjectName SFChallenge.Data.UnitTests</pre>
<h2>Unit Testing and Design</h2>
<p>Unit Testing is:</p>
<ul>
<li>A muse for thoughtful design</li>
<li>A watchdog of deficient design</li>
<li>An expression of craftsmanship</li>
<li>A touchstone during change</li>
<li>An accepted measure of quality</li>
</ul>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WPF Behavior: Global Application Shortcut Keys</title>
		<link>http://blogs.southworks.net/geoff/2011/03/15/wpfshortcutkeys/</link>
		<comments>http://blogs.southworks.net/geoff/2011/03/15/wpfshortcutkeys/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 00:35:39 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Behaviors]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CommandManager]]></category>
		<category><![CDATA[Global]]></category>
		<category><![CDATA[InputBinding]]></category>
		<category><![CDATA[Keyboard]]></category>
		<category><![CDATA[RegisterAppShortcutKeysBehavior]]></category>
		<category><![CDATA[Shortcut]]></category>
		<category><![CDATA[Windows Presentation Foundaton]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://65.52</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2011/03/15/wpfshortcutkeys/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<h2><strong>WPF Support</strong></h2>
<p>WPF provides excellent support for shortcut keys:</p>
<ul>
<li>The InputBinding class supports Key, Mouse, and recently Touch gestures.</li>
<li>An InputBinding can be associated with any UIElement using the InputBindings property.</li>
<li>Custom controls that handle RoutedCommands can associate InputBindings using the CommandManager.RegisterClassInputBinding.</li>
<li>The  CommandManager provides tunneling and bubbling of the commands allowing any control with a CommandBinding to handle the command.</li>
<li>The static ApplicationCommands, ComponentCommands, and NavigationCommands provides commands that can be reused to implement common functionality.  These come with a converter allowing you to just name the command as a string.</li>
<li>Controls like Button expose Command and CommandParameter dependency properties that make commands a first-class citizen in WPF.</li>
</ul>
<p>Pretty great stuff.</p>
<h2><strong>Some problems</strong></h2>
<p>All is well - right up to the point where you want to have a shortcut key that works across your application, regardless of input focus.  You will quickly find that everything about the CommandManager wants to route starting at input focus and the entire tunneling/bubbling strategy will fight you tooth-and-nail.</p>
<p>I found some examples on the web where folks added Window.InputBindings on their main window and implement the commands on the main window.  This works because the main window is pretty much always in the routed command chain.  This is great for a trivial application, but not an application where the main window contains several different views that may be shown/hidden.  It is especially difficult when the UI is composed from a set of custom control libraries, or composed at run-time.</p>
<h2><strong>Solution Goals</strong></h2>
<p>I wanted the following from a global shortcut key solution:</p>
<ul>
<li><strong>Focus independent</strong> &#8211; Key gestures to work regardless of where the focus is.</li>
<li><strong>IsVisible aware</strong> &#8211; If a control is hidden, then the shortcut key doesn&#8217;t invoke that command.</li>
<li><strong>Follows standards </strong>- The command and input binding infrastructure of WPF is leveraged.</li>
<li><strong>Distributed bindings</strong> &#8211; Each control associates their commands with application-wide shortcut key gestures.  This is similar to how a button binds to a command, or a textbox binds Ctrl+X, Ctrl+C, Ctrl+V to global commands.</li>
<li><strong>Low impact</strong> &#8211; Because examining keystrokes for application-wide shortcut keys likely looks at every keystroke, the key down handler needs to be considerate of how much time and memory it consumes.</li>
<li><strong>Thread-safe </strong>- Key gestures and commands should work when multiple windows are open.</li>
<li><strong>Support declarative and imperative bindings </strong>- Key gestures can be bound in XAML or from code.</li>
</ul>
<h2><strong>A Solution: RegisterAppShortcutKeysBehavior</strong></h2>
<p>RegisterAppShortKeysBehavior is a standard System.Windows.Interactivity.Behavior&lt;T&gt; that can be attached to any control or control template. The behavior encapsulates all functionality required to support global shortcut keys.</p>
<p>In the following example the command is a static RoutedCommand property on the ChangeColorControl.</p>
<pre>&lt;local:RegisterAppShortcutKeysBehavior&gt;
  &lt;local:RegisterAppShortcutKeysBehavior.InputBindings&gt;
    &lt;KeyBinding Command="{x:Static local:ChangeColorControl.ChangeColor}" Gesture="CTRL+g"/&gt;
  &lt;/local:RegisterAppShortcutKeysBehavior.InputBindings&gt;
&lt;/local:RegisterAppShortcutKeysBehavior&gt;</pre>
<p>As well, controls can call static Register and Unregister methods in code.  When a control is unloaded, it is automatically unregistered.</p>
<pre>public static void Register(InputBindingCollection inputBindings, FrameworkElement commandTarget)
public static void Unregister(FrameworkElement commandTarget)</pre>
<h2>Running the Behavior</h2>
<p>You can download the behavior as part of a sample at: <a href="http://www.bellacode.com/code/GlobalShortcutsSample.zip">http://www.bellacode.com/code/GlobalShortcutsSample.zip</a>.</p>
<p><a href="http://blogs.southworks.net/geoff/files/2011/03/Capture.png"><img class="size-medium wp-image-73 alignnone" src="http://blogs.southworks.net/geoff/files/2011/03/Capture-300x200.png" alt="" width="300" height="200" /></a></p>
<p>Open the solution in VS 2010 and run it (F5).</p>
<p>In this sample, there is a custom control that contains a command to randomly change its background color.  The generic style for the control contains a button mapped to this command that you can click and see the color change.  As well, the style uses the behavior to map a global shortcut key of Ctrl+G.</p>
<p>On the main window there are two instances of the control.  You can show/hide each individual control to see how the command is only executed when the control is visible.</p>
<h2><strong>How it works</strong></h2>
<p>1.  In the <strong>OnAttached </strong>overridden  method:</p>
<ul>
<li>The InputBindings are added to a static  list and the control&#8217;s parent window is added to a static list.</li>
<li>The AssociatedObject of the Behavior base class is set as the command target for each InputBinding.  This allows the right control&#8217;s command to be invoked when the global shortcut  is pressed.</li>
<li>The behavior subscribes to each window&#8217;s PreviewKeyDown event.</li>
</ul>
<p>2. In the <strong>PreviewKeyDown </strong>event handler:</p>
<ul>
<li>In this event, the KeyEventArgs and keyboard state are matched against the static list of input bindings.  For each match,  the command is invoked.</li>
<li>The command is only invoked  when there is a modifier key down (Ctrl, Alt, or Shift).  This prevent performance issues from doing too much work on every keystroke the user types.</li>
<li>The command is only invoked when the control is visible.  This allows applications that show/hide views to automatically target the active view without having to complicate their CanExecute logic.</li>
<li>If a command is invoked, then e.Handled is set to true.</li>
</ul>
<p>3.  In the <strong>OnDetaching </strong>overridden method:</p>
<ul>
<li>During OnDetaching, the InputBindings and parent window are removed from their lists.</li>
</ul>
<p><strong>Some other details of this behavior:</strong></p>
<ul>
<li>The static lists are locked before they are read or modified to prevent windows running different message pumps on different threads to have an access violation.  Most UI is single-threaded, but I followed the practices of the CommandManager class here.</li>
<li>To improve performance of the PreviewKeyDown handler, I keep a copy of the InputBindings in an array that I acquire before looping.  This holds the lock for the shortest period of time and limits memory pressure to a single copy.</li>
<li>The parent window list keeps track of each control in order to &#8220;reference count&#8221;.  This prevents a window from being registered twice or removed too  early when multiple on controls in the same window register global shortcut keys.</li>
<li>In the case of using the static Register method:  If the window for control doesn&#8217;t exist, then the window registration is delayed until the control is loaded.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>x264 encoding with IIS Transform Manager</title>
		<link>http://blogs.southworks.net/geoff/2010/08/14/x264-encoding-with-iis-transform-manager/</link>
		<comments>http://blogs.southworks.net/geoff/2010/08/14/x264-encoding-with-iis-transform-manager/#comments</comments>
		<pubDate>Sat, 14 Aug 2010 00:08:18 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Emerging Technology]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[IIS Transform Manager]]></category>
		<category><![CDATA[X264]]></category>

		<guid isPermaLink="false">http://65.15</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2010/08/14/x264-encoding-with-iis-transform-manager/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blogs.southworks.net/geoff/files/2010/08/editjobtemplate.png"></a><a href="http://blogs.southworks.net/geoff/files/2010/08/edittask.png"></a><a href="http://blogs.southworks.net/geoff/files/2010/08/editwatchfolder.png"></a><a href="http://blogs.southworks.net/geoff/files/2010/08/edittask.png"></a>I recently got the time to play with the IIS Transform Manager and the X264 encoder.  I&#8217;ve created a Transform Manager task that allows for using X264 to encode videos by dropping files into a watch folder.  I based my work off of Ezequiel&#8217;s excellent <a href="http://blogs.southworks.net/ejadib/2010/07/27/rough-cut-editor-rce-and-iis-transform-manager-best-friends/">blog post </a>about integrating the RCE with Transform Manager.</p>
<p>While I&#8217;ve used encoding tools before, this was my first attempt at integrating with Transform Manager and my first time working with X264. </p>
<p>I found working with IIS Transform Manager much easier than I expected. Adding a new task only requires authoring a single class and a well-defined XML file.  Deployment is just dropping the DLL and XML in folders than a few clicks to configure.</p>
<p>The source code is included <span style="color: #ff0000"><a href="http://blogs.southworks.net/geoff/files/2010/08/transformx264.zip">here</a></span>.</p>
<p><strong>About X264</strong></p>
<p>X264 is a lightning fast, open source media encoder for creating H.264/MPEG-4 AVC format videos.  It has both a command line executable and an FFMPEG implementation. </p>
<p>I chose to work with the command-line executable because I could run it stand-alone to verify it worked outside of Transform Manager.  I may go back and build another task around the FFMPEG implementation later.</p>
<p>I found the following resources very helpful in understanding X264:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/X264"><span>http://en.<span>wikipedia</span>.org/wiki/X264</span></a></li>
<li><a href="http://www.videolan.org/developers/x264.html">http://www.<span><span>videolan</span></span>.org/developers/x264.html</a></li>
<li><a href="http://mewiki.project357.com/wiki/X264_Settings"><span>http://<span>mewiki</span>.project357.com/wiki/X264_Settings</span></a></li>
</ul>
<p><strong>Preparation</strong></p>
<p>These are the steps I went through to prepare my development machine.  I already had Visual Studio 2010 and IIS setup on a Windows 7 client machine.</p>
<p>Note: As I download files to the &#8216;My Downloads&#8217; folder, I always right-click the files to display properties and click the &#8216;Unblock&#8217; button.  Otherwise, some things won&#8217;t extract properly.</p>
<ol>
<li>I installed <a href="http://www.iis.net/media">IIS Media Services 4.0 Beta 1</a> from Microsoft using the Web Platform Installer 2.0</li>
<li>I installed <a href="http://www.iis.net/download/TransformManager">IIS Transform Manager 1.0 Alpha 1</a> from Microsoft using the Web Platform Installer 2.0</li>
<li>I download the latest X264 from <a href="http://x264.nl/">http://x264.<span><span>nl</span></span>/</a></li>
<li>I downloaded a sample Y4M video file from: <a href="http://wiki.multimedia.cx/index.php?title=YUV4MPEG2">http://wiki.multimedia.<span><span>cx</span></span>/index.<span><span>php</span></span>?title=YUV4MPEG2</a>. </li>
<li>I used <span><span>WinRAR</span></span> to extract the example.y4m.bz2 file. </li>
<li>I configured the IIS Transform Host service to log on using my credentials (which have administrator access) and started the service.</li>
</ol>
<p>This seems like a lot of steps, but it only took me about 30 minutes.  The IIS extensions and web platform installer add features to IIS without any annoying reboot.</p>
<p><strong>Getting Started</strong></p>
<p>The first thing I did was run X264.<span><span>exe</span></span> manually.  I gave it the example.y4m file and asked it to produce example.mp4. </p>
<pre><span>     x264.<span>exe</span> -o example.mp4 example.y4m</span></pre>
<p>This produced the video pretty instantaneously because the video is short.  I then ran the video in Windows Media Player (WMP) to ensure it looked right. </p>
<p>Next  I created a C# class library project in Visual Studio 2010.  I created an libs folder and copied in the required DLLS from the following locations.  Note: I&#8217;m running a 64-bit machine.</p>
<p>C:Program Files (x86)IISTransform Manager</p>
<ul>
<li>Microsoft.Web.Media.<span><span>TransformManager</span></span>.Common.<span><span>dll</span></span></li>
<li><span>Microsoft.Web.Media.<span>TransformManager</span>.Core.<span>dll</span></span></li>
<li>Microsoft.Web.Media.<span><span>TransformManager</span></span>.SDK.<span><span>dll</span></span></li>
</ul>
<p>I created 3 classes and 1 XML file:</p>
<ul>
<li>X264.cs &#8211; Launches the X264.<span><span>exe</span></span></li>
<li>X264<span><span>TransformTask</span></span>.cs &#8211; the <span><span>ITransformTask</span></span> implementation</li>
<li>X264<span><span>Namespaces</span></span>.cs &#8211; the set of <span><span>XNamespaces</span></span> to integrate with the task definition.</li>
<li><span>TransformX264</span><span><span>TaskDefinition</span></span>.<span><span>xml</span></span> &#8211; the XML file that defines the transform task.</li>
</ul>
<p>I realized I would by copying the DLL and XML file and stopping and restarting the service repeatedly during development, so I wrote a small batch file.  Your paths will vary:</p>
<pre>copy /Y "C:<span><span>Southworks</span></span>x264Transformx264Transformx264binDebugTransformX264.<span><span>dll</span></span>" "C:Program Files (x86)IISTransform ManagerTransformX264.<span><span>dll</span></span>" copy /Y "C:<span><span>Southworks</span></span>x264Transformx264Transformx264TransformX264<span><span>TaskDefinition</span></span>.<span><span>xml</span></span>" "C:<span><span>ProgramData</span></span>MicrosoftIISTransform ManagerConfigurationTask DefinitionsTransformX264<span><span>TaskDefinition</span></span>.<span><span>xml</span></span>" net stop <span><span>IISTMHost</span></span> net start <span><span>IISTMHost</span></span> pause</pre>
<p>For each of the following coding steps,  I wrote the code, built the project, ran the batch file, copied a video into the drop folder, and inspected the task activity log in the IIS Management Console/Transform Manager .</p>
<p><strong>Coding Part I - </strong>Running the task</p>
<p>I implemented the <span><span>ITransformTask</span></span> interface with Initialize() and Start().  I left Start() implemented as setting progress to 100.  I built and ran my batch file.  Then I configured the Transform Manager Task and created a Watch folder.</p>
<p> The following screen shots show additional properties that were implemented later.</p>
<p><a href="http://blogs.southworks.net/geoff/files/2010/08/editjobtemplate.png"></a></p>
<p style="text-align: center"><a href="http://blogs.southworks.net/geoff/files/2010/08/editjobtemplate.png"><img class="alignnone size-medium wp-image-16 aligncenter" src="http://blogs.southworks.net/geoff/files/2010/08/editjobtemplate-300x239.png" alt="" width="300" height="239" /></a></p>
<p style="text-align: center">Create an edit the job template</p>
<h4 style="text-align: center"><a href="http://blogs.southworks.net/geoff/files/2010/08/edittask.png"><img class="alignnone size-medium wp-image-17 aligncenter" src="http://blogs.southworks.net/geoff/files/2010/08/edittask-250x300.png" alt="" width="250" height="300" /></a></h4>
<p style="text-align: center">Add and edit the task template</p>
<p style="text-align: center"><a href="http://blogs.southworks.net/geoff/files/2010/08/editwatchfolder.png"><img class="alignnone size-medium wp-image-18 aligncenter" src="http://blogs.southworks.net/geoff/files/2010/08/editwatchfolder-300x228.png" alt="" width="300" height="228" /></a></p>
<p style="text-align: center">Add and edit the watch folder.</p>
<p><strong>Coding Part II -</strong>  Calling X264.<span><span>exe</span></span></p>
<p>I implemented the X264 class Run() method to use Process to launch the x264.<span><span>exe</span></span>. </p>
<p>I hard-coded the path to the x264.<span><span>exe</span></span>, the input file, and the output file to be the same as when I ran X264.<span><span>exe</span></span> from the command-line. </p>
<p>I then called X264.Run() from X264TransformTask.Start with a try-catch around it.</p>
<p><strong>Coding Part III -</strong>Parsing basic <span><span>metadata</span></span></p>
<p>I needed to make all x264.<span><span>exe</span></span> path location and output format configurable and to use the real path to the input file. </p>
<p><span>I added x264<span>ExePath</span> and <span>outputFileExtension</span> properties to the task definition file. I also wrote the following small helper method to get a property value. </span></p>
<pre style="font-family: consolas"><span style="color: blue">private</span> <span style="color: blue">string</span> <span><span>GetMetadataProperty</span></span>(<span style="color: blue">string</span> propertyName)
{
    <span style="color: #2b91af"><span><span>IManifestProperty</span></span></span> property = <span style="color: blue">this</span>.<span><span>transformMetadata</span></span>.<span><span>GetProperty</span></span>(<span style="color: #2b91af">X264<span><span>Namespaces</span></span></span>.X264 + propertyName);
    <span style="color: blue">if</span> (property != <span style="color: blue">null</span>)
    {
        <span style="color: blue">return</span> property.Value;
    }

    <span style="color: blue">return</span> <span style="color: blue">null</span>;
}</pre>
<p>I then leveraged Ezequiel&#8217;s code to get the input file name(s):</p>
<pre style="font-family: consolas"><span style="color: #2b91af"><span><span>IEnumerable</span></span></span>&lt;<span style="color: #2b91af"><span><span>XElement</span></span></span>&gt; elements = <span style="color: blue">this</span>.<span><span>transformMetadata</span></span>.Manifest.Descendants(<span style="color: #a31515">"ref"</span>);
<span style="color: blue"><span><span>foreach</span></span></span> (<span style="color: #2b91af"><span><span>XElement</span></span></span> element <span style="color: blue">in</span> elements)
{
<span style="color: blue">    string</span> fileName = (<span style="color: blue">string</span>)element.Attribute(<span style="color: #a31515">"<span><span>src</span></span>"</span>);
    <span style="color: blue">this</span>.<span><span>transformLogger</span></span>.<span><span>WriteLine</span></span>(<span style="color: #2b91af"><span><span>LogLevel</span></span></span>.Information, <span style="color: #a31515">"Transforming file: "</span> + fileName);
    <span style="color: blue">this</span>.Transform(<span><span>fileName</span></span>);
}</pre>
<p>While the <a href="http://msdn.microsoft.com/en-us/library/ff728119(v=VS.90).aspx">task definition schema</a> is nice, I wanted to see the real manifest so I would understand what I was navigating.  I used the following code temporarily to write out the manifest:</p>
<pre><span style="color: blue">using</span> (<span style="color: #2b91af"><span><span>StreamWriter</span></span></span> writer = <span style="color: #2b91af">File</span>.<span><span>CreateText</span></span>(<span style="color: #a31515">@"C:<span><span>Southworks</span></span>x264<span><span>Manifest</span></span>.<span><span>xml</span></span>"</span>))
{
<span style="color: blue">    using</span> (<span style="color: #2b91af"><span><span>XmlWriter</span></span></span> xmlWriter = <span style="color: #2b91af"><span><span>XmlWriter</span></span></span>.Create(writer))
    {
        <span style="color: blue">this</span>.<span><span>transformMetadata</span></span>.Manifest.<span><span>WriteTo</span></span>(<span><span>xmlWriter</span></span>);     
    }     

    writer.Flush();
}</pre>
<p> Now I had something that would do a basic transformation using X264 with arguments <span>loaded from </span>the Transform Manager Task.  I also went ahead and logged the actual command line X264 is called with to the Transform Manager activity log.</p>
<p><strong>Coding Part IV -</strong> Supporting X264 options (Take 1)</p>
<p>X264.<span><span>exe</span></span> has a lot of command line options and flags that I wanted to be able to handle.  Type x264 &#8211;<span><span>fullhelp</span></span> to see them all. To start I only needed a few: <span><span>keyint</span></span>, min-<span><span>keyint</span></span>, <span><span>scenecut</span></span>, and open-<span><span>gop</span></span>. </p>
<p>I didn&#8217;t want to have to write a lot of code each time I added support for a new option.   Given that the options are specified in the task <span>definition</span> XML file and would be passed to a command-line executable, I decided against having the task know too much about the options or try and enforce certain types/values for parameters.</p>
<p><span>As an example, I was tempted to convert the &#8216;&#8211;keyint&#8217; option to an integer and throw an exception if it didn&#8217;t convert.  However, X264.<span>exe</span> will take &#8220;infinite&#8221; as a valid number.  </span></p>
<p>I noticed X264.<span><span>exe</span></span> has two types of options: name-value pair and named flags. </p>
<p>I updated X264 with a dictionary of name-value pairs and the argument builder to pass them along to x264.<span><span>exe</span></span>.  I supported flags by <span>outputting</span> only the name if the value is string.Empty. </p>
<pre style="font-family: consolas"><span style="color: blue">string</span> optionValue;
<span style="color: blue">foreach</span> (<span style="color: blue">string</span> optionName <span style="color: blue">in</span> <span style="color: blue">this</span>.options.Keys) {     optionValue = options[optionName];     arguments.Append(<span style="color: #a31515">"--"</span>);     arguments.Append(optionName);     arguments.Append(<span style="color: #a31515">" "</span>);

    <span style="color: blue">if</span> (!<span style="color: blue">string</span>.IsNullOrEmpty(optionValue))     {         arguments.Append(optionValue);         arguments.Append(<span style="color: #a31515">" "</span>);
    }
}</pre>
<p><span>I then wrote two small methods on top of my <span>GetMetadataProperty</span>.  </span></p>
<p><span>Note: You won&#8217;t see these methods in my code because I found a more extensible way to handle options that I describe in the next section.</span></p>
<pre><span style="color: blue">private</span> <span style="color: blue">void</span> ProcessMetadataX264Option(<span style="color: blue">string</span> propertyName)
{
<span style="color: blue">    string</span> propertyValue = <span style="color: blue">this</span>.<span><span>GetMetadataProperty</span></span>(<span><span>propertyName</span></span>);     </pre>
<pre>    <span style="color: blue">if</span> (!<span style="color: blue">string</span>.<span><span>IsNullOrEmpty</span></span>(<span><span>propertyValue</span></span>))     
    {     
        <span style="color: blue">this</span>.x264.Options[<span><span>propertyName</span></span>] = <span><span>propertyValue</span></span>;     
    } 
} 

<span style="color: blue">
private</span> <span style="color: blue">void</span> ProcessMetadataX264Flag(<span style="color: blue">string</span> propertyName)
{
<span style="color: blue">    string</span> propertyValue = <span style="color: blue">this</span>.<span><span>GetMetadataProperty</span></span>(<span><span>propertyName</span></span>);     
<span style="color: blue">    if</span> (!<span style="color: blue">string</span>.<span><span>IsNullOrEmpty</span></span>(<span><span>propertyValue</span></span>) &amp;&amp; 
       (<span style="color: blue">string</span>.Compare(<span><span>propertyValue</span></span>, <span style="color: #a31515">"false"</span>, <span style="color: #2b91af"><span><span>StringComparison</span></span></span>.<span><span>OrdinalIgnoreCase</span></span>) != 0))     
    {     
<span style="color: blue">        this</span>.x264.Options[<span><span>propertyName</span></span>] = <span style="color: blue">string</span>.Empty;
    } 
}</pre>
<p>Finally, I separated initializing X264 into a separate method, added string array to list the option and flag names, and some <span><span>foreach</span></span> loops to process each one.</p>
<pre><span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span>[] x264Options = <span style="color: blue">new</span> <span style="color: blue">string</span>[] { <span style="color: #a31515">"<span><span>keyint</span></span>"</span>, <span style="color: #a31515">"min-<span><span>keyint</span></span>"</span>, <span style="color: #a31515">"open-<span><span>gop</span></span>"</span>, <span style="color: #a31515">"<span><span>pulldown</span></span>"</span>, <span style="color: #a31515">"<span><span>scenecut</span></span>"</span>};
<span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">string</span>[] x264Flags = <span style="color: blue">new</span> <span style="color: blue">string</span>[] { <span style="color: #a31515">"<span><span>tff</span></span>"</span>, <span style="color: #a31515">"<span><span>bff</span></span>"</span> };</pre>
<p>Now to add support for an X264 option, all that would be required is to add it to the task definition XML and update the array of option and/or flag names.</p>
<p><strong>Coding Part V &#8211; </strong>Supporting X264 options (Take 2)</p>
<p>Although recompilation isn&#8217;t the worst thing, I didn&#8217;t like that I had to keep the array of option names and the task definition file synchronized. </p>
<p>Looking at the task definition and the manifest, I saw that all the properties are prefixed with my <span><span>namespace</span></span> prefix &#8216;MSX264&#8242;.  I also noticed that <span><span>ITransformMetadata</span></span>.<span><span>TaskMetadata</span></span> selects the task properties.  I updated the code to process all the task <span><span>metadata</span></span>. </p>
<p>x264<span><span>ExePath</span></span> and <span><span>outputFileExtension</span></span> are special properties, so I handle those directly. To distinguish name-value pair from flags, I prefix flags with &#8216;flag-&#8217;.   Note: <span><span>XName</span></span>/<span><span>XElement</span></span> restrict using most punctuation like parenthesis, exclamation point, or dollar sign.</p>
<pre style="font-family: consolas"><span style="color: blue">private</span> <span style="color: blue">void</span> ProcessTaskMetadata()
{            
    <span style="color: #2b91af"><span><span>IEnumerable</span></span></span>&lt;<span style="color: #2b91af"><span><span>XElement</span></span></span>&gt; elements = <span style="color: blue">this</span>.<span><span>transformMetadata</span></span>.<span><span>TaskMetadata</span></span>.Descendants();     
    <span style="color: blue"><span><span>foreach</span></span></span> (<span style="color: #2b91af"><span><span>XElement</span></span></span> element <span style="color: blue">in</span> elements)
    {
        <span style="color: blue">if</span> (element.Name.Namespace == <span style="color: #2b91af">X264<span><span>Namespaces</span></span></span>.X264)
        {
            <span style="color: blue">if</span> (element.Name.LocalName == <span style="color: #a31515">"x264<span><span>ExePath</span></span>"</span>)
            {
                <span style="color: blue">if</span> (!<span style="color: blue">string</span>.<span><span>IsNullOrEmpty</span></span>(element.Value))                 
                {                     
                    x264.ExePath = element.Value;                 
                }       
            }
            <span style="color: blue">else</span> <span style="color: blue">if</span> (element.Name.LocalName == <span style="color: #a31515">"<span><span>outputFileExtension</span></span>"</span>)
            {
                <span style="color: blue">if</span> (!<span style="color: blue">string</span>.<span><span>IsNullOrEmpty</span></span>(element.Value))                 
                {                     
                    outputExtension = element.Value;                 
                }
            }             
            <span style="color: blue">else</span> <span style="color: blue">if</span> (element.Name.<span><span>LocalName</span></span>.<span><span>StartsWith</span></span>(<span style="color: #a31515">"flag-"</span>, <span style="color: #2b91af"><span><span>StringComparison</span></span></span>.<span><span>OrdinalIgnoreCase</span></span>))             
            {                 
<span style="color: blue">                string</span> flagName = element.Name.<span><span>LocalName</span></span>.<span><span>Substring</span></span>(5);                 
<span style="color: blue">                if</span> (<span style="color: blue">string</span>.Compare(element.Value, <span style="color: #a31515">"true"</span>, <span style="color: #2b91af"><span><span>StringComparison</span></span></span>.<span><span>OrdinalIgnoreCase</span></span>) == 0)                 
                {                     
<span style="color: blue">                    this</span>.x264.Options[<span><span>flagName</span></span>] = <span style="color: blue">string</span>.Empty;
                }
            }
            <span style="color: blue">else</span>
            {
                <span style="color: blue">if</span> (!<span style="color: blue">string</span>.<span><span>IsNullOrEmpty</span></span>(element.Value))                 
                {                     
                    <span style="color: blue">this</span>.x264.Options[element.Name.<span><span>LocalName</span></span>] = element.Value;                 
                }             
            }
         }
     }
 }</pre>
<p>Now to support a new X264 option, only the task definition file needs to be updated, re-dropped, and the service restarted.</p>
<p><strong>Summary</strong></p>
<p>In a little over 2 days I was able to integrate a the X264 encoder with IIS Transform Manager.</p>
<p>This task supports:</p>
<ul>
<li>Launching the X264 command line executable.</li>
<li>Configuring the location of the X264 executable and the output format in the task definition.</li>
<li>Adding properties to the task definition and passing those options along to X264.</li>
<li>Distinguishing between X264 name-value and flag options in the task definition.</li>
<li>Logging completion/failure back to the Transform Manager.</li>
</ul>
<p>I&#8217;m pretty happy with this for a first working version, although I have some improvements that could be made to this code:</p>
<ul>
<li>Replacing the magic strings and number with constants</li>
<li>Redirecting stdout on the X264 exe to the activity log.</li>
<li>Catching the and reporting the X264 exit code.</li>
<li>Generally better fault tolerance.</li>
</ul>
<p>Transform Manager lets you easily integrate and chain tasks together, so the output of this task could be chained to MP4 to smooth streaming and deployment out to other locations.  Transform manager also provides a stable and efficient work flow for processing files that are dropped into watch folders.  The task definition is a nice blend of setting properties and defining a task schema.  Overall, I think Transform Manager puts video processing within IIS within reach for any developer.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An improvement to INotifyPropertyChanged</title>
		<link>http://blogs.southworks.net/geoff/2010/05/22/an-improvement-to-inotifypropertychanged/</link>
		<comments>http://blogs.southworks.net/geoff/2010/05/22/an-improvement-to-inotifypropertychanged/#comments</comments>
		<pubDate>Fri, 21 May 2010 23:30:31 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[INotifyPropertyChanging]]></category>
		<category><![CDATA[PropertyChangedEventArgs]]></category>

		<guid isPermaLink="false">http://65.9</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2010/05/22/an-improvement-to-inotifypropertychanged/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: right"><span style="color: #027ac6"><span style="color: #027ac6"><a href="http://www.microsofttranslator.com/bv.aspx?ref=Internal&amp;from=&amp;to=es&amp;a=http%3a%2f%2fblogs.southworks.net%2fgeoff%2f2010%2f05%2f22%2fan-improvement-to-inotifypropertychanged%2f">en español</a></span></span></p>
<p>Awhile back, I needed to have one object calculate a total across a collection of items for a value that changed regularly.  Using a just-in-time calculation wasn&#8217;t efficient due to a large number of items and some complexity in the total calculation.</p>
<p>I first tried implementing and using INotifyPropertyChanging.  This caused some small performance problems because now I was firing 2x the number of events.  It also made the subscribing to events more complex as the subscriber had to remember the value between the changing event handler and the changed event handler. Otherwise, I ended up wtih an intermediate incorrect state during the transition.</p>
<p>Download the <a href="http://blogs.southworks.net/geoff/files/2010/05/notifypropertychangedsample.zip">Source Code</a>.</p>
<p><strong>PropertyChangedEventArgs&lt;T&gt;</strong></p>
<p>I needed a PropertyChangedEventArgs that passed both the old and new value.  I want it to be type-safe as well. My solution was to write PropertyChangedEventArgs&lt;T&gt;.</p>
<pre>public class PropertyChangedEventArgs&lt;T&gt; : PropertyChangedEventArgs
{
  public PropertyChangedEventArgs(string propertyName, T oldValue, T newValue)
    : base(propertyName)
  {
    this.OldValue = oldValue;
    this.NewValue = newValue;
  }</pre>
<pre>  public T NewValue { get; private set; }</pre>
<pre>  public T OldValue { get; private set; }</pre>
<pre>} </pre>
<p><strong>Raising the event</strong></p>
<p>Raising the event just requires remembering the old and new values.  Not every property has to raise the new event arguments type since it would likely be inefficient for large objects or long strings.</p>
<pre>public double MyValue
{
  get
  {
    return this.myValue;
  }</pre>
<pre>  set
  {
    if (this.myValue != value)
    {
      double oldValue = this.myValue;
      this.myValue = value;
      this.RaisePropertyChanged&lt;double&gt;("MyValue", oldValue, this.myValue);
    }
  }
}</pre>
<p><strong>Subscribing to the event</strong></p>
<p>Existing subscribers not have to be changed, and those that need PropertyChangedEventArgs&lt;T&gt; just cast to the derived agruments type:</p>
<pre>private void MyClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
  PropertyChangedEventArgs&lt;double&gt; e2 = (PropertyChangedEventArgs&lt;double&gt;)e;</pre>
<pre>  switch (e.PropertyName)
  {
    case "MyValue":
    {                       
      if (e2.OldValue != e2.NewValue)
      {
        this.MyTotal = this.MyTotal - e2.OldValue + e2.NewValue;
      }
    }</pre>
<pre>    break;</pre>
<pre>    //...
  }
}</pre>
<p> </p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generic IPropertyAccessor (and implementation trick)</title>
		<link>http://blogs.southworks.net/geoff/2010/05/19/generic-ipropertyaccessor-and-implementation-trick/</link>
		<comments>http://blogs.southworks.net/geoff/2010/05/19/generic-ipropertyaccessor-and-implementation-trick/#comments</comments>
		<pubDate>Tue, 18 May 2010 20:19:07 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IPropertyAccessor]]></category>
		<category><![CDATA[static type checking]]></category>

		<guid isPermaLink="false">http://65.7</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/geoff/2010/05/19/generic-ipropertyaccessor-and-implementation-trick/" class="more-link">read more<img src="http://blogs.southworks.net/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: right"><span style="color: #027ac6"><a href="http://www.microsofttranslator.com/bv.aspx?ref=Internal&amp;from=&amp;to=es&amp;a=http%3a%2f%2fblogs.southworks.net%2fgeoff%2f2010%2f05%2f19%2fgeneric-ipropertyaccessor-and-implementation-trick%2f">en español</a></span></p>
<p>Last week I needed a way to get at the property values in a class (instance) by name.  The class implementing the properties and the class accessing the properties needed to be independent.  </p>
<p>I also didn&#8217;t want to implement a class per property (way too much typing), and I didn&#8217;t want to have to instantiate anything per class instance that I was accessing.</p>
<p>I put my final solution into a small sample. Download the <a href="http://blogs.southworks.net/geoff/files/2010/05/samplepropertyaccessor.zip">Source Code</a>. </p>
<p><strong>First attempt</strong></p>
<p>I started with a weakly-typed approach that used object:</p>
<pre>public interface IPropertyAccessor
{</pre>
<pre>  object GetPropertyValue(object @object, string propertyName);</pre>
<pre>  void SetPropertyValue(object @object, string propertyName, object value);</pre>
<pre>}</pre>
<p>This worked well enough and was simple to implement using a switch statement on propertyName. I wasn&#8217;t very happy with this approach because it isn&#8217;t type safe.   My caller knew the properties to access and their types. </p>
<p><strong>A type-safe attempt</strong></p>
<p>I modified the class to be a generic:</p>
<pre>public interface IPropertyAccessor&lt;T&gt;
{</pre>
<pre>  TProperty GetPropertyValue&lt;TProperty&gt;(T @object, string propertyName);</pre>
<pre>  void SetPropertyValue&lt;TProperty&gt;(T @object, string propertyName, TProperty value);</pre>
<pre>}</pre>
<p>This appeared to be a great solution &#8211; until I tried to implement GetPropertyValue and SetPropertyValue and got a compiler error- &#8220;Cannot implicitly convert type &#8216;string&#8217; to &#8216;TProperty&#8217;&#8221;.</p>
<pre>public TProperty GetPropertyValue&lt;TProperty&gt;(MyObject @object, string propertyName)
{
  switch (propertyName)
  {</pre>
<pre>    case "Name":
      return obj.Name;  //ERROR here! (and casting won't help)</pre>
<pre>    default:
      throw new ArgumentException("Unrecognized property name.", "propertyName");                   
  }
}</pre>
<p><strong>Solution &#8211; Trick the compiler</strong></p>
<p>I was stuck until <a href="http://blogs.msdn.com/user/Profile.aspx?UserID=28764">Michael Puleio</a> showed me some code that used the following to trick the compiler into not trying to statically type check.  This extension method to object makes the static type checker give up through the use of a generic method that does the casting.</p>
<pre>public static T CastAs&lt;T&gt;(this object value)
{
  return (T)value;
}</pre>
<pre>public TProperty GetPropertyValue&lt;TProperty&gt;(MyObject @object, string propertyName)
{
  switch (propertyName)
  {</pre>
<pre>    case "Name":
      return obj.Name.CastAs&lt;TProperty&gt;;  // This works!</pre>
<pre>    default:
      throw new ArgumentException("Unrecognized property name.", "propertyName");                   
  }
}</pre>
<p> I&#8217;ve seen some examples using reflection, but I wanted a compiled approach for the case I had.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
