WPF

Source code for Jason Dolinger’s Model-View-ViewModel presentation

December 3rd, 2008

Some time back, I posted Jason’s presentation on Model-View-ViewModel and dependency injection with WPF and Unity (if you haven’t checked it out yet, you really should… the stuff there is good for Silverlight, too).  There were numerous requests to take a look at the source code.  It’s now available here.

Jason Dolinger on Model-View-ViewModel

November 6th, 2008

A while back, Jason Dolinger, a consultant here at Lab49, gave us a presentation on design in WPF with the Model-View-ViewModel pattern and the Unity dependency injection framework.

Jason started with an application that one would write in a “traditional” way, with button clicks handled by event-handlers in the code-behind that then updated other parts of the UI. Using WPF data-binding, Commands, and Unity, he transformed it, piece by piece, in a much more manageable, encapsulated, readable, and testable M-V-VM design. It was awesome.

It was so awesome, in fact, that after the presentation Jason recorded the demo for all to see here.

Check it out. It’s the most practically instructive explanation of WPF design I’ve seen.

UPDATE: I thought I should mention that while Jason’s presentation is geared towards WPF, the patterns he describes are very applicable for Silverlight as well. There are a few things to take note of, though:

1) Jason creates ViewModels that are DependencyObjects. For some (apparently undocumented) reason, DataContexts in Silverlight cannot be DependencyObject descendants. That means that you need to implement ViewModels as INotifyPropertyChanged (an option also available for WPF that Jason mentions in his video). This doesn’t fundamentally affect the pattern, but should be noted.

2) Unity, which Jason uses for dependency injection, is available for Silverlight right now as part of pre-release Composite WPF & Silverlight (Prism) v2. You can download it here. (I haven’t been able to find Unity for Silverlight as a separate download.)

3) Silverlight does not support bindings for Commands out of the box. It does, however, expose the ICommand interface. With just a little bit more work using an “Attached Behavior” approach, we can get the kind of Commanding that Jason uses in Silverlight as well. Check out the description here.

Running WPF Application with Multiple UI Threads

July 29th, 2008
Introduction

It’s a good, time-proven practice to perform long, CPU intensive tasks on some sort of a background thread to improve your UI thread responsiveness. Sometimes though UI-related tasks themselves can be quite expensive. WPF, for examples, forces you to do all UI work on the thread that created the UI. A very flexible WPF measure/layout paradigm for UI rendering also comes with high CPU usage cost. In a very UI intensive application (for example, trading app with about ten windows showing real-time montage and blotter data) simply the cost of generating and laying out visuals can become too high for a single thread to keep up. When your UI thread saturates individual windows may start skip rendering cycles, become slow to response to user input, or even freeze. If your UI thread approaches this kind of saturation you should consider creating dedicated UI threads for some (or all) of your UI-intensive windows. This post is a step by step walk-through of doing just that.

Read the rest of the article…

Composite WPF: Improving Out-of-the-Box Module Dependency Resolution

July 8th, 2008

Introduction

Microsoft has recently released its long awaited composite application framework for WPF (http://www.codeplex.com/CompositeWPF). As a heavy user and a big fan of the original CAB/Smart Client framework I rushed to explore it. To say that I was impressed is to say nothing. The [patterns & practices] team has done a tremendous job. The first thing that amazed me is the quality of the supporting documentation: direct mentioning and in-depth discussion of patterns used and architectural  decisions made, extensive tutorials and walk-throughs on all major concepts, and very cool reference implementation. So I immersed myself in CompositeWPF implementation to figure out how it stands against its CAB predecessor. I was specifically interested to see what CAB’s deficiencies were addressed and what are the areas improved and polished. So I started from the very beginning…

At the core of the composite application framework lies dynamic discovery and dependency resolution of its modules. This article discusses dependency resolution implementation in the new framework, its limitations (in both new and original frameworks), and suggests the ways to overcome those limitations.

Read the rest of this entry »

How to: Running multiple WPF applications in the same process using AppDomains

June 19th, 2008

    Step 1: Creating basic WPF application

    The first step is to create a simple host application. Select "File/New/Project…" in Visual Studio and pick "Visual C#/Windows/WPF Application". Give it a name of "WPFDomainLab" and click OK.
    The default application with a single main window is generated. Now go to the properties for "App.xaml" and change its "Build Action" from "Application Definition" to "Page". This allows us to add our own Main() method with explicit WPF application startup code. If you try to compile at this point you should be getting "Program ‘XXXX.exe’ does not contain a static ‘Main’ method suitable for an entry point".

    We now need to add Main method to handle WPF startup. The following class will do it:

    using System;
    
    namespace WPFDomainLab
    {
        class Startup
        {
            [STAThread()]
            static void Main()
            {
                App app = new App();
                app.MainWindow = new Window1();
                app.MainWindow.Show();
                app.Run();
            }
        }
    }

    Save this as Starup.cs and include it in your project. Now the project should compile. Before running it open Window1.xaml and have it display something interesting:

    <Window x:Class="WPFDomainLab.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="100" Width="300">
        <Grid>
            <ContentControl
                Content="{Binding DomainName}"/>
        </Grid>
    </Window>

    This will display the current domain’s friendly name. We now need to open the code-behind file (Window1.xaml.cs) and add the code to provide binding data context:

    using System;
    using System.Windows;
    
    namespace WPFDomainLab
    {
      /// <summary>
      /// Interaction logic for Window1.xaml
      /// </summary>
      public partial class Window1 : Window
      {
        public Window1()
        {
          InitializeComponent();
          this.DataContext = new {
            DomainName =
              "I live in " +
              AppDomain.CurrentDomain.FriendlyName
          };
        }
      }
    }

    If you compile and run the app at this point you should get the following window:

    image 

    At this point we have a single WPF application running in the default application domain.

    Step 2: Moving WPF app into a dedicated domain

    Lets go ahead and move this application to its own dedicated domain. These are the changes needed to accomplish this in a simple way (Startup.cs):

       1:  using System;
       2:   
       3:  namespace WPFDomainLab
       4:  {
       5:    class Startup
       6:    {
       7:      [STAThread()]
       8:      static void Main()
       9:      {
      10:        AppDomain domain =
      11:          AppDomain.CreateDomain(
      12:            "another domain");
      13:        CrossAppDomainDelegate action = () =>
      14:        {
      15:            App app = new App();
      16:            app.MainWindow = new Window1();
      17:            app.MainWindow.Show();
      18:            app.Run();
      19:        };
      20:        domain.DoCallBack(action);
      21:      }
      22:    }
      23:  }

    Lines 10-12 create another domain.

    Lines 13-19 are used to package application startup logic in a delegate that will be remotely executed in another domain.

    Line 20 actually runs the delegate in “another domain” and creates full-blown WPF application there. If you compile and run the app now you should get the following:

    
    image 

    Step 3: Starting second WPF application in its own domain

    Adding a second instance of our WPF application running in yet another domain looks simple now, but it has some caveats. Consider the following changes to create two separate domains each running a WPF app (Startup.cs):

       1:  using System;
       2:   
       3:  namespace WPFDomainLab
       4:  {
       5:    class Startup
       6:    {
       7:      [STAThread()]
       8:      static void Main()
       9:      {
      10:        var domain1 = AppDomain.CreateDomain(
      11:          "first dedicated domain");
      12:        var domain2 = AppDomain.CreateDomain(
      13:          "second dedicated domain");
      14:   
      15:        CrossAppDomainDelegate action = () =>
      16:        {
      17:          App app = new App();
      18:          app.MainWindow = new Window1();
      19:          app.MainWindow.Show();
      20:          app.Run();
      21:        };
      22:   
      23:        domain1.DoCallBack(action);
      24:        domain2.DoCallBack(action);
      25:      }
      26:    }
      27:  }

    Lines 10-13 create two different domains.

    Lines 23-24 actually create WPF applications in respective domains.

    If you run host application at this point you will find that it doesn’t quite work as expected. First a single window appears stating “I live in ‘first dedicated domain’ domain”. Only when you close the first window, the second one appears (after a pause), now stating “I live in ‘second dedicated domain’ domain”.

    The reason for this strange behavior is that all three domains (default one created by CLR and two domains we explicitly created) share the same execution thread. The first WPF app “hijacks” Window message pump and blocks the thread at “app.Run()”, so “domain2.DoCallBack(action);” is not even executed until the first app terminates.

     

    Step 4: Starting a dedicated thread for each domain

    To remedy this we need to create a dedicated thread for each of the domains that we create. The following changes accomplish the task (Startup.cs):

       1:  using System;
       2:  using System.Threading;
       3:   
       4:  namespace WPFDomainLab
       5:  {
       6:    class Startup
       7:    {
       8:      [STAThread()]
       9:      static void Main()
      10:      {
      11:        var domain1 = AppDomain.CreateDomain(
      12:          "first dedicated domain");
      13:        var domain2 = AppDomain.CreateDomain(
      14:          "second dedicated domain");
      15:   
      16:        CrossAppDomainDelegate action = () =>
      17:        {
      18:          Thread thread = new Thread(() =>
      19:          {
      20:            App app = new App();
      21:            app.MainWindow = new Window1();
      22:            app.MainWindow.Show();
      23:            app.Run();
      24:          });
      25:          thread.SetApartmentState(
      26:            ApartmentState.STA);
      27:          thread.Start();
      28:        };
      29:   
      30:        domain1.DoCallBack(action);
      31:        domain2.DoCallBack(action);
      32:      }
      33:    }
      34:  }

    Lines 18-24 create a dedicated thread object to run WPF app and package WPF app startup code inside this thread’s start method.

    Lines 25-26 sets the thread’s apartment to STA, this is a WPF requirement, otherwise it will not run (it will throw).

    Lines 27 actually starts a dedicated thread in the given domain.

    If you run application host now you will see both windows running in the same process in two different domains happily coexisting side by side. Applications are fully isolated, each getting its own static variables, base directory and configuration file (if customized). The performance is sluggish though and we are going to address this next.

     

    Step 5: Optimizing assembly loading

    When you ran the final application from step 4 you probably noticed that its startup time is extremely bad. Depending on your system it may take up to 10 seconds for the second application UI to show up.

    The reason is the default .Net loader behavior. By default every domain gets its own copy of assemblies loaded into domain’s context independently of other domains. It means that all .Net Framework and WPF assemblies will need to be loaded and JIT-ed twice (once in each domain). In addition to duplicating the work loading assemblies in non-default domain is extremely slow (I haven’t figured out why). Fortunately there is a simple solution for the problem and a simple change will do it:

       1:  using System;
       2:  using System.Threading;
       3:   
       4:  namespace WPFDomainLab
       5:  {
       6:    class Startup
       7:    {
       8:      [STAThread()]
       9:      [LoaderOptimization(
      10:        LoaderOptimization.MultiDomainHost)]
      11:      static void Main()
      12:      {
      13:  
      14:      }
      15:    }
      16:  }

    The attribute on line 9 does the trick. Basically it instructs .Net loader to load all GAC-installed assemblies in a domain-neutral way, thus sharing the assembly code between domains. This avoids loading and JIT-ing assemblies multiple times.

    You can read more about domain-neutral assemblies here.

    The final solution can be downloaded from here:


Using a Linq To SQL Query as a WPF DataContext

April 12th, 2008

Linq To SQL allows you to easily query data sources from a database to create in memory lists and enumerations. A typical query is:

IEnumerable<Person> people = from p in DBContext.Persons orderby p.LastName, p.FirstName select p;

You could then use "people" as your data context in WPF, but it’s very limiting since it’s only an IEnumerable<Person>. You can’t add new items, get an item by index, etc. The best option for WPF data binding would be to have an ObservableCollection<Person>, but you can’t get that from a Linq To SQL query and have the data context preserved. The next best option for WPF binding is BindingList<Person>, but how do you get one of those?

(BindingList<Person>)((IListSource)(from p in DBContext.Persons orderby p.LastName,p.FirstName select p)).GetList();

It takes a lot of casting, but this gives you what you need. This BindingList<Person> is still attached to the DBDataContext behind the scenes, so adding, removing, and updating items in the list works correctly. After manipulating the list, just call DBContext.SubmitChanges() and all changes will propagate to the database.

StockBoids blogging

March 18th, 2008

For those with questions about the winning entry in the WPF Contest, Szymon is blogging about it here

WPF Contest Winner Announced

March 16th, 2008

At the closing keynote of the 2008 Microsoft Financial Services Developer Conference in New York, I announced the finalists and winners for the first Lab49 WPF in Finance Innovation Contest:

The Grand Prize winner was Szymon Kobalczyk:
Szymon Kobalczyk screenshot

The two Finalists were Jacob Carpenter:
Jacob Carpenter screenshot

and Jobi Joy: 
Jobi Joy screenshot

while the Honorable Mention went to Paul Hounshell: 
Paul Hounshell screenshot 

These applications can all be downloaded from my SkyDrive account:


(link)

Everyone was very impressed with the level of innovation and creativity displayed by these entries. Congratulations to everyone, this was a great competition. 

Mix08: Tim Vercruysse from Lava Trading interview

March 13th, 2008

In this show I chatted with Tim Vercruysse, Director - Software Development, Citi/Lava Technology.  We discussed the unique challenges that he faces, being in the financial services industry, and how they differ from what most people mean when they talk about "user experience".  Tim also talked about the main benefits - beyond user experience - that he sees from Silverlight and WPF.  Last, we wrapped up with a discussion of what developers in the financial services industry need to learn in order to stay relevant in this demanding environment.

Listen to the podcast here (Quicktime file link)

Virtualized WPF Canvas

March 9th, 2008 / Development in a Blink

via WPF Performance blog. Chris Lovett from Microsoft now wrote a great sample that shows how you can also virtualize a Canvas container control so it can efficiently host and scroll thousands of WPF elements without consuming huge amount of memory. Download HERE Sample has code for these Gestures

WPF Contest Deadline Extended

February 28th, 2008

I’ve heard from a number of contestants who are working on their entries but (work/family/vacation/scrabulous/etc) has gotten in the way and they’d like a bit more time.  Well, we’ve heard you, and we’re extending the submission deadline until March 10th

That gives you plenty more time (including TWO extra weekends) to work on your entry before submitting it.

If you’ve already submitted something, don’t worry, you can use the extra time to improve your entry; you can keep submitting new versions right up until the deadline.

Don’t delay, get cracking! No excuses now…

(contest site here; submit here.)

All aboard the WPF Express

February 25th, 2008 / Development in a Blink

Scott Guthrie’s Silverlight 2.0 tutorials, Building a Simple Digg Client, closed the deal for me on using WPF. The closer, Part 8. The Rule of Least Surprise Is a general principle in the design of all kinds of interfaces, not just software: “Do the least surprising thing”. In my post Why use WPF? my friend Drew Marsh […]

Resources for Learning WPF

February 7th, 2008

As many of you know, Lab49 is sponsoring the WPF in Finance Innovation Contest. Over the course of the contest, several people have asked for some resources to learn WPF better.

As it happens a number of our distinguished judges have written excellent WPF books, I encourage you to check them out:

Adam Nathan - WPF Unleashed

Chris Sells - Programming Windows Presentation Foundation

Charles Petzold has actually written TWO books on WPF -
3D Programming for Windows AND Applications = Code + Markup

Our other two judges, Rob Relyea, and Josh Smith, have put together some great resources as well.

Rob has compiled a great list of WPF Books and WPF Resources, while Josh wrote up A Guided Tour of WPF.

Hope this helps & good luck in the contest.

WPF Contest Update - Now Open to All!

February 7th, 2008

Our WPF Contest has gotten a huge amount of interest not only from those in the U.S. but from many around the world. In the face of incredible demand, we have now updated the contest rules, eliminating the previous restriction to residents of the U.S., Canada and Mexico.

So, all you residents of South America, Europe, Asia, Africa, Oceania, and Antarctica :-) - open up your keyboards and get cracking! Deadlines are approaching.

Microsoft Syndicated Client Starter Kit released

January 30th, 2008

Microsoft Syndicated Client Starter Kit just released on WindowsClient.net :

…a Starter Kit designed to make it easy to create rich, syndicated multimedia and content experiences which engage the user, from documents and photos to videos and podcasts.

Jonathan Tigner at ActiveWin.com has the story here.  Yes Jonathan, we’re listening.

UI Automation, WPF and PowerShell

January 28th, 2008 / Development in a Blink

Dr. James McCaffrey’s article in the February 2008 msdn magazine Test Run: The Microsoft UI Automation Library outlines the new Microsoft UI Automation library. Read the article and download the source for more details. From here I created a class library and refactored his example into these five methods. PowerShell The script below acts on a simple WPF application […]

Legion - Grid computing using Silverlight

January 28th, 2008

Check out this excellent CodeProject submission named "Legion", which is a grid computing ("cycle stealing") framework in Silverlight, by Daniel Vaughan.

Legin Grid Management Window

Full disclosure: uses graphing component by Lab49’s own Andre de Cavaignac

New Whitepaper on the role of XAML in Designer/Developer collaboration

December 10th, 2007

Jaime Rodriguez and Karsten Januszewski have collaborated on a paper titled "The New Iteration: How XAML Transforms the Collaboration Between Developers and Designers in Windows Presentation Foundation".

HTML Version | PDF version

(via KarstenJ)

Mole II: Amazing WPF Debugger Visualizer

December 7th, 2007

Allows you to see the visual tree, logical tree, xaml, dependency and/or attached properties, collections, snapshots, etc etc etc.

Mole II WPF Debugger Visualizer on CodeProject.  This was build by Josh Smith (also a judge in our WPF Contest!), Karl Shifflett, and Andrew Smith (who doesn’t have a blog that I can find).

Obligitory screenshot:

image

Announcing the Lab49 WPF in Finance Innovation Contest

December 3rd, 2007

Ok, this is cool. 

This morning, we are announcing the first-ever "WPF in Finance Innovation Contest". WPF has enormous potential in finance, to affect the way we visualize and interact with the complex, fast-moving sea of data within the industry. To help spur innovation within this new area, we’re holding a contest with great prizes, challenging developers to build interesting new applications to visualize and interact with financial data. 

We’ve got an amazing panel of WPF luminaries to judge the entries.  We’ve lined up over $15,000 in prizes for the winners and early entrants. And the top 3 finalists will get to appear on stage at next year’s Microsoft Financial Services Developer Conference to showcase their app to the world.

So, we’ve done our part. 

Now go do yours - sign up and submit your entry.