Friday, December 17, 2010

“Sandbox” Editors with ClientUI Contacts

We’re developing a full-stack WPF/Silverlight development series in concert with Intersoft Solutions using DevForce and Intersoft’s “ClientUI” technology. You can learn about the series and keep up with the latest developments on our website.

Today I’m announcing the second installment of the series which replaces the “synchronous” editor with a “sandboxed” editor.

With the initial “synchronous” editor, users changes entered in the child window editor are visible immediately in the main view, the view that lists the contacts, as we see here:


That immediacy is a good experience in some screen layouts … say when the detail editor is embedded in the same screen as the list view. But many people feel that a child window editor implies a temporary workspace. Unsaved changes should be confined to the editor; changes should propagate to the main view only after the user saves them.

For example, the unfinished editing session in which we changed “Andre” to “Bob” should look like this:


In other words, the editing experience should take place “in a sandbox”, hence the name “sandboxed editor”. In the second sample in the DevForce/ClientUI series, we make some small changes to turn the “synchronous” editor into a “sandbox” editor.

In a post to follow very soon, I’ll describe the issues in detail and the code to get it done.I’ll be excerpting from the walkthrough document that accompanies the second code sample.

While that walkthrough is specific to the ClientUI sample, all of the principles and many of the techniques are applicable no matter how you build your DevForce application.

Go ahead … jump ahead of me and read that document. Or you can wait for me to re-cast it here in my blog in a few days. Either way, you can’t lose.

Happy holidays!

Update: Checkout the related post in which I answer an email about nested sandbox editors

Sunday, December 5, 2010

Design with Database Data in DevForce

Recently I’ve migrated John Papa’s BookShelf (aka BookClub) example to DevForce. Download the DevForce version (BookShelfDF) from our web site. You can learn about John’s original version and get his code from the PDC 2010 web page.


The DevForce BookShelfDF includes a document describing the steps for migrating from RIA Services to DevForce and proceeds to describe the improvements that DevForce made possible. Among them is the ability to create design-time entities for display while developing your Views in visual design tools such as Blend and the Visual Studio designer (“Cider”). This post is a reprint of that section of the document.

Warning: this is a long-ish post.

Monday, November 22, 2010

ClientUI Sample: MVVM for WPF & Silverlight

We just published a new sample application in partnership with Intersoft Solutions. Here’s what excites me about it:

  • Two solutions, in WPF and Silverlight, share the same source code and XAML
  • Demonstrates MVVM and Repository patterns
  • The views are Blendable and rely on design data delivered by ViewModels
  • It looks great
  • It’s concise and easy to read
  • Includes a fifty page walkthrough that explains how it is put together and why
  • A terrific mash-up of DevForce and some great Intersoft UI controls

Learn more about our evolving series of joint samples.

Download the code

See what Jimmy Petrus of Intersoft says about it

The Intersoft “ClientUI Sample” was the inspiration. It’s a lovely demo of a Forms-Over-Data application – a “Contact Editor” built with Intersoft controls. The UI presents two views: one lists all Contacts; the second is an overlay dialog for editing the currently selected contact and address. A “contact” is a person with an address.


The application appears and behaves the same in both WPF and Silverlight flavors. Intersoft’s APIs are identical for both WPF and Silverlight. They built both versions of the sample using the same code and xaml files, no changes required. They simply compiled separately against the WPF and Silverlight libraries. We thought that was pretty neat (and no mean feat).

Our two companies teamed-up to extend Intersoft’s “UI-only” sample with a DevForce entity model and our distributed persistence components so the editor could retrieve and save data from a database.

The DevForce APIs are the same for all .NET client platforms (ASP.NET, Windows Forms, WPF, Silverlight). As with Intersoft products, you write it once compile for the target libraries.

After integration with DevForce, the ClientUI sample became an end-to-end Contact editor that can save … delivered in WPF and Silverlight, built on a single code base.

Intersoft’s original ClientUI sample followed an MVVM design. That made our DevForce integration job easy. We hardly touched the views. We replaced the original, hand-coded model with a DevForce generated model that can exchange data with a database over the internet. We introduced a Repository and EntityManagerFactory, massaged the ViewModels, added a dash of configuration … and voila!

The conversion process is covered in detail - with digressions on patterns used and design choices - in a fifty page PDF that is part of the downloaded zip file.

We have our ideas for future development. We’ll surely demonstrate how to “sandbox” the editing dialog so that changes propagate to the main view only after they are saved. I’d like to add automated testing and maybe we’ll dare to use an IoC container. I’m sure you’ll tell us what you’d like to see.



The sample assumes you’ve installed IdeaBlade’s DevForce (6.0.7 or later, free version is fine) and Intersoft’s “ClientUI 2010” (v3.0.5000.11 or later, trial version is fine).

Friday, November 12, 2010

Silverlight Firestarter: See what’s coming


Want to know what Silverlight is all about and what’s coming in Silverlight vNext? Reserve a few hours on Thursday 12/2 for a free seminar from the folks that know: the Microsoft Silverlight team and friends.

You can catch it all online or be there in person and meet some wonderful people.

What part of “Free” do you not understand? Go register:

P.S.: I’ll be there in person. Look me up.

Wednesday, November 10, 2010

Silverlight’s Bright Future

Our strategy has shifted” may be the most unfortunate phrase ever uttered by a Microsoft exec. Bob Muglia, President of the Server and Tools Division, said it in his interview with Mary Jo Foley. Pundits and Silverlight detractors have been partying on it for more than a week.

It should just be good theater. Unfortunately, it has spooked the herd. More than a few of our customers and prospects are wondering if Silverlight is “dead”.

Some Silverlight defenders counter by reminding us that HTML 5 is not ready and runs on less than 1% of installed browsers.

But the merits and demerits of HTML 5 are beside the point. If you’re considering building in Silverlight, you have to know that Silverlight itself has a future. You don’t care about Silverlight 5. You want to know there will be a Silverlight 10. You want to believe that Microsoft sees Silverlight as a strategic, mainstream web development platform.

I believe Microsoft sees Silverlight as a strategic, mainstream web development platform … for many years to come.

Don’t take it on my authority; I don’t have any authority. Believe Bob Muglia when he sets the record straight. If I may paraphrase, Bob said Microsoft is investing heavily in HTML 5 because that is the standards-based technology with the potential for the broadest possible reach. Investment in HTML 5 does not mean abandoning Silverlight. It’s not a retreat from Silverlight. Far from it. Silverlight thrives … on the web, on the desktop, and on the phone.

Bob simply acknowledged that Microsoft will vigorously pursue multiple web technologies to meet diverse market needs.

Where is IdeaBlade going?

It’s IdeaBlade’s mission to help business application developers reach their users wherever they are, using whatever technology they want to use. Our DevForce product drives Console applications, “headless” services, Windows Forms, WPF, Silverlight, and HTML applications written with Web Forms and MVC.  Next month we’ll release our support for an OData API that enables any client … including any phone … to access your DevForce business model.  When there is a way to write applications in HTML 5, we’ll be there too.

We are always balancing our portfolio of client technologies. But to be clear, we believe Silverlight is now – and will remain for the foreseeable future – the best way to build and deliver business applications to the web. Bob Muglia said it too: “Silverlight provides the richest way to build Web-delivered client apps”, especially “enterprise application[s] … both inside and outside the browser.”

No HTML technology today can match Silverlight in capability or productivity for the web application developer. A comparable HTML 5 platform by all accounts is years away.

What’s all the Fuss?

The story at last year’s PDC was “three screens and a cloud” glued together by Silverlight. Barely a year later they’re ballyhooing HTML 5 as the glue. A third of the keynote goes to IE 9 and HTML 5; Silverlight is hardly mentioned. Then Bob says “strategic shift” and the stuff hits the fan.

What we have here is a failure to communicate. Microsoft evangelizes the shiny new balls but seems less adept at the sustained marketing necessary to keep existing brands burning bright – xBox excepted. The Silverlight team is going great guns on Silverlight vNext development back in Redmond but you would not know that at PDC and there is still no public target for a putative Silverlight 5 release. Other consumer-facing corporations invest in their brands, especially successful brands. Even soap is regularly “new and improved.” Microsoft can’t count on product development to keep the brand alive. They should be as relentless on the marketing front.

They tried mightily to recover the Silverlight momentum. Muglia apologized (yes – he said “apologize”) for his part in launching the controversy. Read his post carefully; he was adamant that Silverlight is a strategic technology with a long future. When you’re done reading Bob, read Scott Guthrie’s post which reiterates and elaborates on Bob’s themes; Scott is Vice President of the Developer Division and he ought to know.

Of course they also have to promote HTML 5 in a big way and Silverlight must pay a price for its previously exaggerated ambitions. The truth is that Silverlight will have less reach than we once hoped. It will still be cross-platform – running in many browsers and on both Mac and Windows. But the grand vision of Silverlight on every device on the planet cannot be realized. That was always a tall order and, over the last year, it became obviously unachievable. Apple blocked them successfully on iPhone and iPad … and will continue to do so as long as their market share permits.

Microsoft must have a future on these devices; they are too important to ignore. And Microsoft also must provide an alternative to Silverlight in other venues where Silverlight is shut out. We all know that some customers prohibit browser plug-ins … which precludes both Silverlight and Flash.

Silverlight was never the only game in town. You’ve heard about MVC, yes? MVC is an HTML technology and will likely be the backbone of HTML 5 development. Scott Guthrie is as avid a promoter and staunch ally of MVC as he has been of Silverlight. His blog posts for the last few years give each technology equal love.

MVC did not diminish Scott’s enthusiasm for Silverlight … and neither does the prospect of HTML 5.

Silverlight is not just the Phone

Reading some of the press, you might fear that Silverlight had been relegated to a phone development platform. They talked a ton about “Silverlight + Phone” at PDC. Silverlight is indeed the preferred platform for the Windows Phone 7; other than XNA it is the only development platform for WP7. I suspect Muglia was so phone-conscious that, in the interview moment, he just didn’t think of what else we use Silverlight for … hence his unfortunate “other sweet spots” comment.

Give him a break. WP7 is the hot new thing. According to Steve Ballmer, it’s Microsoft’s next billion dollar product. It’s a big deal and a key theme at PDC. Talking up Silverlight on the phone is called “staying on message”.

But Silverlight is also the premier client technology in many other spaces. For example, it’s the best way to build applications on top of SharePoint and that process got a lot easier with SharePoint 2010. We saw Silverlight front-ends on Azure. We are seeing Silverlight front-ends on Bing.

From our perspective, the most important fact: Silverlight remains the recommended client platform for distributed business applications, both inside and outside the browser. Bob Muglia said it. Scott Guthrie reiterated it.

The FUD Factor

Do you think it is curious that some in the technical press and the Silverlight detractors so eagerly cling to Muglia’s one inapt phrase? Why do they misrepresent and dismiss his clarification? Do these people really know something? Do they have secret inside Microsoft skinny? Do they mention unnamed sources? A “deep throat” of some kind?

No. All they do is read the same tea leaves everyone else is stirring: Muglia’s interview, the IE9 PDC publicity parade, the lack of a big Silverlight announcement … and throw in their own wishful thinking (egregious example here).

I have no inside scoop either. I’m reading what you’re reading.

I do have real-world experience developing with Silverlight (question: can you name a “Silverlight is Dead” article by anyone who has written a Silverlight application?)

I have my Microsoft contacts and I spoke to as many of them as I could reach. Every one of them … without exception and without equivocation … believes passionately that Microsoft is committed to Silverlight. They are dead certain that the Silverlight franchise is growing. They believe that HTML 5 is a big bet too … but that it does not dim Silverlight’s star. And no one expected a “strategic shift” announcement.

I worked at GE for twelve years. I know what a “strategic shift” looks like. We would never learn of a “strategic shift” by reading a Friday afternoon interview in a trade rag.  GE doesn’t work that way. GE would prepare us for a bombshell like that. The board would know. The senior executives would know. The press kit would be prepared. Company meetings would be scheduled at every level.

Microsoft is no GE … but it isn’t stupid either. There was no preparation. Muglia’s remarks were a bolt from the blue – as he said himself. There wasn’t supposed to be an announcement. All we have here is an interview by an executive trying to stay on message: Azure, WP7, IE9+HTML5.

If you’ve ever worked for a business or run a business, you know how this happens: a casual remark to a journalist gets wildly misunderstood and misrepresented. You don’t make a critical decision on this basis. You exercise prudent judgment and listen when company executives correct the record.

Well … what of HTML 5?

Now I must speak for myself, not IdeaBlade.

HTML is the way to get the broadest possible reach. HTML 4 is perceived to lack the pizzazz for the new breed of rich internet applications so everyone is pinning hopes on HTML 5. There are some problems with that:

1. Near zero reach for the next few years. A tiny fraction of browsers installed today support HTML 5. It takes a long time to replace the installed base of browsers (proof: even Microsoft can’t seem to kill off IE6). Plug-ins (like Silverlight and Flash) have been adopted much more readily than new browsers.

2. HTML 5 is not a standard yet. The WC3 doesn’t think it’s ready; see here and here. The browser wars of the 1990s are coming back and it’s going to be hell for the developers trying to write applications that actually work on all the browsers on all the devices. One wag described HTML 5 as “Write once, test everywhere!”

3. The developer story is missing. Applications don’t build themselves. You need libraries and tools to design, develop, debug, and test. None of this infrastructure exists for HTML 5. You need experience and best practices to build an application properly. No one has experience building HTML 5 applications. The essential foundation of human and physical capital is years away.

4. HTML 5 sets the lowest common denominator for user experience. The Silverlight team wrote convincingly about this in a recent post. The comparatively low HTML standard and limited capabilities may be good enough for some applications; will it be good enough for yours? Or will it prevent your RIA developers from delivering the rich experience and features that your application requires and that your market demands?

Ask yourself why your application is not on the web today? If HTML 4 were a viable option, why aren’t you there now? Is it because you can’t affordably deliver the rich responsive experience of your existing application? What is it about HTML 5 that will change that picture? What in HTML 5 will make your application better than it would be in HTML 4?

Silverlight remains more productive, more testable, more maintainable than any HTML-targeted approach. I can think of other excellent reasons to build an HTML application. But if the balance of considerations favored Silverlight last week, I can’t imagine why the distant prospect of HTML 5 should change the equation today … as long as you believe Silverlight is going to continue to grow and improve … as I clearly do.

Sunday, September 5, 2010

DevForce and RIA Services Compared Part 1: Getting Started

Sorry folks. I've temporarily pulled my series of articles comparing WCF RIA Services with IdeaBlade's DevForce while I reconsider the approach. It will be back in another form.

      Saturday, September 4, 2010

      Billy sez: Design, Don’t Decorate

      Billy Hollis writes about application UI design in this month’s DevProConnections and how that is not the same as hanging new draperies with WPF and Silverlight.

      Here’s what I want you to do:

      1. Go read the article
      2. Look at the associated video
      3. Go to his website
      4. Find yourself a class

      The rest of this post is commentary.

      Most of us (include me among the “us”) are stuck in a rut. We’re bringing to our Silverlight apps the same tired user interactions that we built for WinForms or the Web.

      I’ll make my point with a rant about the Editable Grid.

      I am sick of the Editable Grid. It won’t die. It pops up in one UI after another.

      It’s not that I’m bored with it. I’m not suffering from ennui. I’m not making a fashion statement.

      It’s just bad. It screams “I don’t know what the user wants, I don’t care what the user wants, I’ll just chuck every thing on the screen and let him figure it out.

      The user, poor bastard, must scroll through endless columns until he stumbles on the one he wants. Every cell of every row is in the same font size and shade; he can’t visually distinguish the critical values from the who-really-cares values. Want to tame the scrolling? let’s shrink the font and get more columns on the screen.

      It’s a nightmare to program properly with unlimited opportunities to screw up and confuse the user at the same time.

      Ah … but it’s so easy to get started, right? A line or two and you’re done. Now you can get back to wondering when the Reactive Framework will be part of the BCL.

      The 3rd party control vendors know you want this atrocity and to differentiate their grids from Microsoft’s DataGrid they trick ‘em out with ever more confusing options (filters, sorters, groupers, frozen columns, tear-aways, column-configuration-savers, etc.).

      All so you can tip-toe past the courageous, hard work of demanding to know what the user really needs. Nah … just do the cowardly thing, give him every lever and dial imaginable, and tell him to figure it out for himself. Why think, Einstein, when you can make the user do it for you … and perfume the stench by saying “I gave him choices".

      Guess what control I use in 9 out of 10 demos? Yup, the editable grid.

      I am as bad as you guys.

      Like you, I’ve been happy as a clam, pasting a grid on page after page. The guy who woke me up … was Billy Hollis.

      Billy is here to remind us it doesn’t have to be that way. Silverlight and WPF have technically removed the barriers to efficiently writing productive user experiences.

      The problem isn’t the technology. It’s us. We are the problem. We aren’t clearing the cobwebs. We’re behaving like we did at the dawn of GUI interfaces … wondering how to port keystroke menus onto a window.

      Hey … the “Outlook” standard should be dead. It would be dead … if we didn’t grant it new zombie life in WPF.

      Billy is ready to show us how to move on.

      Did you know Billy offers WPF and Silverlight design training?

      Not “Insert-Tab-A-into-Slot-B” training. I mean training your mind and your skills to get out of the rut. Sure you’ll learn WPF/Silverlight – duh. And I’m not knocking that kind of training either; it’s valuable too.

      What I really need is some help seeing UI differently and, most important, acquiring a discovery process to help me develop a UI that supports my user. Maybe … just maybe … I’ll finally learn to build a UI that is thoughtful and usable … and not waste weeks agonizing over my failures.

      It’s up to you. I recommend you hustle over to Billy’s website and see if you can find a way to take one of his classes. That’s what I’m going to do … if they ever let me out of here.

      p.s.: I’m still doing editable grids in my demos. You can lead a horse to water …

      Is Mvvm Light Right For You?

      I wrote in “DevForce Meets Mvvm Light” about how easy it is to use these products together on the same application.

      Is “Mvvm Light” the way to go?

      There is no right way to go. You have choices. There is Prism to consider. I’m a big Caliburn.Micro fan too.

      But those may be a bit daunting for folks just starting down the MVVM road and perhaps you don’t need their sophistication for your application … yet.

      I recently asked Laurent to give me the name of an Mvvm Light expert to help me build an example. That was before I downloaded the product. One look and I had a healthy laugh at myself. You don’t need no stinking expert to use this “framework”. It’s pretty darned obvious.

      It really lives up to its “Light” name. It is truly almost instantly accessible. To be honest, many of the applications our customers build would need more infrastructure than you’ll find in Mvvm Light. He made some choices that are too lightweight for these apps.

      But … and there is always a but … I sense this is a great way to get into the water and it will float you a nice distance before you decide you need something richer (and more obtuse).

      Maybe you’ll never need “more”. I’ll bet that, even if you do, you’ll be able to merge or port your Mvvm Light work straight into whatever framework you ultimately adopt.

      I’ll admit it; I’m a geeky guy with a weakness for unnecessary complexity. The angel on my shoulder says “cut your audience some slack and introduce them to Mvvm Light.”  The devil on my shoulder says “come on … they’re going to need the heavy machinery and you make your living showing off … this Mvvm Light stuff won’t burnish your reputation for arrogant sophistication!”

      Today, I’m listening to the angel. I think. Sometimes I can’t tell which is which. Whatever.

      Here’s some recent praise from other high-profile luminaries who favor Mvvm Light.

      From: Billy Hollis
      Sent: Friday, September 03, 2010 7:40 AM
      To: 'Ward Bell'
      I prefer an approach of starting simpler and building just the complexity needed instead of starting complex and just putting up with all the complexity. I consider MVVM Light, for example, to be a better starting point for the majority of teams.


      Jonathan Goodyear’s editorial in DevProConnections Magazine, August 2010

      We reviewed several frameworks, among them Microsoft’s Prism and Caliburn. … we felt strongly … that the framework … should have as few moving parts as possible. Our team has a couple of designers on board, so compatibility with Expression Blend (or “blendability”) was important as well.  I think that we found a near perfect match in MVVM Light.

      DevForce Meets Mvvm Light

      Model-View-ViewModel (MVVM) is THE most successful UI development paradigm ever …  measured by the number and variety of people talking about it. I don’t recall anything like this level of interest with respect to MVP or MVC. For most of UI history the majority of developers couldn’t name the pattern they were using … if they even thought they had a pattern. “MVC”, for most people, is a technology, not a design pattern.

      Today, MVVM is the jargon-du-jour. And I think that’s a good thing.

      We should retain some perspective. Not every view must be MVVM. And yet a healthy number of WPF/Silverlight screens should be done in MVVM style and I’d want to have a really good reason to depart from that standard.

      How do you write a screen in MVVM style? Do you need a framework?

      Some people think you do. There are plenty to choose from. And Laurent Bugnion’s “MVVM Light” has to be the most popular of the ulta-lightweight choices.

      One of our customers asked for an example of DevForce and Mvvm Light working together. I put such an example together and made it available on the “DevForce Resource Center” (DRC); the Mvvm Light example page is here.

      I provide code that shows three ways to start a DevForce + Mvvm Light application and one “Hello World” example.

      Blend is a critical part of the story. “Blendability” is central to the Mvvm Light philosophy … and I agree. The working example view was written entirely in Blend.

      Expect more from me soon on developing with Blend.

      Meanwhile, here’s your launch point for Mvvm Light with DevForce.


      Friday, August 20, 2010

      DevForce “Blends”

      We are seeing an increasing interest among developers in using Blend to design application views. I think this is great. Silverlight and WPF are great technologies for building productive business applications. But you can’t be as productive and effective as you should be if you only work in XAML. You need the tools.

      And Blend 4 is an incredibly great tool. I say this even though I’m only competent to use about $1.30 of it.

      All of this is preface to a forum question we received:

      I’m attempting to mock data at *design* time. … Has anyone ever managed to get this to work? …Using DF to avoid creating dozens of mock repositories on a large project? Now that would be a coup!

      My answer follows:

      We are well on our way to making DevForce play well with Blend. Actually, we probably are THERE. But we haven't documented it well and I don't feel that I'm particularly close to anything worthy of calling a "Best Practice." Let's say I have some "ok" practices :-/

      Here's visual evidence of an existence proof: yes, you truly can use a DevForce EntityManager and entities at design time:

      ComboBox Sample in Blend

      This example comes from my slight re-design of the "Simple ComboBox in Silverlight" sample code.

      [Aside: the existing sample is on our web site now. The revised one will be released with our forthcoming "DevForce Cookbook." Look for the Cookbook to arrive within a matter of weeks.]

      The original point of the sample was to demonstrate how to wire up a ComboBox to DevForce entities AND bind that ComboBox to other DevForce entities.

      The previous version looked bloody awful; this one just looks bad.

      However, it's beautiful for the purpose of this forum post! You can plainly see employee, "Ima", in on the Blend art board. "Ima" does not exist in the Northwind tutorial database. She's a fake Employee, ginned up in a MainPageDesignViewModel that derives from the production MainPageViewModel. The view doesn't know; it's just binding to a ViewModel (VM).

      All of the fakery happens in the design VM's constructor, shown here:

          public MainPageDesignViewModel() {

      EntityManager = new NorthwindManager(false);
      EntityManager.DefaultQueryStrategy = QueryStrategy.CacheOnly;

      var designEmp = new Employee {
      EmployeeID = 1, FirstName = "Ima", LastName = "Blast", ReportsToEmployeeID = 2,
      var designManagerEmp = new Employee {
      EmployeeID = 2, FirstName = "Slim", LastName = "Ornun", ReportsToEmployeeID = null,


      PotentialManagers = new List<Employee> { designManagerEmp };
      CurrentEmployee = designEmp;
      Messages.Add("We're in DesignTime now !!!");

      The design version of the VM (a) creates two fake employess (Ima and her boss, Slim), (b) creates a disconnected, cache-only EntityManager (EM) - to ensure there is no attempt to talk to the database, and (c) adds the two employees to that EM. Because both fakes are in cache, DevForce can implement the navigation between Ima and Slim via the "Manager" property. I neglected to show this in the ComboBox but you can see it in the message which reads "Ima Blase whose manager is Slim Ornun".

      It is only a few short hops from here to doing the cache-to-file trick that you want. In fact, I've done what you want on a different project and we'll provide a similar, smaller example in one of the Cookbook recipes .... although perhaps not in the first Cookbook edition. Trust me, it works great.

      To be precise, it worked great for test runs of your application that you wanted to be fast and free of the need to talk to a database. It didn't work in Blend (although for different reasons than Jason cites).

      Until DF 2010 v. 6.0.5, it simply wasn't viable to use DF entities in Cider (Visual Studio visual designer) or Blend because we required that the Desktop (aka Web aka "Full DotNet") model carry the same assembly name as the Silverlight model. No problem for the CLR but most tools, including design tools, just choked.

      Using the same assembly name is no longer required. In fact, is heavily discouraged.

      Now this ComboBox sample dates from 6.0.2 (I think) ... certainly before we got rid of the assembly name restriction. It did not Blend.

      All I had to do was some assembly renaming plus clean and re-build. The view popped right up in Cider and Blend.

      There was no data visualization though. Just a bunch of weird boxes. The XAML looked ok ... obviously it ran ok ... but it made no sense rendered in Cider or Blend.

      A little dragging around was helpful but I still wanted to see sample data.

      So I refactored the ViewModel to facilitate a derived, design-time version of that ViewModel and, presto, that's how I was able to get the layout you see in the image above.

      [While I was at it, I replaced the button click wiring with Blend Behaviors ... and deleted the entire custom code-behind]

      You can do the same things to your application, or wait for the Cookbook if you want to see the details.

      As I mentioned, the cache-to-file variation is not far off. That will take some explanation, however, as there are a few places you can stumble on the way ... as you discovered. Please hang in there.

      Monday, August 9, 2010

      DevForce in the Cloud: Prism Explorer

      On our second flight to Azure, we deployed our “Prism Explorer” sample application. The address is the same as before:


      The UI dates from Silverlight 2 (our first Silverlight release). We’ve ported it forward to DevForce 2010 and Silverlight 4 but haven’t touched the XAML. Pretty ugly but it gets the point across. Some day, some day …

      Prism Explorer, aside from showing that DevForce and Prism play nice, demonstrates a variety of DevForce features such as:

      • Arbitrarily complex queries, including anonymous projections
      • Add, delete (enabled for Customer only in this case), and save
      • Integrated validation (e.g., Customer requires a city)
      • Lazy and eager load of related entities
      • Online and offline (toggle “Connect” button)
      • Save and restore entities to isolated storage file
      • Out of browser

      Here it is, running Out-of-Browser, after querying for “Customers (and their orders) starting with C”


      Here’s another moment in the life of the UI – queried for all Employees and clicked Edit button on good ole Nancy Davolio:


      I shot video of Kim and me deploying it. Raw footage is 40 minutes, much of that watching it build on my stressed-out notebook (Camtasia and VS competing for cycles). Hope to get it to 20 minutes after cutting out the dross.

      Still, I was amazed to get this done in 50 minutes of clock time (paused video 10 minutes while publishing to Azure staging ). That includes commentary, fumbling, and miscues.

      More on all of that in my next post.

      Friday, August 6, 2010

      DevForce in the Cloud: 1st Flight

      Our first Azure DevForce “application” debuted today.


      Sure it’s just Northwind customers in an un-styled, read-only Silverlight DataGrid. Kind of like putting a monkey in orbit. But it’s an important step for IdeaBlade and DevForce … and I’m feeling a wee bit proud.

      Behind that simple (simplistic?) exterior are DevForce 2010, SQL Azure, Windows Azure, Silverlight 4, Entity Framework v.4, and .NET 4. That really is EF 4 running in the cloud, not on the client as it is in most Azure demonstrations. That really is the DevForce middle tier “BOS” in the cloud and a DevForce Silverlight client executing in your browser.

      We’ll probably have taken this sample down by the time you read this post. But who knows; if you’re quick, you may still be able to catch it at

      Kudos to Kim Johnson, our ace senior architect / developer who made it happen. Thanks to Microsoft’s Developer Evangelist Bruno Terkaly who first showed us EF 4 in Azure when there were no other published examples.

      I’ll be talking about DevForce and Azure much more as our “DevForce in the Cloud” initiative evolves. It’s clearly past the “pipe dream” phase and I anticipate acceleration in the weeks ahead.

      Those of you who’ve been wondering if we’d get there (Hi Phil!) or whether to "play it safe" and build your own datacenter (really?) … wonder no more!

      ObservableCollection / DataGrid Memory Leaks

      Ran into a BEAR of a memory leak today. Or, rather, one of our customer’s did … while investigating our PrismExplorer sample that demonstrates DevForce 2010 and Prism v.2.2 playing well together.

      This post is a re-post of my exchange on our IdeaBlade Forum. I figure it’s worth repeating here should you run into it and not think to look on our forum.

      The lesson, I hasten to add, is for all Silverlight developers. DevForce entities are not the cause. If you bind a Silverlight DataGrid to objects that implement INotifyPropertyChanged, this post is for you.

      The takeaway is this: Don't reassign the ObservableCollection<T> bound to an ItemsSource; repopulate it!

      An now … the story. First, the customer reports a problem

      When ever I bind a datagrid or listbox via a ViewModel to an ObservableCollection(results) in a Callback method from a simple query … I end up consuming memory which will never be released, … not after disposing of the EntityManger, View, Viewmodel, etc. This behavior can be reproduced in your Prism Explorer when querying Customers, Orders, and back a few times. You can see this in Performance Monitor (perfmon) under process->private bytes where the count keeps climbing up.

      Here is my response:

      You are (mostly) correct and oh ... how awful!

      As I demonstrate below, memory is recovered when you clear the EntityManager. It would be recovered if you disposed of the EntityManager itself. I'm not sure why you didn't see these effects.

      However, you are absolutely right that something horrible is happening. I spent much of the day researching it.

      The only good part of the story is that it has nothing to do with DevForce. The cause is something in Silverlight, probably in the Silverlight DataGrid.

      I will explain but it will be a bit of a journey leading ... ultimately ... to a sad-but-necessary workaround.

      If you want to skip the journey and go right to the destination, the lesson for your code is:

      Don't reassign the ObservableCollection<T> bound to an ItemsSource; repopulate it!

      And now ... my sad tale ...

      The main "ModelExplorer" view binds a Silverlight DataGrid.ItemsSource to the QueryResults property of the supporting ModelExplorerViewModel (the VM).

      "QueryResults" is defined as IList but is always an ObservableCollection<T> in practice (henceforth written as "OC<T>").

      The problem starts with the repeated resetting of the QueryResults in the ModelExplorerViewModel after every query.

      A peculiarity of PrismExplorer (PE) is that the main "ModelExplorer" view could be asked to display objects of any type in the DataGrid. That's its purpose as a demo screen. Your grids typically only show one kind of object. But PE must work with arbitrary query result types.

      Because those types change, the OC<T> must change to match type.

      The obvious thing to do was craft a new OC<T> after every query ... one designed for the query results type, assign that new OC to the QueryResults, and raise PropertyChanged on "QueryResults". The DataGrid dutifully hears the call and refreshes its display.

      Unfortunately, it consumes an extra 300K every single time. "300K" is not a misprint.

      Here's the code with the garbage collection call and logging (aside: we now inject ILoggerFacade into the VM now so that we can write to the Visual Studio Output window).

          public IList QueryResults {
      get { return _queryResults; }
      set {
      _queryResults = value;

      Log("=== Total Memory = " + GC.GetTotalMemory(true));

      RaisePropertyChanged("QueryResults", "QueryResultsCount");

      If you add this instrumentation, query for "All Customers", and click the "Query" button repeatedly, the Output window will show that your memory consumption is climbing ~300K each time. Here are actual measurement.

      Prism Explorer: "=== Total Memory = 3406212";
      Prism Explorer: "=== Total Memory = 3914916";
      Prism Explorer: "=== Total Memory = 4336668";
      Prism Explorer: "=== Total Memory = 4756884";
      Prism Explorer: "=== Total Memory = 5177356";
      Prism Explorer: "=== Total Memory = 5782900";
      Prism Explorer: "=== Total Memory = 6202860";
      Prism Explorer: "=== Total Memory = 6616220";
      // Cleared the EntityManager
      Prism Explorer: "=== Total Memory = 3655320";
      Prism Explorer: "=== Total Memory = 4076292";
      Prism Explorer: "=== Total Memory = 4498300";
      Prism Explorer: "=== Total Memory = 4918260";
      Prism Explorer: "=== Total Memory = 5358912";
      // Cleared the EntityManager
      Prism Explorer: "=== Total Memory = 3655384";

      Note that DevForce isn't going anywhere. You are issuing the same query repeatedly and DevForce satisfies it from the EntityManager cache. However, the PE ViewModel is building a new OC<Customer> each time and reassigning QueryResults. The DataGrid is rebinding the ItemsSource to the new OC<Customer> each time ... and chewing up memory each time.

      If we comment out "_queryResult = value", DevForce and PE will continue to do their things ... DevForce may query the database or satisfy from cache if it can. PE will always build a new OC<T>, assign QueryResults with that OC<T>, raise PropertyChanged, stimulate the DataGrid to rebind to the QueryResults. Exactly the same code paths.

      The only programmatic difference is that QueryResults always returns the exact same (empty) object.

      The memory consumption goes flat ... as it should.

      Of course it climbs modestly when you issue a query that fetches new data; that is to be expected. Press "Clear" to clear the EntityManager cache and memory is recovered.

      This is proof enough for me that the memory leak is in Silverlight ... perhaps in the Silverlight DataGrid. Our entities are involved in some way ... that's why clearing the EntityManager cache allows the GC to recover memory. But the DataGrid is clearly chewing up memory at a fast clip without our adding any new entities to memory.

      What could possibly take 300k? The entity data involved are miniscule (it's Northwind! 7 Employees ~90 customers). All entities combined do not weigh 300K.

      The memory consumption grows by 300K when there are no new entities. Evidently Silverlight or OC is in a deadly embrace with the entities that prevents garbage collection (there are events involved). But even if so ... the numbers are staggering. We aren't adding 300K of new data each time we click the button. You can't write enough event handlers to consume 300K. The cost of an OC isn't 300K.

      In my research, I tripped over an old WPF blog post (can't find it now) that said something about WPF creating completely new data and control templates for each OC. Now THAT is a fast way to burn memory. I'm betting that Silverlight is creating and caching a complete visual representation of the DataGrid and the associated entities each time I reset the ItemsSource with a new OC<T>!

      I tried a number of things to shake up the binding ... anything to make it let go of whatever it was holding:

      • clear the _queryResults ( _queryResults.Clear() ) before re-assigning it with the new OC

      • clear the _queryResults and set it null before re-assigning it with the new OC

      • clear the _queryResults, set it null, raise PropertyChanged ... then assign with new OC

      None of these attempts worked. Only pressing "Clear" worked.

      What to do? The obvious answer is reuse the OC ... and that is the lesson for your application: Don't reassign the ItemsSource; repopulate it!

      Of course OC<T> requires strongly typed contents. I tried OC<object> with the intention of simply clearing and refilling it with new results after each query. That executes without error. But it doesn't show anything on screen either ... pretty useless :-).

      It actually worked if I use List<T> instead of OC<T>. But then I wouldn't have the benefits of ICollectionPropertyChanged and I'd have to manage adds, removals, clears by hand. Yuck.

      The WorkAround

      As a last resort, on each pass I check to see if the type of the fresh results matches the element type of the OC. If it does, I can re-populate the OC. If it does not match, I have to replace the ItemsSource with the new OC ... and pay the 300K tax.

      If you always query for the same type, you'll be fine. You can change the query itself - there are numerous Customer and Employee queries in PE - without paying the tax. It's changing the result type that incurs the tax.

      I tried to be clever and keep a dictionary of previously used OC types. If I was querying customers, I'd pull out the OC<Customer>; if I was querying employees, I'd pull out the OC<Employee>. That didn't help. The DataGrid doesn't remember OCs that it has seen before. Re-using old OCs didn't change its penchant for devouring another 300K

      So all I can do is slow it down. If PE starts to blow, you can "Clear" the EntityManager and it will recover.

      Here's the revised code (which will appear in the next PE release, minus the GC & Log calls)

          public IList QueryResults {
      get { return _queryResults; }
      set {


      Log("=== Total Memory = " + GC.GetTotalMemory(true));

      RaisePropertyChanged("QueryResults", "QueryResultsCount");

      private void ResetQueryResults(IList results) {

      if (null != _queryResults) _queryResults.Clear();
      if (null == results 0 == results.Count) return;

      var resultsType = TypeHelper.GetItemType(results);

      if (_queryResultsElementType == resultsType) {
      // Same results collection type; can refill it
      foreach (var item in results) {
      } else {
      _queryResults = results;
      _queryResultsElementType = resultsType;

      private Type _queryResultsElementType;

      Here are memory reports:

      // Query for All Customers

      Prism Explorer: "=== Total Memory = 3411896"
      Prism Explorer: "=== Total Memory = 3425356"
      Prism Explorer: "=== Total Memory = 3416064"
      Prism Explorer: "=== Total Memory = 3416076"
      Prism Explorer: "=== Total Memory = 3416076"
      Prism Explorer: "=== Total Memory = 3429460"
      Prism Explorer: "=== Total Memory = 3416076"
      Prism Explorer: "=== Total Memory = 3415020"
      // All Employees
      Prism Explorer: "=== Total Memory = 4203344"
      Prism Explorer: "=== Total Memory = 4212964"
      Prism Explorer: "=== Total Memory = 4213000"
      Prism Explorer: "=== Total Memory = 4213000"
      Prism Explorer: "=== Total Memory = 4213000"
      // Clear Entity Cache ... followed by All Employees
      Prism Explorer: "=== Total Memory = 3706416"
      Prism Explorer: "=== Total Memory = 3588660"
      Prism Explorer: "=== Total Memory = 3593996"
      // First Employee
      Prism Explorer: "=== Total Memory = 3590928"
      Prism Explorer: "=== Total Memory = 3604372"
      Prism Explorer: "=== Total Memory = 3589676"
      // Employees named Smith (there are none)
      Prism Explorer: "=== Total Memory = 3605584"

      // All Employees (again)

      Prism Explorer: "=== Total Memory = 3757472"
      Prism Explorer: "=== Total Memory = 3762120"
      Prism Explorer: "=== Total Memory = 3770336"
      Prism Explorer: "=== Total Memory = 3762144"

      Friday, April 30, 2010

      Context for Comparing DevForce, CSLA, and RIA Services

      I recently posted on some important differences between DevForce and RIA Services. Someone posted a comment to the effect that DevForce and CSLA seem to be the same and invited me to comment.

      I see the similarities between DevForce and RIA Services. I don’t think DevForce and CSLA are alike at all. Why would someone suggest that they are?

      That got me thinking and lead to this post which reframes the question.

      It first establishes what we have in common … and how to decide quickly if you should consider any of us … or none of us … for your application project.

      Then it articulates fundamental criteria for comparing the three.

      Important: These criteria are not evaluative. They are as neutral as I can make them. I feel pretty confident in that neutrality because, as I apply them to the three products, I can not tell which one of them is “better”. They help me organize my thoughts, not decide which one is “right.”

      Let's start with the what we have in common.

      DevForce, CSLA, and RIA Services target the same problem: building distributed business applications from end to end, server to client.

      If you don't think you have this problem, none of us are right for you.

      We offer .NET-only products. RIA Services is limited today to Silverlight applications; DevForce and CSLA support most .NET client technologies (I don't think any of us are ready for WP7 .. yet. CSLA may work on the CE; we do not). Your required server and client operating environments may make the choice for you.

      We all have the same presumption of a relational database as the primary backing store. Sure we can also persist to other backing stores. But these alternatives appear in supporting roles if they appear at all. None of us are your best choice for building applications that primarily access data through messaging services or persist to one of the NoSql schema-less data stores.

      We all attempt to solve your application problem within some flavor of "mobile business objects" paradigm. If you summarily reject a "mobile business object" solution on principle, none of us are right for you.

      Finally, we are all framework products. We're not application generators. If you want to drag-and-drop your way to a finished product, we're not for you. If you reject 3rd party frameworks, we are not right for you either.

      With me still? Because now we are ready to differentiate the three products.

      You have looked at the problem and you've chosen to solve it by allocating some responsibilities to a framework, reserving others for yourself in the expectation that you will be writing custom application code.

      Every framework is opinionated. Each says:

      • We will be responsible for these tasks (the A-list).

      • You will write custom code for these other tasks (the B-list).

      • Our architecture and recommend development practices pretty much prescribe that you will write your custom code in manner C.

      You look at these opinions and ask yourself

      • Do I want the framework to do the things on the A-list?

      • Do I want to write code for the things on the B-list?

      • Do I want to develop in manner C?

      • How productive will I be if I adopt this framework?  How quickly can I write quality B-list code when I adopt manner C?

      • What items on the A-list do I really have to do myself? Can I take these particular tasks away from the framework with acceptable ease and still, in the main, be using the framework the way it was intended?

      • I wish some of the items on the B-list were handled by the framework. What will it take for me to write them myself or acquire them from someone else?

      • I don't care about some of the items on the A-list; do these items get in my way and if so, will that be a serious problem?

      • Do we have the skills and development culture to use this framework effectively? If not, can we and should we acquire those skills?

      • How do these factors collectively influence my development timeline? Do I have a deadline? If so can I reasonably expect to hit the deadline with the resources I have using this framework?

      You will also consider some “non-functional” factors

      • Product quality and maturity
      • Access to source code
      • Support
      • Influence on roadmap and repairs
      • Product release schedule
      • Community (resources, training, etc.)
      • Company stability

      I have conspicuously omitted one factor: license costs. CSLA and RIA Services have no license costs. DevForce does. Why doesn’t that matter?

      It doesn’t matter because you’re building a custom application that you’ll be living with for years. A few thousand dollars of licensing fees are irrelevant … they are rounding error … compared to the application investment you’re about to make and the risks you are about to assume.

      If this is not blindingly obvious to you, you shouldn’t be making this decision. You simply don’t have the requisite business acumen to make the right choice.

      When you dissect the products according to these criteria – which you’ve refined and weighted to suit your business environment  and requirements – the differences among CSLA, DevForce, and RIA Services will stand out in sharp relief.  You will have a foundation for choosing among them.

      I said the differences will be stark; I didn’t say that the choice will be easy. Even within the same organization people will weigh some differences more heavily than others.

      You will at least have arranged matters so you can see more clearly what you’re arguing about.

      Wednesday, April 28, 2010

      DevForce Or RIA Services?

      I’m thrilled RIA Services is out at last.

      Developers who are familiar with Forms-over-Data, end-to-end, business application development at last have a Microsoft-sanctioned approach to building such applications in Silverlight.

      They’re less inclined to roll-their own data management solution and more inclined to let someone else handle the plumbing.

      That choice is not without problems. It’s unnerving to hand the keys over to a framework and say “you drive.” But let’s face it, your home-brew solution is just another framework too. It may be yours … which makes you feel all gnarly and in control. But it’s still a framework that someone is going to have to document, train, maintain, support, and grow … at the probable expense of delivering the end product demanded by the customer.

      RIA Services has made it OK to delegate these challenging and time-wasting aspects of the application to a third party.

      For me, the usual conversation has shifted from “Why do I need something like DevForce?” to “Why DevForce instead of  RIA Services?”

      Here’s how someone put that question on the RIA Services Forum.

      DevForce or WCF RIA Services? Both seem to do more or less the same data abstraction for Silverlight, but which would be the better route to go in the end? The price tag for me is the winner with WCF RIA services, but this is not always the right choice. Any thoughts?

      Colin Blair, MVP and RIA Services aficionado, invited me to respond to that forum post. Which I was happy to do :-).

      You could read it there. But I’ll spare you the trip and re-post my response here.

      I have much more to add… and I’ll elaborate in the coming weeks and months. Meanwhile, it’s a start.


      Yes, RIA Services and DevForce share a common perspective: end-to-end application development, programming against a rich entity model backed (typically) by relational data with validation, concurrency, security, change management, unit-of-work rolled in.

      DevForce has been in commercial release since 2002 (long before Silverlight) so it's been dipped rather thoroughly in the acid bath of real world experience.

      It supports both 2-tier and n-tier applications (a config change) and all the typical .NET client technologies: Windows Forms, WPF, Silverlight, ASP Web Forms, ASP MVC. You can write one code base and use it across all of them ... not that that is always a great idea. We have versions for .NET 2.0, 3.5 and 4.0.

      Let's assume, however, that you are only interested in Silverlight and you don't care about product maturity, track record, or any of that.

      If it seems that DevForce and RIA Services are similar ... that's intentional. We have a common perspective and we want DevForce to align with RIA Services APIs and techniques as much as possible ... so that it's easy to move between the two communities.

      But DevForce and RIA Services are not clones. We do many things differently and offer capabilities beyond the RIA Services baseline.

      Our customers often cite some of the following dozen DevForce differences as their reasons for choosing DevForce:

      1) Same model on server and client. The code you write on the server is the same as the code on the client (unless and except where you don't want it to be). Open the Employee class on either side ... it's identical. The physical class file resides on one side (typically a server, full .NET project) and you have a Silverlight model assembly that links to that file. Compilation produces different assemblies (.NET and Silverlight) whose class names, structures, and logic are effectively the same.

      2) No code generation magic.  We don't touch your code. We don't generate client code. No surprises.

      3) Most DevForce applications use Entity Framework for Object Relational Mapping (ORM) and persistence operation (query, insert, update, delete).

      DevForce generates its own (partial) classes from EF's EDMX using T4 templates; we don't need, use, or generate EF's own classes.

      Our classes are serializable and designed to support RIA scenarios. We inscribe the UI-hint attributes (e.g., Display) and the obvious validation attributes (e.g., Required) into the generated classes. No separate metadata class files needed (keep reading)

      4) You can override our code generation to introduce your own behaviors. You could take over the entire template but it's much easier to override one of the many code generation methods that target the moment of interest to you (e.g., property generation).

      5) No service method pollution.  In RIA Services you have CRUD methods for each type in your model. There could be 400 methods in a 100 entity model. We don't generate CRUD methods; like WCF Data Services, we manage CRUD operations dynamically. Of course you CAN write arbitrary service methods if you wish. You can intercept any Query to inspect, limit, adjust the query. You can intercept any Save to inspect, reject, add/subtract/modify the entities in the change set, or perform arbitrary operations (custom logging and auditing).

      6) Iterative Development: In demos, you build your model and you're done. In reality, you will add, remove, and rename your properties, entities, and the relationships among them. over the long course of your application's lifespan. Such adjustments are trivial with EF-backed models; update the EF model, compile, and run.

      Ok ... maybe you should test too and you made these changes because you wanted to introduce new capabilities. The point is that you'll program to those business concerns; you won't be updating a domain service file and fixing up satellite, entity-related class files.

      7) Client-side LINQ. DevForce supports client-side composition of any LINQ to Entities query, including projections of all kinds, projections into anonymous types, aggregations, grouping and ordering, includes, polymorphic queries (query on a base type). There is NO query you have to compose on the server in a "domain service" method. You don't add OrderBy clauses on server query methods. It is almost unheard of for a DevForce application to have a server-side query method.

      8) Client-side caching. Query results are cached as are entities you create, modify, delete ... and have not yet saved. RIA Services does this too.

      But DevForce applies your LINQ queries BOTH to the server store and to the cache. Suppose you have queried for all Northwind employees; you change "Nancy Davolio" to "Sally Davolio" and you add a new employee named "Sam". Meanwhile, another user has saved a new employee named "Sherry". What is the result of a query for employees with first name beginning "S"? The DevForce answer includes "Sally (formerly Nancy)", "Sam" and "Sherry".

      You can tell DevForce to query ONLY the cache or ONLY the server ... as appropriate.

      It's trivial (and recommended) in DevForce for your Silverlight application to prepare the cache with entities you need for a particular user scenario as you enter that workflow. You then would default subsequent query execution to "CacheOnly", and "party on" as if you had an in-memory database. Yes, you can still make remote queries and asynchronously refresh all or part of the cache at will.

      The key benefit: you can easily program the user experience in the synchronous style familiar to most business application developers and still exploit the responsiveness of asynchronous data access ... using the same queries.

      9) Productivity and Testability. You don't need a database or server to build and test your application. You can populate the DevForce entity cache with test entities - entire object graphs - and run disconnected. You can serialize the cache to file (e.g., Isolated Storage) - in a single method - and restore that cache at will. I often build a development data cache file, include it as a resource, and launch my application "in test mode"; the cache fills with the dev data rather than having to hit the server, and I'm running with no web server at all. I can make and explore UI changes in a fraction of the time it would take if I had to spin up Entity Framework and a server. I can work with colleagues far away who don't have Entity Framework or the database ... because there is no dependence at all.

      10) DevForce entity properties are implemented with "property interceptors" that enable you to inject custom behavior into the getters and setter. Without touching the Employee class I can add logic to automatically mask the Social Security number  ... unless the employee is the current user or the user is an HR admin. I could inject logic into a setter to force values to upper case. I have complete, fine-grained control of the DevForce generated properties before and after the actual value access or mutation.

      11) DevForce validation supports the same DataAnnotation validation attributes as RIA Services in addition to our own (richer) validation attributes. But you're not limited to attributes. You can add validation rules programmatically to the class and we'll discover them. You can access the list of validation rules for any type and manipulate that list, removing existing rules and adding other rules ... perhaps customer-specific rules determined by metadata. You can do this with logic entirely outside the entity class. And DevForce validation can be applied to any object, not just entities.

      12) Navigation properties (Order.OrderDetails, Order.Customer) to related entities work even if the related entities are not in cache. DevForce fetches them asynchronously ... and can notify you when the data arrive. I would be wary of multiple, hidden trips to the database (the N+1 problem with lazy loading); you should consider eagerly loading these entities instead. But lazy loading has its place. Of course you can disable lazy loading of any property at any time.

      You can find out more for yourself by visiting our web site, or write to me at

      Friday, April 2, 2010

      DevForce Extensibility With MEF InheritedExport

      We’ve offered extensibility points in Our DevForce product since the beginning of the century.

      Our customers wrote classes that implemented certain of our interfaces. We discovered those classes by examining assemblies named in a configuration file (app.config or web.config). We had our own probing and injection logic because market forces precluded use of a 3rd party IoC.

      In DevForce 2010 we’ve switched to the Microsoft Managed Extensibility Framework (MEF) which is baked into the .NET 4 platform.

      How hard was that? It wasn’t a big deal. Mostly we had to figure out how it worked and find the best approach for us. Which is the point of this post.

      Because we almost made a mistake. We didn’t know about MEF’s InheritedExportAttribute.

      DevForce Extensibility

      Let me set the stage.

      Suppose you want to alter DevForce default behavior by supplying your own way of doing something. Maybe you want to supply a custom “LoginManager” to authenticate users. Maybe you want to supply a class that intercepts all attempts to save data to the database … so you can confirm the user’s right to save or impose some extra server-side validation or add audit records … whatever.

      Heretofore, you wrote a MyLoginManager that inherited from IEntityLoginManager and stuffed it in a server-deployed assembly; call it "MyServerStuff". You next identified “MyServerStuff.dll” as a probe assembly in your web.config. We’d look there for a class implementing IEntityLoginManager and, upon finding yours, would instantiate and use your class instead of our default class. Similarly, you wrote a MyEntityServerSaving class that inherited from IEntityServerSaving and we’d find it too.

      In MEF, MyLoginManager and MyEntityServerSaving are “parts”. They are parts that you “export” for DevForce to “import”.

      The DevForce 2010 difference: we let MEF do the finding and creation of your types instead of doing that ourselves.

      Our Initial Mistake

      In a beautiful world, you – the developer of MyLoginManager and MyEntityServerSaving – don’t change a thing. Your classes just work.

      Actually, it’s better than that. You can throw away the <probeAssembly> tags in the web.config and the app.config. That kruft was a repeated source of confusion and heartache for our customers. It’s gone. No <probeAssembly> needed if you drop your assembly on the server in the \bin directory.

      We should have done that long ago. MEF made it obvious.

      BUT … it looked like it wouldn’t be quite this easy. How would MEF know to import your MyLoginManager and MyEntityServerSaving?

      We couldn’t figure that out. In vanilla MEF, you attach an Export attribute to a component that you want others to import. It seemed you’d have to decorate your custom classes with these attributes like this.

        public class MyLoginManager : IEntityLoginManager { // your code }

      Ugh. Why impose this burden on the poor developer? How many support calls would we field that ran something like this?

      “Sir? DevForce didn’t find your class? Please open Visual Studio … now look at the class definition. Does it have an Export attribute? Yes an “Export” attribute. What? Oh yeah you’ll need an assembly reference and a using clause too. Sure, I’ll hold why you build, redeploy and run it …”


      Fortunately, I know how to complain. I wrote a “WTF” email to Glenn who graciously replied as follows:

      You might want to look into InheritedExports. If you are not using metadata you can put an [InheritedExport] on an interface which will automatically apply to the exporter.

      In other words….

        public interface IFoo {}

        public class Foo : IFoo { ...}

      Foo above automatically exports IFoo since the decoration is on the interface. There are some issues if you are doing this combined with metadata.

      How about that!

      We added “[InheritedExport]” to all of our extensibility interfaces. Now our customer’s existing custom classes are discovered and work as they did before without modification. No attribute needed.

      What if the extensibility point is a base class instead of an interface? That works too. Check this out. In DevForce, we have an EntityServerSaveInterceptor class that intercepts server side saves. It does some work by default … work that you can extend.

      Here’s its new MEF’ed signature in DevForce 2010:

          [InheritedExport( typeof(EntityServerSaveInterceptor) )]
          [DefaultExport( typeof(EntityServerSaveInterceptor) )]
          public class EntityServerSaveInterceptor {

      Note the “DefaultExport”. That tells MEF to import an instance of this class if you don’t supply your own.

      Customers can subclass our default version just as they did before:

          public class MyEntityServerSaveInterceptor : EntityServerSaveInterceptor {

              protected override bool ClientCanSave(Type type) { … }


      They can’t MEF up.

      Is MEF Legal?

      You don’t know about MEF? Where have you been? How could you have missed Glenn “Mr. MEF” Block; the man is everywhere – print, stage, and screen – talking up the MEF magic.

      You can read about MEF here and here and here and all over the place. Mike Taulty, who is excellent on any subject, produced some superb MEF screen casts. The once-obscure Dependency Injection technique has gone mainstream with MEF and will be arriving soon in a code base near you. You’ve probably been doing something like it for years and didn’t know it.

      Thursday, April 1, 2010

      DevForce / UFC Gym Bling On Silverlight TV

      We had way too much fun at MIX 2010 in Las Vegas last month. John Papa captured the flavor in a Silverlight TV interview with me featuring the UFC Gym Kiosk.

      Watch the episode online by clicking this link or clicking the mage below:

      3-31-2010 11-51-04 PM

      My buds channeled their inner Elvis (mosaic courtesy John Papa):

      Clockwise from top: Brad Abrams, moi, Karen Corby, Dan Wahlin, John Papa, Tim Heuer

      This being April 1st and the garb verging on outrageous, you’re excused for doubting the seriousness of the interview.

      In fact, we explored many substantive issues:

      And I think the demo showed well what you can do in two weeks by concentrating on the User Experience (UX) and leaving the plumbing to us.

      Who says business can’t be fun?   We had a blast!   Enjoy.

      Wednesday, March 31, 2010

      Of Tailors and Tooling (rant)

      Daniel asks a tailor to make him a suit. The tailor measures him and says “come back in three days.”

      Daniel returns to try on the suit. “The left sleeve is too short” he complains. The tailor says “Raise your right shoulder and drop the left shoulder and you’ll look great.” Daniel does and, sure enough, the two sleeves meet properly at the wrist.

      The left pant leg is too long” cries Daniel. “No problem” says the tailor. “Lift your left hip and walk on your toes.” Sure enough, both pant legs break beautifully just above the ankles.

      Daniel pays the tailor and ambles out to the street wearing his new suit. Another man approaches him and exclaims “Wow, great suit! Who’s your tailor?”. Daniel beams and points to the tailor shop. “He must be a terrific tailor,” says the man, “to be able to fit a cripple like you!

      I’m feeling like Daniel a lot lately. A number of us have been exploring implementation patterns for MVVM in complex, composite business applications. Just as we start getting somewhere promising … someone stops us short and says:

      You can’t do that because it doesn’t work in Blend.

      Let me be clear. I think Blend is grand and am learning to appreciate its power. I desperately want to facilitate the best possible UX. I know I can’t design the visuals worth a damn. I realize the people who can are not programmers and shouldn’t be asked to become programmers. I get it. I will do what it takes to make Blendable Views … including adjusting my posture.

      But I’m not happy with show-stopper arguments like “It won’t work in Blend.” That may be the reality today but it need not be my future.

      We should be honest about the consequences of saying “it won’t work in Blend”. Make no mistake, we’re twisting and contorting our architectures to satisfy the present state of the tooling.

      Worse, we’re encouraging the tailor!

      Sometimes I believe he thinks it’s a good thing for us to slouch and droop uncomfortably down the street. He actually thinks it’s a good thing to build View first, to inscribe code in the XAML, to block access to design-time APIs, to resort to Behaviors for simple programming tasks. He can’t believe I need to inject dependencies in the ViewModel … perhaps because that means he’d have to confront his own inadequacies.

      I should get over it. Yet my hackles go up when I detect that smug, dismissive tone.

      Hey, if you have to say “it won’t Blend” that’s an admission of failure. It means you’re not where you should be. I can deal with that. But stop sounding triumphant … as if what I want to do is stupid because it won’t Blend.

      Yes, please make the tooling great for the designer. But the developer is the customer too … never forget that. The tooling should change to suit me … not the other way around.



      Sunday, March 21, 2010

      Commands as XAML Resources

      I’m watching Nikhil Kothari’s talk at MIX 2010 while I write. As with all things Nikhil, you owe it to yourself to take a look.
      The talk is nominally about developing with WCF RIA Services. It’s really about programming style. Most RIA Services demos are 100% drag-and-drop. You might think that’s the only way or the preferred way to write a RIA Services application.
      Not so!  … and Nikhil is determined to show a different path. A standing ovation from me for bucking that trend … while keeping it all accessible to a general development audience.
      I particularly liked the moment around the 31st minute when he uses SketchFlow to show how the View relates to a ViewModel.
      Scoot ahead to 35:40 and you’ll find Nikhil wiring ViewModel actions to View buttons via Commands that he’s instantiated as resources in the View.
      I’m intrigued by this approach even if I’m not completely sold on it.

      The Problem

      Silverlight lacks the means to directly bind view events (e.g., button clicks) to ViewModel actions (e.g., “Load Books”). That omission has spurred a variety of solutions: event handlers in code-behind, ViewModel commands wired by attached behaviors, and auto-wire-by-convention (Caliburn-style) to name a few.
      Nikhil has found another way to do it. We can leverage data binding and declare the hook-up in XAML using a simple resource rather than the more obscure behavior. It is quite seductive. Let me elaborate.

      Button Binding

      The button has a Command property which can be bound to an implementation of ICommand.
      In MVVM we strive to bind the View to members of the ViewModel. It seems natural for the ViewModel to expose ICommand implementations that we can bind to buttons in the View. I’ve done this myself … I hate to admit.
      Picking up on Nikhil’s example, our BookViewModel could present a “LoadBooksCommand” property that delivers an ICommand wrapper around the VM’s private “CanLoadBooks” and “LoadBooks” methods.
      To support this we write code in the ViewModel like so:
          private ICommand _loadBooksCommand = new Command(LoadBooks, CanLoadBooks);
          public ICommand LoadBooksCommand { get { return _loadBooksCommand; } } 
      Yuck. The ViewModel author is interested in “LoadBooks” and “CanLoadBooks”. These are the meat of the matter.
      The ICommand is a View artifact that has crept into the ViewModel. The Command(…) isn’t even an instance of a .NET class; we have to get it as a helper from some framework ... Prism perhaps. The whole business is distracting kruft and a PITA.
      Many of us just put up with it, writing those command pairs over and over.
      Nikhil says “Let’s not pollute the ViewModel this way. Let’s refactor the Command back to the view where it belongs”. Our ViewModel will expose “CanLoadBooks” and “LoadBook”s publically just as we would any bindable property. No more ICommand nonsense.

      Command Resources

      In his SilverlightFx framework he’s defined a “Command” class that we can instantiate in XAML.
      We create Command instances as resources in our view as follows:
          <fx:Command x:Key=”loadCommand” Target=”{Binding}” Method=”LoadBooks” />
      Notice that the target is the default binding which will be the ViewModel and the Method name corresponds to the method of that name in the ViewModel (I’m guessing he can infer the CanLoadBooks method as well).
      Finally, we bind the “loadButton” Command property to the “loadCommand” resource. In the video, Nikhil uses the Cider designer for this purpose (so much for “no drag-and-drop”). You might prefer to tweak the XAML yourself:
          <Button x:Name=”loadButton” Command=”{StaticResource loadCommand}" ...  />

      What’s Not To Like?

      I guess it’s ok. Nikhil is making the better of a bad situation, namely, that we cannot yet bind View events to ViewModel methods.
      We require a trick shot. We bank the binding cue ball from the button’s Command property off of a static resource at the top of the XAML file and into the ViewModel “LoadBooks” hole. I am not happy about that. I’d prefer to bind the button directly to my ViewModel. On the other hand, I dislike the ICommand crap in my ViewModel. If I must choose between the two, I’m reluctantly inclined toward Nikhil’s approach.
      Of course they both breakdown when you need to wire a ViewModel method to anything other than a button Command property. What do you do for the SelectionChanged event of a ComboBox? You can’t bind to that as you can “Button.Command”. You’ll have to reach for a different trick – an attached property perhaps – to do what is essentially the same thing.

      Bind By Convention

      That’s why I’m increasingly enamored of Rob Eisenberg’s “bind-by-convention” approach which he showed at MIX. I can write
        <Button x:Name=”LoadBooks” />
      and Rob’s little framework will both find and wire up my ViewModel’s “LoadBooks” and “CanLoadBooks” methods.
      If my ComboBox looks like this:
       <ComboBox x:Name=”Books” />
      and if my ViewModel has "Books", "SelectedBook" and "BooksChanged" methods, he'll bind the ComboBox's ItemsSource, SelectedItem and SelectionChanged events for me.
      There’s no fuss, no muss whether I’m binding Buttons, ListBoxes, TextBoxes, whatever. And I can always go old-school when the naming conventions fail me. Pretty sweet.
      A minor downside with Rob’s approach is the lack of tooling support. Intellisense doesn’t kick in when I’m setting a control’s Name property. I can live with that … especially because his full framework comes with diagnostics that tell me which expected bindings are missing at runtime.

      Summing Up

      I’m all too used to the ICommand-in-ViewModel and I know I don’t love that. I have a feeling that Nikhil’s Command Resource is a better way. It’s certainly more elegant.
      Bind-by-convention is the most appealing choice. But I’ll withhold final judgment until I have more experience with it.
      You’ll want to watch Nikhil’s talk in any case to get a more rounded view of your choices. He ranges over more ground than commanding … commanding is perhaps 10 minutes of a one hour talk. Check it out.

      Comments on this post are closed.

      Friday, March 19, 2010

      Rob E’s Mini-MVVM Framework @ MIX10

      Rob Eisenberg’s MIX 2010 talk, “Build Your Own MVVM Framework” was terrific. If you feel modestly comfortable with MVVM, run over and get the video and the code.

      Rob may be best known for his Caliburn WPF/Silverlight Presentation Development Framework. That’s a hefty body of work and if the word “framework” sends an unpleasant shiver down your spine … relax yourself.

      The “framework” demonstrated at MIX is roughly 500 lines (says Rob … I haven’t checked yet <grin/>). It’s based on Caliburn but stripped to essentials that Rob covered in an easy-to-follow, leisurely, one hour code-walk.


      • Simple MVVM
        • "VM first" in the sense that VM is in the driver's seat.
        • No impediment to "View first" in the sense of view-design drives VM-design.
      • Simple naming conventions eliminate tedious code and XAML
      • Configuration at-the-ready when conventions fail
      • No code-behind … and didn’t miss it
      • No behaviors … and didn’t miss them (not that they’d be bad)
      • No XAML data binding; debuggable bindings created at runtime
      • No drag-and-drop binding … and didn’t miss it
      • No ICommand implementations and no event handlers
      • No files over 150 lines (as I remember)
      • Cool co-routines for programming a sequence of sync and async tasks; no call backs in the ViewModel
      • Screen Conductor pattern in play

      All that in one hour.

      The “co-routine” trick alone is worth your time. You almost get F# “bang” syntax in C#.

      It could get more complicated in your app … and you’d have Caliburn. But it might not  … and you’d be living large with dead-simple, DRY code.

      One of the best sessions ever.

      If only we could teach Rob to emote. The guy is passionate on the subject but you might miss it behind that mono-tone voice of his. A Jim Carrey he is not. You want entertainment? Look elsewhere. You want substance … tune in.

      He got a big ovation, by-the-by, so it ain’t just me who liked it.

      MVVM, Josh Smith’s Way

      I’ve long admired Josh Smith’s work. He’s one of the best explainers on the web and he – together with Karl Shifflett and Andrew Smith - gave us Mole, the superb WPF Visual Studio debugger visualizer.

      I heard recently that he’d published an e-book on Model-View-ViewModel (MVVM). I met him for the first time at the Microsoft MVP Summit last week and he graciously handed me a printed copy. I devoured it on the plane home and spent the next day playing with the code and preparing this review.

      It’s called “Advanced MVVM” and you can buy a printed copy for $20 or get it for $15 on the Kindle. The companion code is freely available at

      $15 bucks for a 52 page “book”? It’s more of an extended essay to be honest … an essay with code. After spending some pleasurable hours with both book and code I thought “where do you get that kind of entertainment / self-reflection for $15?” I have a surfeit of 600 page sleepers lounging on my bookshelf at home; paid more then $50 for each and hardly cracked them. Should we pay by the pound? So I’m over it. I don’t mind paying for the hours Josh poured in and the fun I got out. Set your expectations appropriately and you’ll feel fine.

      ---- 19 March 2010 Note ---

      Ok, it’s been a month or so since I wrote this. Life happens while you’re making plans. I intended to be among the first to comment on it. I’m late to that party (although I have deliberately NOT looked at what others may have said) so I’m not sure if it’s still timely. I also shared it with Josh last week to see if I had missed something and get his feedback, particularly in light of my critical remarks.

      He encouraged me to publish it even at this late date. I hope he’ll repost here some of his responses to the points I raised.


      MVVM has spooked a lot of developers. There’s more than a whiff of astronaut architecture about it. There have to be at least 20 MVVM frameworks and no end of contentious arguments to confound and distress you. No wonder so many are put off.

      MVVM in a Nutshell

      In fact MVVM is fundamentally a simple idea. It starts with the realization that your application is an intractable mess in part because you dumped all of your UI logic into the code-behind … with the help of Microsoft tools. You discover the wisdom of pulling much of that logic out into a companion class (and some helpers) leaving the view class to concentrate on looking pretty and capturing user gestures. The view and its companion must talk; you can structure their conversation according to a variety of familiar patterns. Model-View-ViewModel is one such pattern.

      The predominance of automated binding is the hallmark of MVVM. You bind a View’s textbox to a string-providing property of the ViewModel so that a user’s changes in the textbox flow to the property and so that programmatic changes to the ViewModel property flow back to the textbox. You bind View events (e.g., button click) to event handlers in the ViewModel enabling user gestures to be conveyed to the ViewModel.

      You could write your own bindings by hand, pushing and pulling data and events with custom code. That’s a lot of work. The XAML-based client technologies (WPF and Silverlight) provide a binding framework that requires little to no custom coding. In most cases you can “connect the dots” declaratively and it just works.

      Now the View concentrates on appearance and the ViewModel feeds the view. This separation is both clarifying and liberating. You can start looking at that ViewModel to figure out what it should do and how it should do it without also worrying about the visuals. The subsequent examination of ViewModel’s more limited responsibilities sets you on a more sustainable course. At least this has been my experience … and that of the hundreds (thousands?) of other developers who’ve adopted this pattern.

      Now you’ll note that I said it “sets you on course”; I did not say it delivers you to the promised land. There are details to work out. If the View looks to the ViewModel for data, where does the ViewModel get that data? Are we talking about data values alone or the business rules that surround that data, rules about data validity, integrity, security, and persistence?

      Many of us draw a circle around these concerns and call that circle “the Model”, the third element in the MVVM triad. Our guiding intuition is this: “the persistent data are definitely in the model and if the rules about data are true for this and every possible UI, the rules belong in the model as well.”

      If the last name is required, it is required everywhere; that’s a model rule. If gold customers can select from several thank-you gifts, that sounds like UI logic to me … and belongs in the ViewModel. The specifics have to be worked out.

      Back To Josh

      At this point the discussion risks slipping into theory and theater. We could run to the white board, scribble madly, and count angels on pins without writing a line of code. I love doing that.

      Josh has taken another direction which is likely to be both more popular and more effective. He briefly presents his take on MVVM in clear, accessible prose … and then makes it tangible with an extended exploration of a meaty sample application. I’ve read plenty of pattern papers; I don’t remember any that were so thorough … and entertaining … in their examples.

      For style and substance this is a remarkable achievement. I truly hope that Josh’s book is widely read because I think it has a better chance of helping WPF and Silverlight developers feel comfortable about MVVM than anything else I’ve seen.

      I’m a little worried that some will fear the word “Advanced” in the title. The term “MVVM” is forbidding enough and many folks are still looking for the introduction. I think this book is the introduction they really need.

      In what sense is it “advanced”? It’s far from the last word on the subject. It won’t settle any arguments (least of all mine). But it does rise above the introductory level in two important respects.

      First, it considers the implications of multiple, cooperating MVVM instances. Most MVVM articles present a single MVVM-triad: a single View and its companion ViewModel and Model.

      No application needs a single MVVM triad. If you have a one-screen application, don’t use MVVM; it’s overkill. MVVM is for multi-screen applications consisting of multiple MVVM triads which spring to life somehow and somehow interoperate.

      Second, as I noted earlier, Josh doesn’t just talk about the pattern. Most of the pages describe the accompanying game, BubbleBurst, which is implemented in MVVM style. Instead of paeans to principles and their wondrous benefits, you see MVVM in action, warts and all.

      BubbleBurst is “advanced” enough to both introduce MVVM and reveal important implementation challenges of multi-MVVM applications. Yet it’s simple enough to be easily understood in the pages of a book or in a few hours spent trolling the code. It’s also fun to play.

      Proceed with Caution

      I’m about to begin my critical remarks. Before I do, I want to reemphasize my enthusiasm for what Josh has accomplished. This book is a wonderful place to begin your MVVM journey and I found it to be an enjoyable and insightful read. So, hell-yes, I’m recommending it.

      On the other hand, it would be a shame if developers stopped their education here. Important elements of the story are missing and many recommendations are seriously misguided in my view. Readers should take Josh seriously but, once they are comfortable with the pattern, they should become aware of starkly contrasting perspectives as well.

      Critical Omissions

      Four vital topics are neither covered nor illustrated in the code:

      • Testing
      • Model (the first ‘M’ in MVVM)
      • Dependency Injection
      • Event Aggregation


      Josh asks “What is the point of having ViewModels?” First among his reasons: “the ability to easily write unit and integration tests for the functionality of the user interface without having to get into the messy world of writing tests for live UIs.

      That’s the last we hear of testing. There is not a single test in the code base. If testing is as important as he says, I’d expect a thorough treatment starting with building a test regimen and showing, by example, how to write good tests. Instead, we get lip service.

      I don’t think testability is the only value of MVVM. I couldn’t recommend it for this reason alone. MVVM is a significant architectural investment that introduces complexity. I wouldn’t incur that complexity cost merely to make my UI testable. I’d look for a less onerous route. Fortunately, I think it has other benefits such as clean separation of concerns, improved readability, and easier debugging (try break-pointing XAML!).

      But testability is both a motivation for and a by-product of MVVM style and it should have been covered thoroughly in an “advanced” treatise on MVVM.

      Moreover, the design would have benefitted greatly from attempts to test it. Many lines of view code-behind are both untestable and harder to follow than they should be. I see early signs of the spaghetti code that afflicts more complex and mature applications … a drum I’ll beat furiously later in this review.

      At almost 300 lines, the BubbleMatrixViewModel begs to be tested both for quality and to reveal the expectations latent in its 20+ public and internal members.

      The Missing Model

      The pattern is called Model-View-ViewModel. Josh’s Model is nowhere to be found. Model and ViewModel are combined and it’s not clear to me how one would disambiguate them.

      The absence of Model isn’t blatantly obvious in a simple game like BubbleBurst. The game doesn’t to retrieve or save objects to a persistent store. We aren’t expecting much in the way of business model logic either; there’s nothing of interest to validate or secure. So the lack of a model is not a deep fault of this particular application. Indeed, it’s a convenient way to concentrate our attention on the central issues for most students of MVVM:

      • What code belongs in View and what code in ViewModel?
      • How do View and ViewModel interact?
      • How do you instantiate Views and ViewModels?

      Nonetheless, we can’t pretend to provide a comprehensive guide to MVVP without talking about the Model and how it interacts with ViewModel and (to a lesser extent) View. A business application will demand a clear delineation of responsibilities and equally clear communication paths.

      I’m not letting BubbleBurst off the hook either. I felt on several occasions that some ViewModels were heavier and more complicated than they should be because an inchoate game model was not independently defined.

      Dependency Injection

      I appreciate that Dependency Injection frightens many developers. You can discover MVVM without learning about Dependency Injection. Josh can kind of get away without it as long as he doesn’t test his ViewModels and doesn’t have to think about the services required to manage a persistent model.

      But I feel you can’t call this “Advanced MVVM” … or even “Intermediate MVVM” … without introducing DI at some point. In Josh’s application, every View and every ViewModel class is known to and instantiated by some other View or ViewModel class. That won’t fly in real-world applications which have Views and ViewModels that are ignorant of each other.

      The constructor of the BubbleMatrixViewModel instantiates three concrete bubble components: BubblesTaskManager, BubbleFactory, and BubbleGroup (twice) before making heavy use of them. That’s a lot of dependencies that would make this ViewModel brittle and especially difficult to test.

      Taking hard dependencies means Josh can freely assume that ViewModels will always have parameterless constructors and can always be instantiated in XAML, as he often does here. Someone new to MVVM might think this is the norm. It is not.

      Josh himself alludes to DI as one of the avenues opened by the MVVM pattern: “[MVVM] means that you can use frameworks like MEF to dynamically compose your ViewModels, to easily support plug-in architectures …”. That’s the last we hear of MEF or dynamic VM composition.

      Again, I think we can ignore DI in an introduction to MVVM; we cannot ignore it in an advanced lesson on MVVM.

      Event Aggregation: communicating with the unknown

      All of Josh’s MVVM triads are statically determined. Their relationships to each other are fixed and well known.

      I was surprised to see a ViewModel for one view hold a reference to a ViewModel of a subordinate view. That’s not how I do it; my general rule is that MVVM triads do not hold references to each other. I concede that the rule makes it difficult to organize cross-triad communication. Josh’s approach is simple and elegant … when available.

      In real-world business applications, the MVVM triads often can’t know about each other. They are often defined in separate modules without mutual references. Views appear and disappear dynamically. Direct communication is frequently impossible.

      That’s why so many so-called MVVM frameworks include some kind of messaging or Event Aggregation infrastructure. You don’t need them to understand MVVM triads in isolation. But you never see an application with a single MVVM triad and you rarely find an MVVM application with statically determined, session-permanent views. No “advanced” treatment of MVVM can neglect Event Aggregation.

      View First or ViewModel First?

      Here’s an incendiary topic Josh leaves untouched.

      I see two ways to ask this question:

      • Do I design the View first or the ViewModel first?
      • Do I instantiate the View first or the ViewModel first (or does something else instantiate and wed them)?

      The answer to both questions need not be the same. For example, you could decide to design the ViewModel first and let the View instantiate that VM at runtime. This is plausibly the approach advocated in BubbleBurst although Josh never talks about it.

      Again, it’s important that readers new to MVVM learn that Josh’s way is not the only way.

      View and ViewModel Design

      In my experience there is a “dialog” between View and ViewModel design. The VM exists to serve a view even as it strives for independence from any particular concrete view. A VM is useless if there is no view that will work with it; clearly the VM developer must heed the imprecations of the View developer.

      On the other hand, in business applications the application’s imperatives – what the view must do to satisfy business requirements – are the province of the programmer and are best articulated through the capabilities of the ViewModel.

      Therein lies the necessary tension between View and ViewModel design. As a developer my allegiance is with the ViewModel (“the application should do something worthwhile”) but it would be silly to defend that allegiance at the expense of the View (“a good UX is essential to making an application easy to learn and to use”).

      I’d have liked to see this tension at least acknowledged and perhaps explored.

      Who begets Whom?

      Runtime construction is a question apart from the matter of who drives the design. WPF and Silverlight tooling push you toward “View First” construction in which the View instantiates the ViewModel. You’ll often see the View’s DataContext set by a ViewModel instantiated in the XAML as shown here:

      <viewModel:BubbleBurstViewModel />

      Contrast this with the ViewModel first, code-based approach (not seen in BubbleBurst) in which the ViewModel is assigned to the View’s DataContext as follows:

       view.DataContext = viewModel;

      The View First approach assumes that the ViewModel can be created via a default, parameterless constructor. That’s fine for BubbleBurst but wholly unrealistic in business applications whose ViewModels have dependencies (e.g., on the domain model).

      Neither WPF nor Silverlight XAML support the dependency injection mechanisms that many of us prefer. I wish Josh had talked about this and perhaps discussed the interesting attempts to use MEF dependency injection (via properties rather than constructor arguments)

      I’m not trying to settle these questions. I am saying these questions could have been called out in an “advanced” book on MVVM patterns.

      What Belongs In Code-Behind?

      Do we allow or prohibit code-behind? That’s a fist-fight topic. Josh looks for a Goldilocks solution, suggesting the amount of code-behind is just right if confined to “logic scoped to the view”.

      Such guidance is far too loose in my opinion. It’s not effective guidance at all.

      We choose presentation separation patterns in part because we want to minimize testing of the view. We should test any custom logic we write – no matter how it is scoped. The poverty of our testing tools means that, in practice, we will not test the code in the view. Therefore, any code in the code-behind is suspect.

      I am open to some code in the code-behind; the “InitializeComponent” method is inescapable. I’ll accept a minimum of “switch board” code in the code behind; direct wiring to a ViewModel member is ok in small doses.

      I draw the line at decision logic. I smell a rat when I see a conditional statement of any kind. That’s where bugs breed. Conditional logic is code we should be testing.

      I much prefer this rule: “No conditional logic in the code-behind”.

      That’s unambiguous. We don’t have to wonder what “scope of the view” means. If there’s an “if” or a “switch” statement, something is wrong. You can detect a violation with automation or visual inspection. It’s a rule that’s easy to follow and pretty easy to abide by … when you know how.

      What happens when you don’t follow this rule? You’re lured into the kind of dodgy code that … well we see in the innocent seeming BubbleMatrixView.xaml.cs.

      In fact, far from being “best practices”, I’d say that the View code in BubbleBurst represents some of the worst practices.

      Look at the HandleMatrixDimensionsAvailable method. This event handler is wired to a UI element in the BubbleBurstView. Unfortunately, the UI element happens to be in a different view, the BubbleMatrixView! One view’s code-behind is wired to members of another view; that’s the road to perdition. That would never pass my review.

      I wanted to clean it up immediately. I tried to find the intention behind this practice. Usually I look to the name of a method to discover its purpose. Unfortunately the handler is named for the moment when it is called (“Matrix dimensions available”) rather than for what it does. That’s conventional naming for event handlers but not terribly informative. Unless a handler is brain-dead-simple, I have it delegate immediately to methods with meaningful names. The handler tells me when something happens; the inner method tells me what will be done.

      Had Josh adopted my suggestion, he’d have realized that his handler has multiple responsibilities:

      • wires the outer window’s keydown event
      • picks up the dimensions of the related view’s grid
      • starts the game

      That’s too much work for code-behind in my book.

      When we strive to apply the “no conditional logic in the code-behind” rule, we discover other design problems.

      It appears that Undo logic is distributed between two ViewModels. One of them, the BubbleBurstViewModel, determines if undo is possible while the second, BubbleMatrixViewModel performs the undo. Probe further and we find that even the BubbleBurstViewModel test for undo-ability is delegated back to the BubbleMatrixViewModel. The ping-ponging among Views and ViewModels is confusing; it doesn’t smell right.

      All the signs suggest the real action is in BubbleMatrixView and its ViewModel.

      BubbleMatrixView.xaml is short and sweet.The code-behind in BubbleMatrixView.xaml.cs is another story. Five Region tags sound the alarm. You shouldn’t need region tags in code-behind. Here they barely disguise the complexity of 145 lines of code-behind. That can’t be right.

      MicroControllers: BubblesTaskPresenter Example

      I was able to refactor the 53 lines dedicated to animating bubble tasks. Most of them went to a BubblesTaskPresenter class, a component Jeremy Miller calls the “MicroController”.

      Every MVVM developer should become familiar with the “MicroController” approach.

      A “MicroController” performs a narrow UI task on behalf of a view. We usually write one to encapsulate UI logic that is reused across multiple views. That’s not the case here; the application is too small.

      We also write MicroControllers to encapsulate UI-specific functionality in a UI-agnostic wrapper. They make it easy for non-UI components, such as ViewModels, to invoke the UI-specific behavior we find in Views. That’s what we need here.

      I noticed that the ViewModel holds a TaskManager which raises a PendingTasksAvailable event when there are bubble display tasks. This sets off a sequence of calls between View and ViewModel which collectively “process tasks” queued up by the ViewModel.

      Josh’s original code forwarded the event to the View’s code-behind. That code-behind then extracted the VM’s TaskManager and called into it. 53 lines of code-behind are dedicated to this entire process.

      After my revision, the view merely provides the ViewModel with a configured MicroController, here called a “BubblesTaskPresenter”:

       _bubbleMatrix.BubblesTaskPresenter = new BubblesTaskPresenter(_bubbleCanvas);

      This is what switchboard code should look like. I’d like to get rid of the instantiation but at least there is a bare minimum of logic and no conditionals.

      The ViewModel receives the concrete presenter in the guise of a UI-agnostic interface, IBubblesTaskPresenter and wires itself to the presenter’s events.

          public IBubblesTaskPresenter BubblesTaskPresenter {
      get { return _bubblesTaskPresenter;}
      set {
      _bubblesTaskPresenter = value;
      _bubblesTaskPresenter.Completed += delegate { ProcessTasks(); };
      TaskManager.PendingTasksAvailable += delegate { ProcessTasks(); };
          private void ProcessTasks() {
      var task = TaskManager.GetPendingTask();

      IBubblesTaskPresenter uses simple .NET types and looks like this:

        /// <summary>
      /// Interface for a presenter of <see cref="BubblesTask"/>
      /// </summary>
      public interface IBubblesTaskPresenter {
      void PresentTask(BubblesTask task);
      event EventHandler Completed;

      Where did the 53 lines of code-behind go? Into the BubblesTaskPresenter.

      What has been gained? Did I just hide the pea under another untestable cup called a “presenter”? Is this merely an academic exercise?

      I don’t think so. True, the presenter is dependent upon WPF and upon BubbleCanvas in particular. But it could be tested with a faked canvas and a faked factory. Testing aside, it’s small and focused; it’s easy to see what it does and how it works. It won’t get lost amidst the other motions of the BubbleMatrixView. We might someday use it in another view that presented BubblesTasks.

      The BubbleMatrixViewModel has grown a few lines but remains readable and testable; its imported IBubblesTaskPresenter is easy to fake.

      The ViewModel no longer exposes the TaskManager. That’s a good thing because the TaskManager is pretty complex piece of machinery with a rich API. We don’t want the View or BubblesTaskPresenter to know about it.

      And the View is 53 lines lighter, reducing the anxiety we might justifiably feel if we handed it over to a non-programming designer for styling.

      Homework Assignment: if you’re playing along and are looking toward your own application design, you might want to linger over the BubblesTaskPresenter. It is specific to bubbles right now … which is appropriate in the absence of forces that would drive us to generalization.

      But you can encapsulate storyboard animations in much this way to both determine state changes within the ViewModel and externalize the animations in “View-space” where they belong. Josh is spot-on when he insists on this separation. The MicroController “presenter” approach is one way to achieve that separation without polluting the code-behind.

      Aside: my first presenter was more abstract and general purpose. My generalization was premature. Generalization made the code more complex than it needed to be in this application. I un-factored it to the current version that knows about BubbleCanvas and BubblesTaskStoryboardFactory.

      Views Shouldn’t Talk To Views

      After clearing out the 53 lines, I was able to focus on what’s left.

      I was deeply troubled by the properties of BubbleMatrixView that are exposed to and consumed by the BubbleBurstView code-behind. That can’t be right. Views shouldn’t need custom properties.

      If you have to expose a custom view member, you should do so through a view interface. We don’t want any code – View or ViewModel – depending upon a concrete view class. That’s asking for trouble and flies in the face of the testability which justifies MVVM.

      It’s also completely unnecessary in this application. As noted earlier the event loop from inner BubbleMatrixView to outer BubbleBurstView leads back around to BubbleMatrixView’s ViewModel. We can cut all that nonsense out and simply update the BubbleMatrixViewModel directly in the code-behind … without any conditional logic.

      I refactored as follows:

      • Removed 30 lines from BubbleBurstView code-behind
      • Added “StartTheGame” to BubbleMatrixViewModel; it combines the functions of setting the dimensions (now private) and starting a new game.
      • Removed 61 lines from BubbleMatrixView code-behind which now calls StartTheGame when the canvas is loaded. Region tags are gone.

      The BubbleMatrixView code-behind is now a trim 30 lines with no conditionals, down from 145 (80% reduction). Of the 30, exactly 5 of them do work.

      My cleanup involved eliminating several null checks. They never did anything useful. First, the variables could not be null in practice. Second, even if they were (e.g., someone broke the xaml), the application would not have functioned anyway. I don’t think a blank screen is superior to an exception. The null checks were about as helpful as empty catch blocks.

      Tidy-up BubbleBurstView Code-Behind

      BubbleBurstView’s code-behind had one remaining “if” and some other code that I felt didn’t belong there.

      Key monitoring logic contained an “if” statement. At first it seemed like key monitoring was a candidate for another MicroController. But there is only one key to handle, the key for Undo. That wasn’t worth the overhead of another MicroController component. Instead I decided to enrich the BubbleBurstViewModel with an Undo method whose signature is:

        public bool TryUndo(bool shouldTry) // returns True if undid

      The code-behind calculates whether the key presses amount to an undo request. The call is:

        e.Handled = _bubbleBurst.TryUndo(isUndoKey);

      I don’t like the isUndoKey calculation but I’ll leave it for another day.

      My final bug-a-boo is the LoadBubbleViewResources method which instantiates a ResourceDictionary and plugs it into the application-level resources.

      I expected this to be loaded by the App.xaml itself but I suspect Josh wants to simulate the notion that independent assemblies have their own resources. While the “Bubble.View” assembly is not independent – the App.xaml has access to it through its host assembly’s references –, I’ll play along.

      In any case, the view’s code-behind shouldn’t know the details of ResourceDictionary construction and App.Resources update. Time for a MicroController: “BubbleViewResourceLoader” which we can invoke from within the code-behind’s constructor for now. It still stinks but it stinks less.

      The code-behind now stands at 41 lines, down from the original 86; only 9 of them do work.

      Picky, Picky

      I’m a restless complainer. I’ve got a few more bones to pick having nothing to do with MVVM.

      Page numbers! You may have noticed that my citations lacked page numbers. That’s because there aren’t any in the printed document I’m reading.

      The abundance of Region tags annoys me. Hey, I use them too, especially in pedagogical code where I want to unveil new ideas didactically in the course of a presentation.

      I appreciate that they seem to organize the code into nice buckets: “constructors”, “methods”, “fields”. But lately I’ve come to believe that they’re more of a code smell.

      If the class is short – as it should be – they interfere with my ability to read and grasp the class at a glance. If the class is long, they suggest that my class implements too many distinct concerns and I’m struggling – vainly – to keep them organized. These concerns would be better delegated to supporting classes. I suspect that automated testing would make this defect more obvious.

      I’m not thrilled with the data triggers. Data triggers are not available to Silverlight programmers probably for good reason. The Visual State Manager is the preferred choice for both WPF and Silverlight.

      A particularly egregious data trigger can be found in BubbleBurstView.xaml where the GameOverView is collapsed when the BubbleBurstViewModel’s GameOverViewModel is null. Could there be a more obscure way to signal that a modal dialog should be hidden? I suspect a bound IsGameOver property would be both simpler and more obvious.

      Where’s The Code?

      Josh’s original source is at . I’ve temporarily posted my refactored version on my site. I’m not promising it will stay there- this is Josh’s code and I’ll do whatever he wants me to do with it (including burn it) – but it’s there now and I’ll let you know if I move it.

      Wrap Up

      I have high hopes for the conversation Josh has started with this book.

      I see it as one place to begin your study of MVVM rather than as the definitive work on the subject. Some of the practices I find dubious and there are serious omissions.

      But I gave it this much attention because it deserves it. It’s a fine piece of writing, a carefully considered example, and a push in the right direction. Josh speaks to a broad audience with an authentic voice they understand and respect. He has my respect as well.

      It’s well worth the $15 bucks on the Kindle.


      p.s.: Cross-posted to my other blog on CodeBetter.