Many eyes will be focused on Barcelona on February 29, 2012 when Microsoft releases the Windows 8 Consumer Preview or what many are calling the beta version of the new platform. You’ve probably heard quite a bit about the Metro interface. It has design roots in Zune, Windows Media Center, and Windows Phone. It presents content-rich tiles and is designed to focus on a touch-first experience. Metro provides a unique experience and involves a specific set of tools and technologies. When you read that Internet Explorer 10 doesn’t support plug-ins, you aren’t getting the full story because it’s really only the Metro version that has this restriction.

Of course, we’ve just learned about the experience for Windows 8 on ARM machines. Probably the most revealing quote for me was this one:

“WOA will not support any type of virtualization or emulation approach, and will not enable existing x86/64 applications to be ported or run.”

There’s quite a bit that can be read into that statement, so let’s break it down for a second. Here’s what I understand:

1. Regular Desktop Applications will NOT run on ARM Machines

I never imagined this would be the case because ARM is simply a different architecture. Fundamentally, the instructions used by the CPU at the lower level are different instructions than the ones on x86 and x64 machines. Microsoft bridged the gap between x86 and x64 somewhat by introducing an emulation layer called WOW64 (Windows on Windows 64-Bit) that enables 32-bit (x86) code to run in the x64 environment. I speculated that a possibility might be that Microsoft would create a similar engine for ARM but that is clearly not the case. So all of those programs compiled to x86 and x64 simply won’t work.

It is possible that some applications may make it over. Microsoft was clear, for example, that they will provide special versions of Microsoft Office 15. This appears to be part of the “blue stack” or desktop mode for ARM, which raises some interesting questions. If I were to try to draw the architecture of the Windows 8 stack based on the latest announcement, it would look something like this. Keep in mind this is a typical “stack” diagram that is not a true architecture and there are some obvious issues (for example, Win32 technically extends beneath the Metro stack but I’ve kept it out to keep it simple). Here’s what I am picturing:

stacks

Notice that the entire Metro stack sits on top of the full suite of processors, while there is a definite dividing line between the x86 and x64 sides versus the ARM side. So What does it mean? Here is the first thing I can infer:

2. The .NET Framework will not target ARM devices

Notice there is no CLR layer in the blue stack side for ARM. From what I read I don’t think this is the case because if the framework were available, Microsoft would explain that a whole suite of existing applications should run fine. Ironically, one of the early points about the .NET Framework was that it contained an abstraction layer with MSIL (Microsoft Intermediate Language) that should allow it to target different platforms, including ARM. It doesn’t appear this effort was made. However, this does raise a point of confusion that I look forward to learning more about and clarifying as more information becomes available. Take a look here:

stackclr

I know that on x86/64 machines, the C# version of Metro applications actually runs on the CLR. It uses the .NET Framework. There is a “core profile” that limits a number of Base Class Libraries (BCL) but it uses this nonetheless. There are also projections of the WinRT API that expose themselves as CLR objects. Since the announcement from Microsoft certainly embraced the fact that ARM realizes the full Metro stack, the implication is that this CLR layer exists. So the question is: do they have a version of the framework available? Did they just provide a smaller stub/trimmed down version like Silverlight that just supports the Metro stack needs? Is there a different mechanism altogether on the ARM platform that is something new? I’m sure these questions will be answered but it does make me curious. If we agree that there is not a general framework version available and we also know that there is no emulation/virtual layer, then I can also safely guess that …

3. .There is No Silverlight on ARM Devices

This is actually not something I’m disappointed about. It makes sense. The Silverlight runtime might not make sense for a number of reasons including the overhead of building a version that targets ARM (this has been done to support Windows Phone 7, but it is a different version) and battery/memory management concerns. I still think writing applications that target the platform specifically makes sense. There is a reason why iPad devices are so popular. They are fluid, the applications are responsive, and they just work. While an x86/x64 tablet has the perfect architecture to host the full desktop experience, ARM is a different architecture specifically targeting the mobile space and should be optimized that way.

This is why I’m fairly sure (and agree with the decision that) the ARM version of Metro won’t run plug-ins. The plug-ins are hosted on Windows machines and are therefore compiled to x86/x64 machine code which is not compatible with ARM. It simply doesn’t make sense for Microsoft to invest in building, what, a special ARM plug-in just for Silverlight?

However, there is a desktop experience and there will be applications released for this mode. So what makes me very curious is this:

stacklanguage

So this is just my educated guess but from the post it is obvious there are desktop experiences like Explorer and applications like Office 15 that will target ARM. So what is the platform for building these? Will Microsoft make this available for us to use, so we can do blue-stack development on ARM machines, or will it only host some exclusive products? Is the engine they are using a C++ based engine or do they have a full suite of language options available that can target this area of the platform? Again, right now I can only speculate but it will be interesting to learn.

At this point you might wonder why I’m so calm saying Silverlight on ARM is a good choice when I just finished a book about Silverlight business applications. The answer is simple. Too many people assume that WinRT is the future for Microsoft and anything that isn’t supported by the Metro stack is going to become extinct. I disagree. In fact, I’ll say …

4. WinRT is NOT the Future for Microsoft

Don’t get me wrong. WinRT isn’t going away and is a major part of Microsoft’s future. I just meant it is not THE future for Microsoft. Contrary to speculation, Microsoft is not putting their eggs all in one basket and are not just focusing on Metro for Windows 8. I am still confident we’ll see traditional WPF and Silverlight development on existing Windows 7 machines and Windows 8 machines for the desktop side moving forward. Do you really think ALL complex user interfaces will go away? That certain people will stop doing CRUD data entry applications, or authors will suddenly be happy using the pen tool to write novels when they can type 15 times faster?

I doubt it.

There will still be a need for devices that run a powerful OS capable of building software and allowing us to use big Excel spreadsheets as well as pop open Word to write a document or PowerPoint to prepare a presentation. I don’t think that blue stack is going away any time soon. I also believe if you do find yourself doing Metro development, you’ll be using many of the same skills you are familiar with in Silverlight.

Don’t take my word for the fact that Windows 8 is not just about Metro. Let’s take a quick look at the evidence for the tale of two stacks.There has been plenty of talk about the jarring experience of falling back to the desktop mode. This mode is backwards compatible for applications that are written for previous versions of Windows and I’ve confirmed this by installing applications like Microsoft Office, Amazon Kindle, and several Silverlight-based touch applications including ones I’ve previously helped write. As my current book Designing Silverlight Business Applications goes into print, it’s comforting this paradigm is still fully supported on the new platform. So what is the evidence that the desktop mode is not just a mere fallback to Windows 7 that hides behind the Metro stack?

Here are a few announcements from Microsoft and changes with the desktop mode for x86/x64 targets that really stand out:

Fast Boot and Reduced Memory Footprint

Windows 8 boots fast. It’s not an illusion either. On an SSD machine you can shut down, press power for a cold boot and be working in your next application within seconds. This is a huge benefit – how many times have you actually delayed firing up your laptop because you dreaded the long boot time? That completely goes away with the new boot.Read about delivering fast boot times in Windows 8. Learn more about how these features also reduce the memory footprint.

Graphical UEFI Boot

The boot is not only faster. The boot supports the UEFI standard and is graphical. Remember those old text-based menus we used to have to navigate when dual-booting? Those are a thing of the past. Not only do you get a nice graphical boot interface, you also benefit from features like touch support so you can use your tablet to navigate the boot options. You can see screenshots of the experience and learn more about it in this link. This is not just an illusion, it works and it works with your Windows 7 applications.

Windows 8 on a Stick

This is a phenomenal feature that I haven’t seen covered much. It refers to the capability to install your Windows instance on a thumb drive so it can travel with you from work to home. This special version of the OS is capable of recognizing the device/hardware configuration and hosting the instance based on the environment you boot to. Imagine being able to install your favorite applications and configurations, then be able to take them and use them on your work desktop as easily as your personal laptop. You can learn more about this feature here.

New Explorer Experience and Features

The Windows Explorer experience has been completely revamped.While remaining familiar to users of the legacy version, it provides more functionality through the expanded ribbon interface. When you manipulate files from within Explorer, you will immediately experience the improved file management basics. Operations such as mounting VHD drives or ISO images have been completely integrated out of the box.The new concept of Storage Spaces allows you to organize pools of storage and virtual disks that behave like physical disks. Disk support has been extended to allow for larger disks with large sectors. This is a completely new file system experience that remains compatible with the legacy features you are familiar with.

Enhanced Task Manager

Microsoft took a new look at the task manager and completely refreshed its capabilities.This is substantial because it wasn’t just extended to support the new Metro platform. It now has a simple view for killing applications that does it quickly and efficiently. The grid was enhanced to help diagnose performance issues by providing heat maps and lighting up resource usage. It also groups like processes together.

There are actually many other features that address the non-Metro space for Windows 8 but I’ve gone on far enough in this post. I’m again very excited about Windows 8 on ARM and commend Microsoft for taking a non-compromise approach to making it the best experience possible. Although WinRT and the Metro platform is definitely the future for mobile and touch-based devices with Windows 8, I encourage you to keep pace with the desktop-based enhancements and remember there is an entirely different stack available for line of business applications that might not make sense in the Metro paradigm.

As a developer with XAML and C# skills you are well positioned to navigate both stacks as you build applications and have the freedom to choose what makes the most sense for your end user. Of course, I’m not assuming those are the only languages my readers know – and now there is a first class space for C++ development as well. No, I didn’t forget our HTML5 and JavaScript developers, but to be honest, that is the one block in the stack that I’ve spent the least amount of time in. I’m currently writing my next book on “Building Windows 8 Metro Applications with XAML and C#”. I believe there will be a huge benefit for existing Silverlight developers to work in both worlds. Look for more details from Addison-Wesley soon on that new title.

What are your thoughts about the recent announcements? Are you going to try to be first in line to download the next version when it becomes available?

I have to admit that I may have rolled my eyes a bit when I first learned about the KnockoutJS library. It sounded too much like forcing a square peg into a round hole. Isn’t Model-View-Controller (MVC) already it’s own pattern? Does it make sense to apply something like Model-View-ViewModel (MVVM) to HTML? I already had enough issues dealing with MVVM on the platform it was designed for, XAML and C# (WPF and Silverlight). Some people simply didn’t get the pattern, others were pushing it without really understanding its benefits, and many applications completely and unnecessarily overcomplicated their implementation of the pattern. So before we talk about whether it makes sense in HTML-based applications, we first need to agree on what the benefits of the pattern are.

I’ve heard many opinions regarding this and have not only read lists, but also published my own. You might hear things like “decoupled code” or “best practices” or “modularity.” Many of the benefits often cited are really just good coding practices that should be implemented regardless of the user interface (UI) pattern being followed. After looking at all of the different benefits, coding using different patterns, and spending several years building enterprise Line of Business (LOB) Silverlight applications it really boils down to two specific benefits:

  1. Testability – MVVM improves the testability of your application. This is only a benefit if you feel that testing itself provides benefits.
  2. Designer-Developer Workflow – MVVM facilitates a separation of UI and presentation logic concerns from the business layer that makes it easy to streamline the development process by allowing design cycles to happen in parallel with development. A great example of this was the Microsoft Looking Glass project that had more than 6 designers working on design for over 3 months while we developed it. The total delivery time was around 4 months, instead of the typical 7 (3 + 3 + 1 month of testing) you get when the design process has to happen sequentially and not parallel to the development effort.

The design-time views even without the workflow are useful but not critical in my opinion. So how does this all translate to HTML-based development?

HTML is Not XAML

The first distinction that Silverlight and WPF developers need to make is between HTML and XAML. They are often compared, but are they really similar?

XAML is a declarative language for instantiating an object graph. While it is commonly used for UI elements, it can create special objects like styles that apply theming to elements, behaviors, triggers, even code that has no visual artifacts whatsoever. XAML by nature is extensible. You can create new elements that map to custom classes, and extend the attributes of existing elements through attachments and custom markup extensions. This strict relationship between the declaration and the object graph means that invalid XAML is a Bad Thing™ and causes the XAML parser to choke. If it cannot instantiate an object or set a property, the entire visual tree is invalid and that’s that.

HTML is declarative markup. It defines a structure. Most of that structure is simply containers for information. There is minimal behavior. Elements are pre-defined based on an accepted standard and arbitrary extension or customization is not supported. The containers provide some structure to information, but it is ultimately CSS that defines the UI and to an extent some of the presentation logic and behaviors. JavaScript handles the object graph for the page, but neither CSS nor HTML declaratively instantiate JavaScript objects. It’s the other way around – JavaScript in the context of a page is more like parsing an XML Document in C# code than it is like having XAML and code-behind. The closest thing to XAML in the web world is server-side code that through whatever mechanism emits the HTML and JavaScript code elements of a web page.

Because HTML is just structure, browsers can also be very forgiving in their parsing. They do not have to map an element to an actual class or type that is instantiated. Browsers will close your tags for you and even make substitutions for elements they don’t recognize. There are well-known algorithms for rendering HTML.

So how does this fit into MVC? First, let’s be clear on one important distinction:

MVC as a Framework, not a Pattern

Note I didn’t say MVC is a framework, but in the context of this conversation we’ll have to agree that I’m referring to MVC as a Microsoft Framework and not the pattern. When you talk about the pattern, it can get very confusing when introducing an entirely separate pattern like MVVM. When you talk about a framework based on the pattern, it’s a little easier to understand. While ASP. NET MVC is based on the MVC pattern, it doesn’t force a strict implementation or interpretation of the pattern and provides quite a bit of flexibility with how you structure your pages. You can choose different view engines and write your code in different languages.

So what about MVVM in the MVC framework? One of the key problems I’ve found when dealing with MVC is markup that looks like this:

<div id="logoDisplay">                
   <% Html.RenderPartial("LogoControl"); %>            
</div>                      
<div id="menuContainer">
   <ul id="menu">
      <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
      <li><%: Html.ActionLink("About", "About", "Home")%></li>
   </ul>                       
</div>

What’s wrong with this? It compiles and runs perfectly fine, right? Here’s my issue: I’ve just lost my designer-developer workflow. True, I might be able to hire an MVC-savvy designer who can work with this code, or I may be responsible for design myself. I’ve seen this workflow before:

  1. Designer creates Adobe Photoshop assets
  2. Same designer or someone else turns it into a beautiful HTML web page
  3. Developer has to rip out the HTML as best as they can and format it into the view and merge into CSS
  4. QA tester finds some strange nuance where a field wraps and unfortunately the designer doesn’t know how to fix it because their version works fine, it’s only in the runtime that it happens
  5. It turns out one of the embedded commands emitted some whitespace that the template didn’t account for and was causing the issue
  6. etc. etc. etc. .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

This also gives me no design-time experience. If HTML was real HTML without any embedded markup, I could just drag it into a browser and go to town. This is one place I start to see value with MVVM in MVC. I could do the same thing above, but make it look like this instead:

<div id="menuContainer">
   <ul id="menu">
      <li data-bind="foreach: menuItem">
         <span data-bind="text: name">Name</span>
      </li>     
   </ul>   
</div>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Now I’ve got clean HTML that I can hand to a designer. I can even pull it up in a browser and view it to get a preview. Only … there’s still a problem. Can you see it?

The Problem with Data-Bind

Remember how I mentioned that HTML is not XAML? HTML is not supposed to be arbitrarily extended as in the previous example. In fact, most editors will complain about the data-bind attribute because it’s not a valid, defined attribute. Sure, you’ll get away with it: browsers are notoriously forgiving when it comes to bad mark-up, but this is what I would call an invasive or intrusive way to mark up HTML. What would really be nice is if we could do this more cleanly and provide pristine HTML with CSS, then provide our behaviors, validations, etc. in a way that is design-time friendly and testable.

A Clean Approach

For my “clean” approach I decided to model a simple form. It allows for first name and last name, shows the name dynamically as it is edited, and only allows submission when both fields are entered. First, let’s take a look at the HTML. I’m confident I could pass this off to a designer and they could modify it to their heart’s content. The only requirement is that they honor my “contract” which is the specific ids I’ve assigned. We agree there is something called a first name and last name and that they should be consistently referenced as firstName and lastName – whatever else they want to change is up to them.

The full HTML is here:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Example MVVM Form</title>
      <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
      <script type="text/javascript" language="javascript" src="jquery-1.7.1.js"></script>
      <script type="text/javascript" language="javascript" src="knockout-2.0.0.js"></script>
   </head>
   <body>
      <h1>Example MVVM Form</h1>
      <p>This is an example of an MVVM-based form. The HTML is "clean" markup - there are no custom attributes, tags, or embedded JavaScript. Everything is wired separately through code.</p>
      <form id="mainForm" action="#">
         <div class="form-label">Full Name:</div>
         <div class="form-field"><span id="fullName"></span>&nbsp;</div>
         <div class="form-label">First Name:</div>
            <div class="form-field">
               <input id="firstName" class="textField" type="text"/>
               <span id="firstNameValidation" class="field-validation"></span>
            </div>
         </div>
         <div class="form-label">Last Name:</div>
            <div class="form-field">
               <input id="lastName" class="textField" type="text"/>
               <span id="lastNameValidation" class="field-validation"></span>
            </div>
         </div>
         <input type="submit" class="formButton" value="Save">
      </form>
      <script type="text/javascript" language="javascript" src="./viewModel.js"></script>
      <script type="text/javascript" language="javascript" src="./mvvm.validations.js"></script>
      <script type="text/javascript" language="javascript" src="./bindings.js"></script>
   </body>
</html>
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now that we have a page we can easily edit, let’s make it a little prettier with some simple CSS:
body {
    font-family: arial, helvetica, sans serif;
}

h1 {
   color: maroon; font-size: 20pt; font-weight: bold;
}
p {
   font-size: 12pt; 
}
.form-label {
   font-weight: bold;
   float: left;
   width: 200px;
   padding: 10px; 
}
.form-field {
   padding: 10px;
}
input.textField {
   width: 300px;
}
input.formButton {
   width: 100px;
   background-color: lightgreen;
   border: 2px solid green;
}
input.formButton:hover {
   background-color: lightred;
   border: 2px solid red;
}
.field-validation {
   font-weight: bold;
   padding-left: 10px;
   color: red;
}

The view model is easy enough, it simply defines fields for the first and last names and a computed field that shows the full name. I’ve even been kind enough to humbly supply a default first name:

function NameViewModel() {

   var self = this;

   this.firstName = ko.observable('Jeremy');
   this.lastName = ko.observable('');

   this.fullName = ko.computed(function() {
      if (self.lastName()) {
         if (self.firstName()) {
            return self.lastName() + ', ' + self.firstName();
         }
         return self.lastName();
      }
      return self.firstName();
   });
}

var viewModel = new NameViewModel();

What’s nice about the MVVM approach is that I can easily extend the view model to provide validation. I will eventually use the JavaScript module pattern to create the validations so they can be easily attached and extended, but for this simple example I just used a simple object instead. In this case there is simply a required validation. In a full production system, I would have a library of these validations and also keep a collection on the target object to allow multiple validations to attach to the same attribute.

ko.extenders.required = function (target, overrideMessage) {
    
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    function validate(newValue) {
        target.hasError(newValue ? false : true);
        target.validationMessage(newValue ? "" : 
             overrideMessage || "This field is required.");
    }

    validate(target());
    target.subscribe(validate);
    return target;
};

function MvvmValidations() {
    
    this.required = function(target, overrideMessage) {
        target.extend({ required: overrideMessage });
    };

}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Now I have a view model specific to my view and a validation library that I can reuse across multiple views. I tie them all to the HTML like this – note that what is important is that the contracts were honored for the identifiers of the various elements, but everything else can be simply attached and declared.

$(document).ready(function() {

   $('#firstName').attr('data-bind','value: firstName, valueUpdate: "afterkeydown"');
   $('#lastName').attr('data-bind','value: lastName, valueUpdate: "afterkeydown"');
   $('#fullName').attr('data-bind', 'text: fullName');
 
   var validations = new MvvmValidations();

   validations.required(viewModel.firstName);
   $('#firstNameValidation')
   .attr('data-bind','visible: firstName.hasError, text: firstName.validationMessage');

   validations.required(viewModel.lastName, "Last name is required."); 
   $('#lastNameValidation')
   .attr('data-bind','visible: lastName.hasError, text: lastName.validationMessage');

   viewModel.saveName = function() {
      if (viewModel.firstName.hasError() || viewModel.lastName.hasError()) {
         alert('Errors exist.'); 
         return false;
      }
      alert('Looks good!');
      return true;
   };

   $('form').attr('data-bind', 'submit: saveName'); 
 
   ko.applyBindings(viewModel);

});

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

You can view the end result and download the source here: http://apps.jeremylikness.com/samples/knockout-mvvm/mvvm.html

Quod Erat Demonstrandum

So what have we achieved? I think quite a bit. This format has allowed me to build out a website using data-binding. The source HTML is clean and can be edited easily by a designer. While I muck around with the DOM at runtime, this is done programmatically and doesn’t require that I invade the HTML or CSS. The JavaScript is separate, reusable, and testable.

The thing I haven’t shown is how this fits into the MVC framework. In the framework you’ll likely go ahead and use some of those helper methods to specify the path to the JavaScript but you should be able to maintain a nice, clean HTML core. And if the view models seem like a lot of work, you’re not thinking about the bigger picture. With a strongly-typed view (one that correlates to a typed model) you can easily create a view helper that emits the necessary JavaScript for the view model. You could probably even emit the code to generate the bindings, and the only step you would need to take as a developer would be to write the controller to return the model and apply any validates specific to the view.

At the end of the day, I’m a believer that MVVM can work in MVC if we remember that HTML is not XAML and approach the code the right way.

I created a quick video to help you get started with using Jounce. The video starts with a blank slate, steps through installation of Jounce and the creation of a sample view model for a simple contact record that includes validation.

You can access the video directly at http://vimeo.com/jeremylikness/jounce-getting-started, or view it below:

Jounce: Getting Started from Jeremy Likness on Vimeo.

Jeremy Likness

I'm pleased to announce the official release of Jounce 2.0 for Silverlight 5. There are quite a number of new features available that I'll review in this post. Most significantly, of course, the code base has been updated specifically to target Silverlight 5. A number of bug fixes, feature requests, and Silverlight 5 features have been added. The DLL for Jounce is still just under 100 KB for release so it remains nimble and lightweight.

There are two ways you can install the latest. Zip over to Jounce at CodePlex to download the binaries and/or the full source. Or, jump into NuGet and install the Jounce package. The package is set up to wire in a default application. To get this functionality, follow these simple steps:

  1. Create a new Silverlight application. I recommend the basic "Silverlight Application" template as I haven't tested with any others, and it doesn't matter if you host it in a web site and/or choose to use WCF RIA services.
  2. Delete the App.xaml and MainPage.xaml files. Trust me on this one.
  3. Jump into the package manager console and type Install-Package Jounce.
  4. Hold down CTRL and press F5 and you should see a welcome message. That's it. You are ready to write your Jounce application.

What's New

The code base is now CLS compliant.

The application service used to wire Jounce now exposes some configuration properties. You can use this to have Jounce ignore unhandled exceptions (by default, it will intercept these and publish them as a message instead) and also to set the debug level. These used to be parsed from the parameters from the object tag but obviously this did not make sense for OOB applications.

When dynamically loading XAP files (i.e. extension or plugin modules) you can specify a callback that Jounce will call to report progress. This allows you to have more control over the extension points and display a progress message to the end user for example.

The processing of the XAP file URL was updated to allow query strings. This is a common method to dynamically serve up XAP files and/or to manage updates for OOB applications. Jounce used to choke on this but the code was updated to gracefully handle this when you specify the URL to the XAP to download.

You no longer have to derive your view model from the BaseViewModel class. The only requirement for the framework to work is for you to implement the IViewModel interface. This will help developers who wanted to provide their own base class services and found it difficult due to the face you cannot derive from more than one base class (hey, I managed to sneak in a basic interview question).

You can specify an option using metadata to automatically call Deactivate on your view model when the corresponding view is unloaded (i.e. if the Unloaded event fires). This allows you to perform clean up automatically when the view goes out of scope.

You can now map a view to a view model in three ways. You can export a ViewModelRoute, you can fluently bind them using a new interface, and you can specify the view model in XAML. The new MapToViewModel custom markup extension allows you to specify the view model name, whether you want a shared or non-shared copy, and whether the Deactivate method should be called when the view is unloaded. This makes it possible to use templates that bind to new instances of view models.

There is additional support for the OOB windows. You can append parameters to the navigation payload or use some fluent extension methods to specify the title and size of a view and have it loaded into a separate window instead of a region. You can also raise events with a title to set the title of the HTML page (in browser) or OOB application (out of browser). To further support OOB, there are additional attributes you can query on the base view model to determine if the application is running out of browser and whether or not it is installed on the user machine.

There is a new class available called CustomType that allows you to construct a dynamic type that is bindable to view models. For example, you might parse a JSON object and use this type to build up the object. It features methods to add new properties and fetch them and will also act as a dictionary with an indexer. It uses an underlying helper class that takes advantage of Silverlight 5's ICustomTypeProvider. You can use the source as a template to build your own custom types (or derive from it instead).

I will update documentation and examples as I can moving forward. My book, Designing Silverlight Business Applications, has many examples of building applications using Jounce including WCF RIA. Thanks everyone for their patience and support of this project!

Jeremy Likness

In 1983 author James Martin published a book called Managing the Data-Base Environment. It’s interesting the term database is hyphenated in the title; it hadn’t quite settled down as a mainstream term yet. I have not read this book myself, but my understanding is that he presented the concept of the “CRUD Matrix” for engineering how an application performs Create, Read, Update, and Delete operations against the database. Regardless of how the term was first coined, it has gained popularity and is in widespread use today.

crudmatrix

CRUD is a model that has existed for decades. A large number of software systems can be classified as a simple combination of CRUD + validation. This is why so many scaffold frameworks provide nearly the same pattern: list records, select record, view detail, edit or delete, and validate a bit along the way. If you are working on an application that follows the pattern of view data, pull it in, do stuff with it, then push it back out, you have an amazing number of options to build it quickly and easily with little ritual or ceremony involved. I see this approach quite often in the development of consumer-facing applications. One track focuses on the engine to present the content to the consumer while the backend system to configure and set up content is quickly generated using a data-driven tool.

If all software operated in CRUD mode many of us might not be employed because it would be so easy to pull CRUD instances out of the assembly line. Software can be quite complex, however, and often models more complex business processes that introduce workflows and state machines that aren’t easily captured with the traditional CRUD model. This fact has led to movements like DDD or Domain-Driven Design, which according to the community website is not a framework or technology but a “way of thinking and a set of priorities.” You focus on the business model and domain, paying attention to important details such as having a common vocabulary that everyone can use to describe the requirements without ambiguity. The source for this concept is defined in the popular “blue book” by Eric Evans called Domain-Driven Design.

A set of new patterns for manipulating data has also emerged to challenge the traditional CRUD model. You can go back to Bertrand Meyer’s Command Query Separation and then examine more recent Command Query Responsibility Segregation (CQRS) pattern by Greg Young to start digging into these principles. A number of implementations exist, including the concept of Event Sourcing. All of these are great patterns to learn and understand as part of your software development toolbox.

cqrs

While the paradigm shift away from traditional CRUD approaches is refreshing, it can also be problematic. There is always the risk of falling victim to the “flavor of the day.” When I began building Silverlight applications, I was reluctant to fully embrace the MVVM pattern because it was consistently hyped as “the way to go” without very much substance around why it was the way to go. I kept sorting through the catchy phrases like “decoupled code” and “SOLID principles” trying to find the value and bottom line for using this pattern, but it wasn’t until I implemented it myself and observed it in practice through several projects that I was able to finally decide it made sense. My teams were able to develop software faster through parallel workflows and the fact that I could engage an entire design team at the same time I was building the application rather than forcing the project into a sequential workflow was the real benefit I found in addition to the support for testing.

I’ve watched a similar trend with CQRS. Like MVVM, many people are declaring it “too complex” when in fact a proper implementation can be quite simple. Just like the MVVM cops appeared one day and starting writing tickets when developers didn’t completely eliminate their code-behind files, I see some CQRS police saying “if you’re not doing it this way, it’s not CQRS.” In many cases that may be correct, but I think it also undermines the spirit of the pattern. In some cases the pure implementation is exactly what is needed … but is it a new rule that everything must go this route?

I think you’ll find the strongest proponents and advocates for the pattern will be the first to say you should use the right tool for the right job. In my book about designing LOB Silverlight applications I added a controller class to an application that is mostly based on the MVVM model. I also include examples with logic in the code-behind. To some this may seem like sacrilege but in fact these cases were the right tool for the right job: they solved the problem while keeping it simple without compromising the ability to test the application.

I learned about the danger of “either-or” thinking back when I was a personal trainer and had an online coaching practice. I found many clients would get stuck in the either-or mentality. For example, “either I completely eliminate soda or my diet is blown.” Rather than, say, cutting back to just one glass a day for awhile. When traveling, I’d hear, “I can’t get my steamed chicken *** and broccoli so I’m just going to get a big pile of junk from a fast food restaurant” instead of looking for healthier options. “The only thing we had to eat was pizza.” Well, sometimes that happens – but instead of eating fifteen slices, why not just eat one? When I taught clients it is okay to compromise – if your workout calls for free weights but your hotel only has dumbbells, go ahead and train with what you have and get a workout done rather than using it as an excuse to sit in the hot tub for an hour – they had tremendous breakthroughs and were able to achieve a true lifestyle change rather than getting stuck in a diet cycle that was doomed to fail and send them back into old habits.

What does this have to do with software? I think quite a bit. You don’t have to take an either-or approach to building applications, either. For example, it’s not a question of using the entire Prism library or Enterprise Library in an application. It’s perfectly valid to pull out the parts you need – maybe the command implementation from Prism and the logging application block from the Enterprise Library – without overcomplicating the project. When you are looking at patterns, it’s fine to create something that is a hybrid if it fits the needs of your application.

Back to CQRS. I think Microsoft has provided some incredible tools for exposing data as services. With the combination of the Entity Framework and WCF Data Services I can create a set of REST-based services within minutes that are consumable by Silverlight, Windows 8 applications, iPads, iPhones, Windows Phones, RIM devices and Android phones and tablets. It’s just that easy. Unfortunately, while the tools also support CRUD operations (and even provide places you can hook into for validation) it doesn’t always integrate well with a domain-driven approach to the application design. That means it’s off the table, right? CQRS is about having different databases, right?

I’d say, “Wrong” on both counts. If the model works well for querying data, configure it to allow queries and get your read operations up and running in minutes. Sometimes over 80% of your application may be about querying and displaying data, so why not keep it simple and expose it in a way that is easy to expand to other platforms when and if needed?

dataflow

But what about updates?

The updates don’t have to follow the same set of interfaces if you don’t want them to. It’s perfectly valid to expose a REST interface or even a RPC-based interface that takes commands rather than “update operations.” Why not? You may have a workflow engine backed by state machines and queues that implement Event Sourcing, and that still doesn’t mean you can’t expose the read interface for your data using WCF Data Services out of the box.

My point is that CQRS provides what I think is a very valuable insight: that how you read and query data is probably very different from how you manage, update, and manipulate data. You don’t have to have a picture-perfect implementation of CQRS to take advantage of this concept – it may be as simple as looking at a different set of interfaces and implementing them using different technologies in the stack. I’ve built implementations based on this philosophy that still have one database and one data model using the Entity Framework but provide multiple implementation paths. They allow me to quickly and easily update the model while keeping the code simple and easy to both understand and maintain.

hybridcqrs

There are some exciting new patterns and approaches to building software that developers should be aware of, but it’s important to look at these as new tools, not new toolboxes. During decades of enterprise software development I’ve rarely watched the toolbox change – it’s almost always been about adding new tools and throwing old ones out. I still see applications that will benefit from the traditional CRUD model and get overly complicated when someone tries to force them into something different. To make a long blog post short: patterns should not be used to define your software, but rather to help solve the problems your software addresses.

About a week ago, I purchased a Samsung Series 7 Slate PC to learn more about the Windows 8 operating system and to test applications I will be developing primarily with C# and Xaml. The laptop ships with Windows 7 installed, but I quickly wiped the existing install and overlaid it with Windows 8. The process for the most part went smoothly. I had to acquire some Windows 7 drivers and install them in compatibility mode in order for the tablet to recognize orientation changes, and I still cannot get the hardware Windows start button or the accelerometer to work. I expected some issues like this as Windows 8 is still a preview OS.

I’ve used the combination of the slate and the operating system quite heavily over the past week and I wanted to take the time to share my impressions in a post while they are still fresh. I’m trying to focus this review more on the OS itself and will call out where I think there are substantial hardware differences.

Summary

Overall, I like it. I’ll preface that with the statement that I am a developer so my opinion is certainly biased compared to what consumers might think. The OS provides the perfect balance between a “total slate experience” which I consider to be watching movies, casual browsing, email, and news readers, and “power user features” like developing software or drilling into a complex Excel spreadsheet. All it takes is a simple external keyboard to efficiently write books and articles and even build software. While the new OS is in beta form and there are not many native applications to choose from, the backwards compatibility makes it possible to install any number of existing touch solutions.

Let me break down where this opinion comes from. I’ll start with the cons.

The Bad

  • Price – this is what I believe still stands as the greatest barrier to general adoption by consumers. The price point is just too high. The idea it can run all of Windows may be appealing to businesses, but not to the average consumer who is comparing this against Android tablets, iPads, and newcomers like the Kindle Fire. If you pay a competitive price for a Windows slate today, you get an inferior product. The Samsung performs well but also is priced well above the nearest competition at well over $1,000.
  • Power – unfortunately I have yet to work with an Atom-based slate that performs well. My standard is to pull up Netflix and run a high definition movie full screen. On a Windows tablet this does several things. First, it loads the Silverlight plug-in and extends the browser environment, and second, it tests the combination of processing that takes place in the Netflix app and the graphics processing happening through the hardware. Unfortunately most of the devices fail miserably for this, and you have to go to an i-series chip. That gives you the power, but means a thicker tablet with a fan and vents.
  • Battery – this ties into the issues listed previously. While the battery is certainly longer than a lot of lap tops – I was watching full screen movies in HD and it lasted hours without draining – it does not go anywhere near the 8 – 10 hours users experience with competing tablets. I believe this is due mainly to the processor architecture and while the alternate system-on-chip processors probably will break this barrier, they will need to perform far better than what I’ve seen so far to make the experience worthwhile.
  • Start Menu – I like the start menu. The concept of live tiles is great, because it turns the start menu into an interactive, “at a glance” dashboard. However, it is not without flaws. First, “grouping” tiles together really doesn’t do anything for me except maybe organize them visually. I want a functional way to group so I can drill in. The idea is as few taps and swipes as possible, which means drilling down, not swiping across. Second, everything ends up as a tile. This may be fine for me, a developer, who knows how to unpin and organize but will be overwhelming to the average consumer. If an install like Office drops fifteen apps, why not organize into a folder by default and have the folder appear on the start menu, and let me drill down and bring common applications back to the top as needed? After installing everything I needed to make the slate productive for me – Office, Live Essentials, etc. – the start menu became so huge I found myself doing nothing but swiping and swiping to get to what I needed.
  • Task Switching – Give me a break. Two experiences? The side swipe is fun to demo and cool when you have two applications, but come on, who really only ever runs two applications? After loading up about five or six applications, continuously swiping across to find what I want is ridiculous. What’s worse, there is no integration with the desktop applications. If you have Explorer, Word, and Outlook running, you get one swipe for “Desktop” and then must ALT+TAB to go between your desktop apps, then either swipe or hit the start button to get back into the Metro applications. Not a good experience. Why not provide an aero-like view or cover flow style preview of the applications when I swipe so I can quickly tap on the one I want? Even a grid of thumbs would be preferable to multiple manual swipes.
  • Consistency – While I like the features and customization options that are available, it’s a little weird that half of the control panel is Metro and the other half dumps you to the desktop and back into the familiar Windows 7 dialogs. Why not finish the experience and make it consistent? You also are shifted to the desktop every time you launch a desktop application, which annoyed me at first but I found I quickly got used to and didn’t mind as much – I’m more irritated about the lame experience trying to swap tasks
  • Ribbons – I get it. The ribbon is the Microsoft UI widget of the future. It’s appearing everywhere. I like the ribbon, and it makes sense in a lot of applications. While I resisted the newer Office releases in the beginning because of the new interface, after using it for years now I’ve come to enjoy it. But here’s a news flash: it’s not the same on a slate. On a touch-based device I want to have context where I touch. That means if I’m navigating the file system, I want to be able to tap on a file or folder and right there see my options and quickly tap through. It’s not a smooth experience to tap down there and then look up there to the ribbon and then find the right place on the ribbon to tap. May have worked well on the desktop, not so fun on the slate. This is weird too because it gives the impression of OS schizophrenia. In the “Metro” portion I have an experience highly tailored to touch that feels right, responsive, and is enjoyable. In the file system explorer for the same OS, suddenly I’m forced to a completely different paradigm that doesn’t feel natural at all. Was it two entirely different teams working on these features? Why are they so different? I don’t buy that it’s because “it’s part of the desktop experience” – no, it’s not. Anything I can reach in my slate is part of the slate experience, whether or not it happens to fall into what was the traditional desktop.

The Good

  • Boot Time – while some may say competitive slates boot quickly, the fact that this boots so fast and provides full-blown Windows capabilities to me is amazing. My slate literally boots in seconds – that’s from a complete shut down. It is fantastic and I no longer dread turning on my machine because I have to figure out something to kill time while it’s booting – it’s that fast.
  • Windows – some people argue this is not a feature and may be a detriment to slates, but I disagree. The fact it is full-blown Windows and not a trimmed-down version is why many customers want a Windows-based slate. It was a key driver for the project I did with Rooms-to-Go. I love it. I installed Office and can easily navigate through Word documents, PowerPoint, and Excel. Sure, sometimes it requires using a keyboard, but the option is there. It gives me my built-in Windows security, allows me to use policies and gives me access to a ton of software that simply isn’t available on competing slates.
  • Backwards Compatibility – while this is just a beta the backwards compatibility so far has been outstanding. I’ve not had an issue installing any Windows 7 productivity software I wish to use. Even drivers for the Slate that aren’t yet available in Windows were successfully installed using compatibility mode. My Amazon Kindle for PC application works beautifully so there’s no need to pick up the hardware, I’ve got my “Kindle” right here. I’ve also had a lot of fun playing with the applications that ship with the Microsoft Touch Pack for Windows 7 that uses Microsoft Surface technology.
  • Silverlight – there was a lot of fuss about Silverlight and it being a dead-end but I’m happy to share it is not only fully supported on the slate, but shines. Some of the best applications I have aren’t written for Windows 8; they are written in Silverlight and run fine as Out-of-Browser (OOB) applications on the slate. Some that stand out are the USA Today Windows Touch application, Mosaic by Tribune, and Telerik’s Facedeck Silverlight Client for Facebook. Oh, did I mention I can just chill at night with headphones and watch my favorite Netflix movies in full screen high definition?
  • Metro – I like Metro. There are things that I believe could be improved, but to me the advantages include:
    • Live Tiles create a true “dashboard” and at-a-glance experience, showing me insights without having to open an application. The tiles just need a better way to organize them.
    • The Metro guidelines (no pop-ups, overlapping windows, etc.) make for a very crisp, clean, enjoyable experience. I am able to easily navigate between applications and they are very responsive. The task switching must be improved, however, and better integrated with the desktop experience.
    • Charms and Application Bars to me make sense and once you understand the gestures make it very easy and consistent to navigate within applications. I really found the slow swipe from the right to get a full menu is something I use a lot, and enjoy the at-a-glance signal, battery, and time in addition to quick-jumps to other areas.
  • Keyboard – the Windows 8 keyboard is awesome. It’s nice and big and easy to type. I have long, complicated passwords and tapping them out is a breeze. My only gripe is the fact that you have to switch to get the numeric keyboard which can slow that down. The highlights and sound provide just the right amount of feedback to make the typing feel natural. The split keyboard is awesome for some major thumb-typing while grasping the sides of the tablet.
  • Pen and Handwriting Recognition – the pen is very powerful. I wanted to spend some time with family while I was editing the final chapters of my Designing Silverlight Business Applications book, so I settled down in the family room with my slate and pen. To my surprise, I was able to be very productive. It was easy to highlight with the pen, and the handwriting recognition was superb – I very rarely had to correct it’s interpretation and my handwriting is abysmal. I was able to have a productive, casual editing session without lugging around a laptop or even pulling out a keyboard. The combination of handwriting and touch makes for a very powerful and productive experience.
  • Search – while I still feel the tiles could be better organized in the start menu, I love the integrated search. It’s fast and easy to use and the fact you can search within a context and even pass searches to other applications is awesome (sorry, can’t think of a better way to say it).
  • IE10 – this may be strange coming from someone who listed Silverlight as an advantage when the IE10 Metro implementation does not allow plug-ins, but let’s face it: 2011 was the year of HTML5 and it is rapidly growing with adoption. I have no qualms about switching to my desktop IE version to run Silverlight applications when most of them are OOB applications that I can launch with a single touch from the start menu anyway. For most web sites, the built-in IE10 browser is all I need. It provides a great browsing experience, renders well, and provides all of the interaction I need. I use the built-in browser often and enjoy the browsing experience – I’ve even started to use YouTube in HTML5 mode although not all videos are available and you have less control over the experience. I especially like being able to pin sites from IE10 to my start menu.

As you can see, there are a lot of pros to weigh against the cons. In summary, I’m very pleased with where the slate experience is going but I’m also concerned. I’m a power user – a developer – so I like falling back to heavy desktop applications, don’t mind doing a little extra to get around, and also am used to shelling out more dollars for my toys than average consumers might be willing to. I think the biggest obstacle to overcome is providing performance at a lower cost to increase value and get rid of fans and fat form factors. The Metro experience needs a bit of work before I think my grandmother, grandfather, or niece will be as comfortable with it as they are grabbing an iPad, but I don’t think it’s an impossible task. I’m very excited to see the upcoming beta release that is rumored for fall of 2012 to see how well Microsoft listened and what steps they were willing to take to improve the quality of the product.

It is very exciting to see the release of Silverlight 5 today, despite all of the rumors flying around the Web. Read the original release announcement from the Silverlight Team here. This is proof positive the team made a commitment to release a new version by the end of the year and stuck to it. This release offers major functionality over prior releases and is something I believe has the potential to revolutionize development for line of business applications, or I wouldn't be writing a book about it. You can download the release here (note that sometimes the servers may take time to synchronize, so if you are not seeing the link, wait a little awhile and refresh ... it will eventually appear for you).

My blog has been covering this for quite some time so I thought it would make sense to recap the coverage I've already provided as well as address some myths vs. facts about this release.

First, a summary of articles I've posted that relate to Silverlight 5:

I will also be releasing a new version of my Jounce MVVM+MEF Framework that fully supports the new capabilities of Silverlight 5 over the next few weeks. You can download the latest source to preview this functionality and I'll consolidate into a 2.0 release probably right after the holidays.

Let's tackle some myths:

Myth: Silverlight is dead.

Fact: Silverlight 5 has just been released. The team has been working hard to implement new features and address issues uncovered through internal and external builds like the beta and release candidates. This release contains significant functionality that make it an ideal platform for building Line of Business applications.

Myth: Silverlight has no Future.

Fact: We're not sure if Silverlight will have a future release, as Microsoft has not formally addressed this and that is definitely a possibility. That doesn't mean it doesn't have a future. There are plenty of cases where the current version will meet the demands of users sufficiently to warrant future development. The next IDE slated for release, Visual Studio 11, has Silverlight support so the tools are not going away any time soon. Silverlight runs perfectly fine on the new Windows 8 desktop so applications developed using this version will not be obsolete when users move to Windows 8, although by all predictions Windows 7 is going to be around for a long, long time. The biggest enemy of Silverlight right now is not capability nor support, but speculation and rumor.

Myth: The Silverlight team gave up on Mac OSX, this release is for Windows/Internet Explorer only.

Fact: Silverlight 5 is fully supported on Mac OSX and across multiple browsers. The new 3D features rely on DirectX and therefore are not available on the Mac OSX platform, and p/Invoke/COM obviously does not make sense because there is no counterpart. All of the core features including interactivity, printing, etc. are all fully supported as demonstrated by the release candidate (RC). You can see the full list of supported browsers and platforms here.

Myth: Silverlight is no longer the optimal choice for platform reach

Fact: I believe this to be true when you extend reach to smartphones. For desktop applications that will traditionally run on Mac OSX, Windows, and Linux, I still see Silverlight 5 as the viable option for the first two. Obviously lack of Linux support rules that out but I have not found that to be an issue for line of business applications. Most businesses are still putting their heavy applications on Windows with a smaller percentage on Mac OSX and Silverlight provides phenomenal capabilities to build the application once and have it run on both platforms, even out-of-browser in occassionally disconnected scenarios. Silverlight is only a viable target for smartphones on the Windows Phone 7 platform. I don't believe this removes Silverlight as a player as it depends on the level of native touch you want for your application. A high-touch application will likely require developing with Silverlight for Windows Phone, Objective-C for iOS devices and Java for Android unless you are using a tool that provides multi-targeting like the Mono suite. On the other hand, if you can get away with less native touch and functionality, HTML5 is certainly a good option for building a mobile footprint once and having it function consistently across those surfaces. Keep in mind however that this does not mean you can build it once and have it run fine on your desktop targets - you'll still be developing different screens. The ability of Silverlight to connect to existing services like REST and WCF end points still makes it a very viable option for the desktop presentation layer even if the mobile footprints are written using an HTML5-based solution.

Conclusion

It's out, it's loaded with features, and it still has plenty of life left in it. Go out and grab the latest version of Silverlight and see for yourself! I'm interested in all comments and feedback below. Thanks!

Jeremy Likness

While writing Chapter 14 of my book, Designing Silverlight Business Applications: Best Practices for Using Silverlight Effectively in the Enterprise (Microsoft .NET Development Series) I focused on an area that is quite common with line of business applications: extremely large data sets. In the example I generated almost 1,000,000 contact rows to illustrate how they would be managed by the Silverlight client. Like many software problems, there are many solutions; here is an excerpt of the three I demonstrated in the book.

All of these solutions use the Entity Framework for data access. How that data access is projected to the client is illustrated bythree different patterns: OData (the straight services, not the checkbox on the WCF RIA Services tab), WCF RIA Services, and using the MVVM pattern. To simplify the examples I'm only focused on reads here. Writes do add a layer of complexity and change tracking, but I argue that the problem to solve there is not how to manage a large data set because anything the user actually interacts with is going to be a smaller order of magnitude.

RESTful OData

It's extremely easy to expose an OData end point from a .NET web application. You can simply add a new WCF Data Service and then define what it has access to. In this example I have a Contact table that looks like this:

After generating the data model, the Entity Framework provides this in my ContactModel space:

The underlying context that was generated is called ContactEntities so for my OData service I can simply point to the underlying context and specify which collections are available and what access rights the client should have:

public class ContactOData : DataService<ContactsEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {            
        config.SetEntitySetAccessRule("Contacts", EntitySetRights.AllRead);
        config.SetEntitySetPageSize("Contacts", 20);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }
}

Note I've specified a page size of 20 records so that the service doesn't return all 1,000,000 records at once. When I hit the service endpoint, I get this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<service 
   xml:base="http://localhost:59389/ContactOData.svc/" 
   xmlns:atom="http://www.w3.org/2005/Atom" 
   xmlns:app="http://www.w3.org/2007/app" 
   xmlns="http://www.w3.org/2007/app">
  <workspace>
    <atom:title>Default</atom:title>
    <collection href="Contacts">
      <atom:title>Contacts</atom:title>
    </collection>
  </workspace>
</service>

This is all a client needs to begin navigating entities as the location of the first collection, Contacts, is clearly specified. We can now navigate to the contacts and receive something like this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed 
   xml:base="http://localhost:59389/ContactOData.svc/" 
   xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
   xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" 
   xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Contacts</title>
  <id>http://localhost:59389/ContactOData.svc/Contacts</id>
  <updated>2011-11-20T16:24:05Z</updated>
  <link rel="self" title="Contacts" href="Contacts" />
  <entry>
    <id>http://localhost:59389/ContactOData.svc/Contacts(1)</id>
    <title type="text"></title>
    <updated>2011-11-20T16:24:05Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="Contact" href="Contacts(1)" />
    <category term="ContactsModel.Contact" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <content type="application/xml">
      <m:properties>
        <d:Id m:type="Edm.Int32">1</d:Id>
        <d:LastName>Alford</d:LastName>
        <d:FirstName>Lucius</d:FirstName>
        <d:Address>Ap #363-9702 Sit Rd.</d:Address>
        <d:City>Jordan Valley</d:City>
        <d:State>CO</d:State>
        <d:Email>mi.eleifend.egestas@mauriserateget.com</d:Email>
      </m:properties>
    </content>
  </entry>
  ...
  <link rel="next" href="http://localhost:59389/ContactOData.svc/Contacts?$skiptoken=20" />
</feed>

Notice that it follows the standard Atom format. Every entry has a clear location including where to go to post updates ("edit"). The full data set includes 20 entries and then specifies a link to grab the next page.

Adding this to the Silverlight client is easy. You can add a service reference, discover it in the current solution and the client will be wired for you automatically. Using a DataGrid that auto-generates the columns, I can write the following code behind:

public partial class ODataClient
{
    private readonly DataServiceCollection<Contact> _contacts;
    private readonly ContactsEntities _context;
    private DataServiceQueryContinuation<Contact> _nextPage;

    public ODataClient()
    {
        InitializeComponent(); 
        _context = new ContactsEntities(new Uri("../ContactOData.svc", UriKind.Relative));
        _contacts = new DataServiceCollection<Contact>();
        _contacts.LoadCompleted += ContactsLoadCompleted;
        var query = _context.Contacts.IncludeTotalCount();
        _contacts.LoadAsync(query);
    }

    void ContactsLoadCompleted(object sender, LoadCompletedEventArgs e)
    {
        _nextPage = _contacts.Continuation;

        if (_nextPage == null)
        {
            NextPage.IsEnabled = false;
        }

        TotalCount.Text = e.QueryOperationResponse.TotalCount.ToString();
        Count.Text = _contacts.Count.ToString();
        dgContacts.ItemsSource = _contacts;
        dgContacts.UpdateLayout();            
    }

    void Button_Click(object sender, RoutedEventArgs e)
    {
        _contacts.LoadNextPartialSetAsync();
    }
}

The fields hold references to the service. It is instantiated with a relative path to the end point. The query is extended to include a total count of records so it can be used to calculate page sizes, and the link to the next page is retrieved and stored for the continuation. When the user clicks the button to load the next block of records, the continuation is called to fetch the next page. The grid and button look like this:

The example is a quick-and-dirty way to parse the OData stream but can be extended to include a proper paging control (instead of simply expanding the grid) as well as edit and update functionality. Now I'll show you how to do the same thing using WCF RIA. The obvious advantage with WCF RIA is that the code projection removes most of the manual steps you need to take.

WCF RIA Services

The domain service for WCF RIA simply maps operations like queries to the corresponding LINQ-to-Entities commands. This example is read-only so the full implementation looks like this:

[EnableClientAccess]
public class ContactService : LinqToEntitiesDomainService<ContactsEntities>
{       
    public IQueryable<Contact> GetContacts()
    {
        return ObjectContext.Contacts.OrderBy(c => c.Id);
    }
}

The service derives from the context for the contact database and the query simply orders the items to allow paging (the result set must be deterministic for paging to work). That's it on the server side. A metadata class is also generated that you can use to apply data annotations to specify column names, validations, etc.

The client automatically has the WCF RIA classes "projected" which is a fancy way of saying the code is generated for the client. In fact, WCF RIA handles so much plubming that the WCF RIA client doesn't have to have a single line of code-behind. Instead, you can drop in a domain data source:

<riaControls:DomainDataSource 
   AutoLoad="true" 
   d:DesignData="{d:DesignInstance Web:Contact, CreateList=true}"                             
   Height="0" 
   Name="contactDataSource" 
   QueryName="GetContacts" 
   Width="0"
   LoadSize="60" 
   PageSize="20">
    <riaControls:DomainDataSource.DomainContext>
        <Web:ContactContext/>
    </riaControls:DomainDataSource.DomainContext>
</riaControls:DomainDataSource> 

By convention, ContactService is renamed to ContactContext on the client. The domain data service uses context as its data source. It is given some design-time data to generate the grid properly, the query to get the list of contacts is specified along with how many records to pre-fetch and how many to show on a page. A DataGrid simply binds to this as the data source along with a DataPager:

<sdk:DataGrid AutoGenerateColumns="True" 
   ItemsSource="{Binding ElementName=contactDataSource, Path=Data}"/>
<sdk:DataPager 
   Source="{Binding ElementName=contactDataSource, Path=Data}"/>

And that is it! It will handle computing total records, managing pages, and generating the grid. The result looks like this:

That provides what I would call the ultimate rapid development experience. It can literally take just five minutes to create the Entity Framework model, map the domain service, then drop the domain data source and grid controls on the client to have a fully functional application. Of course, as a developer you may want more control over how the application works and perhaps need to make sure this fits within your existing patterns. The most popular pattern for Silverlight development is Model-View-ViewModel (MVVM) so here is a quick view model to make it work:

MVVM

Instead of relying on WCF RIA you can abstract the data access layer using a pattern such as repository. This isn't a full implementation but the simple interface looks like this:

public interface IRepository
{
    void ProcessPage(int page, int pageSize, 
       Action<IEnumerable<Contact>> callback);
    int GetTotalPages(int pageSize);
}

Now you can use a mock to test access to the repository and even swap layers if or when it is necessary. Here is an implementation that works directly with WCF RIA:

public class Repository : IRepository
{
    private int _totalCount;
    private readonly ContactContext _contactContext = new ContactContext();

    public Repository()
    {
        var query = (
                        from c
                            in _contactContext.GetContactsQuery()
                        select c).Take(1);
        query.IncludeTotalCount = true;
        _contactContext.Load(
            query,
            callback => { _totalCount = callback.TotalEntityCount; }, null);
    }

    public void ProcessPage(int page, int pageSize, 
        Action<IEnumerable<Contact>> callback)
    {
        var take = pageSize;
        var skip = pageSize*(page - 1);
        var query = (from c in _contactContext.GetContactsQuery()
                        select c).Skip(skip).Take(take);
        query.IncludeTotalCount = true;
        _contactContext.Load(
            query,
            cb =>
                {
                    _totalCount = cb.TotalEntityCount;
                    callback(cb.Entities);
                }, null);
    }

    public int GetTotalPages(int pageSize)
    {
        return (_totalCount/pageSize) + 1;
    }
}

Note when the repository is created, it queries for a single item just to grab the full count for computing the page size. This is updated each subsequent call for a page. The call to grab the page computes how many records to skip and take for a page and then executes the query.

A simple view model can be constructed that uses the repository:

public class ViewModel : INotifyPropertyChanged
{
    private List<Contact> _contacts = new List<Contact>();
    private readonly IRepository _repository;

    public int CurrentPage { get; set; }

    public int TotalPages { get; set; }

    public IActionCommand NextPage { get; set; }

    public IActionCommand PreviousPage { get; set; }

    public IEnumerable<Contact> Contacts
    {
        get
        {
            if (_contacts.Count == 0)
            {
                Refresh();
            }

            return _contacts;
        }

        set { _contacts = new List<Contact>(value); }
    }
}

It exposes current page, total pages, commands to paginate and a list of the current contacts. The constructor sets up the initial conditions and sets a dummy page and page size in the design view:

public ViewModel()
{
    Contacts = new List<Contact>();
    NextPage = new ActionCommand<object>(obj => GoToNextPage(),
                                            obj => CurrentPage < TotalPages);
    PreviousPage = new ActionCommand<object>(obj => GoToPreviousPage(),
                                            obj => CurrentPage > 1);

    if (!DesignerProperties.IsInDesignTool)
    {
        CurrentPage = 1;
        _repository = new Repository();                
    }
    else
    {
        CurrentPage = 2;
        TotalPages = 10;
    }
}

The Refresh method fetches the current page:

private void Refresh()
{
    _repository.ProcessPage(
        CurrentPage,
        20,
        cb =>
            {
                TotalPages = _repository.GetTotalPages(20);
                _contacts = new List<Contact>(cb);
                RaiseChanges();
            });
}       

The commands simply change the current page and call refresh. For example, the command to advance by one page:

private void GoToNextPage()
{
    CurrentPage++;
    Refresh();
}

Now the view model can be bound to a grid. In this example, the current page and page count are used to construct a very simple paging control. All of the information you need to make a full-blown control is available. The MVVM-based view looks like this:

The ease with which it is possible to navigate a large data set from the client is one of the reasons I believe Silverlight is still a strong player in the Line of Business application space. More details and the full source code for this example will be available when my book publishes. As of this writing on November 20, 2011 it is discounted over 40% on Amazon when you pre-order a copy from here. Thanks!

Jeremy Likness

One of the reasons I prefer to manage navigation as an event, rather than a strongly typed interface or handler, is because it allows for so much flexibility and extensibility in the navigation pipeline. In my Jounce framework, for example, the basic navigation event simply wires up an instance of a view to a view model and makes no presumptions about where that view belongs - it leaves positioning the view to the developer. The region manager simply listens for navigation events and passes the views off to region adapters without worrying about how they are wired, so it automatically handles the view simply by extending the pipeline by listening for the message as well. This same model makes it incredibly simple to place views in child windows using the new Silverlight 5 Out-of-Browser feature.

The first thing I'll do is create a controller to listen to navigation messages. It will expect a specific parameter to be passed that indicates when the view should be passed to a window. If that parameter exists, it will use parameters for height, width, and title to spin up the new window. A more complete implementation would store those literals as constants. Here is the shell for the class that implements the listener and subscribes to it:

[Export]
public class WindowController : IEventSink<ViewNavigationArgs>,
                                IPartImportsSatisfiedNotification
{
    [Import]
    public IEventAggregator EventAggregator { get; set; }

    [Import]
    public IViewModelRouter Router { get; set; }
    
    public void OnImportsSatisfied()
    {
        EventAggregator.SubscribeOnDispatcher(this);
    }

Now the handler. The handler will check the parameters for a special "OpenInWindow" parameter that must be set to true. It will only respond when that's the case, and everything else goes through the normal view routing. Because the project uses region management, there is no conflict because these views will not be routed to specific regions. First, if the parameter doesn't exist, the method simply returns. Note the use of the Jounce extension methods that conveniently cast the parameter to a specific type:

public void HandleEvent(ViewNavigationArgs publishedEvent)
{
    var parms = publishedEvent.ViewParameters;
    if (!parms.ContainsKey("OpenInWindow") ||
        !parms.ParameterValue<bool>("OpenInWindow"))
    {
        return;
    }
}

Next, the router is used to get the view model that is mapped to the view, then spin up a non-shared instance of the view and view model. This allows multiple instances to be created and therefore supports multiple windows with the same view/view model combination. The method to get the view takes an object for a parameter that it will set to the data context of the view. Jounce is smart enough to recognize when that object is a Jounce view model, and will take the additional steps of wiring in visual states and calling the InitializeVm and ActivateView methods on the view model. Notice that the parameters are passed into the view model as well - Jounce will pass these in when it attaches the view model to the view.

var viewModelTag = Router.GetViewModelTagForView(
    publishedEvent.ViewType);
var viewModel = Router.GetNonSharedViewModel(viewModelTag);
var view = Router.GetNonSharedView(
    publishedEvent.ViewType,
    viewModel,
    publishedEvent.ViewParameters 
    as Dictionary<string, object>);

Finally, the window is opened with the view set as the content:

new Window
        {
            Title = parms.ParameterValue<string>("WindowTitle"),
            Width = parms.ParameterValue<int>("WindowWidth"),
            Height = parms.ParameterValue<int>("WindowHeight"),
            Content = view,
            Visibility = Visibility.Visible
        };

That's all there is to it. The controller must be imported somewhere to begin listening for events. Then you can simply export the view with a tag like [ExportAsView("MyView")] and publish the navigation using the Jounce extension methods to turn the view tag into a navigation event and add parameters:

var window = "MyView".AsViewNavigationArgs()
    .AddNamedParameter("OpenInWindow", true)
    .AddNamedParameter("WindowTitle", "My View Title")
    .AddNamedParameter("WindowHeight", 300)
    .AddNamedParameter("WindowWidth", 600);
EventAggregator.Publish(window);

Of course you can get even more clever with how you obtain the title or set the sizes, and now opening a child window is not only as easy as publishing an event, but also fully testable in your view models because you can mock the controller for testing.This technique is demonstrated in detail in the chapter about OOB applications in Designing Silverlight Business Applications: Best Practices for Using Silverlight Effectively in the Enterprise (Microsoft .NET Development Series).

Jeremy Likness

If you've worked with the Region Management pattern before, one source of frustration can be the lack of a design-time view. While you can compose individual views to be designer-friendly, the aggregate views that mark regions often end up devoid of anything useful. A simple little trick, however, can change that.

You may be familiar with creating design-friendly view models, but the extensions for Blend work the same with views. For example, consider a main page that has a layout divided into regions that are marked by content controls, like this:

<ContentControl  VerticalAlignment="Center" Margin="20 0 0 0" region:ExportAsRegion.RegionName="SortRegion"/>

There may be one or many views that can fit in the content control, but having it completely empty just doesn't make a good design experience as you cannot tell how components will fit together. With just a little tweak, however, you can change that. Consider this approach instead:

<ContentControl  d:DataContext="{d:DesignInstance Views:SortView,IsDesignTimeCreatable=True}" Content="{Binding}"
VerticalAlignment="Center" Margin="20 0 0 0" region:ExportAsRegion.RegionName="SortRegion"/>

This simple change has done a few things. First, it binds an instance of a reference view to the data context of the control. The binding will only be invoked in the designer and will not be impacted during runtime. Second, the content control is set to the binding, which is the view in the designer, causing it to render the content. With just that simple tweak you now can see how a view will fit into the region!

The view is created directly and is not recursively wired into the design-time experience, so any design-time data within the referenced view will not appear. To get around that you'll need to create a mock view instead and create an instance of that. If the view isn't activated right away, the content control will end up hosting whatever it inherits from the data context of its parents, which may have undesired side effects, but in most cases you will likely activate the view that routes to the region before any artifacts are visible to the end user. If you need to, you can also manually set the data context (the "real" data-context, not the design-time one) to {x:Null} to prevent it from inheriting anything at runtime.

Finally, there is always the option to use a custom markup extension if you really need a more robust view. For me, the trade-off of making a simple tweak is worthwhile.

Here's the design-time view of a small control, showing sample data:

Here's the main page with nothing but regions and design-time views. While the design-time data isn't wired, the views fall into place and I can get a sense of the overall layout (click to see a larger image):

And finally this is the same application at runtime:

So now you don't have to suffer from regions turning their backs on your designer. Enjoy!

Jeremy Likness

A common problem encountered in Silverlight applications is how to set the focus properly when transitioning between controls. For example, in the reference application I'm writing for the book Designing Silverlight Business Applications there is the option to either edit an existing record or create a new one. The result of clicking the appropriate button is a panel overlay that zooms into view. Obviously, it makes sense once the panel is rendered to set the focus to the first field so the user can simply begin entering information.

If the control was managed by adding and removing it from the visual tree, the solution would be simple. This is the perfect example I have of not resorting to exotic solutions to a simple problem. The focus problem is not a business problem, it is a user interface problem. It's perfectly valid to wire a loaded event to the control, name the field that requires focus, and call the Focus method on that field when the parent control is loaded. This is an example where even with MVVM, it just doesn't make sense to solve the problem in the view model when it is so simple to add the code-behind. This doesn't change my ability to have a design-time data or to test my view model. It also works well because if I reuse the same control, the loaded event will still fire every time it is added back to the visual tree.

I mentioned this would be simple if the control was managed based on adding and/or removing it ... but that's not how I manage it. Instead, I use the Jounce framework to position it in a region and show or hide it by changing the visual state. What's nice about this is that I can have a state based on the action that the view model is invoked with, for example "New" for a new item, "Edit" to edit an existing item, and "Closed" when the view should go away. These actions are all handled by setting the visual state, so there is no convuluted logic to set visibility properties or wire any other logic. The visual state is wired as a delegate by Jounce, so when I test my view models I can simply mock the delegate and confirm the transition is set without actually loading a view. I can also set different types of animations, such as zooming the control from the "new" button for one mode and having it fade in from the grid in the other mode.

The problem with this approach is that the control never leaves the visual tree. Everything is managed by visual states, so the "Closed" state simply sets the visibility to collapsed, which keeps it in the visual tree but just ignores any rendering or hit testing logic. So how can I effectively set the focus based on a visual state transition?

I've read some interesting solutions that create a special "reverse behavior" that wires to the control and can be data-bound to a property on the view model. The view model can simply set the property and the data-binding will force the action to happen. Personally, I think this is a fine approach but I don't see the need for my view model to have to understand that part of the UI concern is setting a focus. I wanted to approach it from a UI-centric view and only involve the view model if needed.

It turns out the solution is quite simple. All I need to do is create a control to help manage the focus. Call it the "focus helper" and start with a dependency property that points to another control:

public class FocusHelper : Control
{
    public static readonly DependencyProperty TargetElementProperty =
        DependencyProperty.Register(
            "TargetElement",
            typeof (Control),
            typeof (FocusHelper),
            null);
       
    public Control TargetElement
    {
        get { return (Control) GetValue(TargetElementProperty); }
        set { SetValue(TargetElementProperty, value); }            
    }

}

The reason this helper derives from Control is because I want to be able to place it inside a grid. The next thing I'll do is expose a property to set the focus. First, the details of the property itself:

public static readonly DependencyProperty SetFocusProperty =
    DependencyProperty.Register(
        "SetFocus",
        typeof(bool),
        typeof(FocusHelper),
        new PropertyMetadata(false, FocusChanged));

public bool SetFocus
{
    get { return (bool) GetValue(SetFocusProperty); }
    set { SetValue(SetFocusProperty, value);}
}

You'll notice that I set the property metadata to invoke a callback whenever the property changes. In that call, I want to see if I have a control set. If I do, then I'll simply call the Focus method for that control, then reset the flag back to false so it can fire again if it is set in the future;

private static void FocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var targetElement = d.GetValue(TargetElementProperty) as Control;
    if (targetElement == null || e.NewValue == null || (!((bool) e.NewValue)))
    {
        return;
    }
    targetElement.Focus();
    d.SetValue(SetFocusProperty, false);
}

Now I've got a handy control that will fire the focus method on a target element whenever its own SetFocus property is set to true. It's easy to wire it to whatever input control I want, in this case a TextBox called "Title":

<Behaviors:FocusHelper x:Name="FocusHelper" 
       TargetElement="{Binding ElementName=Title}"/>
<TextBox x:Name="Title" Text="{Binding Title,Mode=TwoWay}"/>

Doing the binding this way also makes it Blend-friendly. If the focused element needs to change, the designer will be able to click on the binding and target the property all through the designer without touching the Xaml. The last step is to update the visual state. When the control is shown, the visibility is set to "Visible." I simply add another entry to the storyboard that sets the focus property to "true":

<VisualState x:Name="New">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" 
                     Storyboard.TargetProperty="(UIElement.Visibility)">
            <DiscreteObjectKeyFrame KeyTime="0:0:0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FocusHelper" 
                      Storyboard.TargetProperty="(FocusHelper.SetFocus)">
                <DiscreteObjectKeyFrame KeyTime="0:0:0">
                    <DiscreteObjectKeyFrame.Value>
                        <System:Boolean>true</System:Boolean>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>
</VisualState>

And that's it ... now any time I set the control to a visual state that makes it appear, the focus is set to the input control of my choice and the user is able to start typing or tabbing between fields right away. To learn more about the application, order your copy of Designing Silverlight Business Applications and read how it was constructed with access to the full source code.

Jeremy Likness

Once again speculation and worry has developers around the world biting their fingers and lamenting the end of a new era. It almost seems developers want to stick a fork in their Silverlight development because so many are latching onto the hype wagon, calling .NET "legacy" and refusing to see the bigger picture. Microsoft announces a new run-time called "Metro" that is not based on .NET, and suddenly .NET is dead — even though anyone can download the bits for the new operating system, install it, and see for themselves that .NET is alive and well. There happen to be two modes for the application, one in a new "Metro" environment and one in a more "desktop" environment. Microsoft's own Visual Studio is NOT a Metro app so I don't buy the line that this is just a staged coup d'etat. Microsoft announces that there are going to be two version of Internet Explorer: a "Metro" version with no plug-ins, and a desktop version that supports them. I downloaded Silverlight, installed it, and even loaded our Silverlight tablet Rooms to Go Application. It installed fine, appeared on the start menu for Windows 8 and launched without an issue ... but the headlines are reading "Microsoft abandons plug-ins."

First, let me say that I believe Silverlight is alive and well. I'm not saying that because I'm writing a book. People who know me understand I don't get emotionally invested in projects and try to force something to happen when it's not meant to be. I'm not basing this on mere speculation. "What if" doesn't buy me anything. Don't get wrong: I know "what if" is real because it tumbles stocks and cancels contracts, so it does have an impact, but instead of adding to the hysteria I prefer to look at the facts. I know that Windows 8 is not going to be the de facto operating system over night. I know that even when it does, I will be able to build and deploy Silverlight applications to it. I know customers will still have applications to support. I also know I work on a lot of Silverlight applications that simply won't work with the new "Metro" interface and require a more immersive UI and model, and that the guidelines for Metro will probably force those to be written in a traditional stack anyway. I know that a new version of Silverlight is coming out at the end of the year if Microsoft makes their drop target, and I know companies have already begun developing applications that take advantage of its features. But just in case the world is really ending and .NET, Silverlight, and all of those other technologies are truly legacy as of today, what will really happen? I asked my followers on Twitter just what it is that would be missing, and here's what I found out:

Multi-platform and OSX Support

Let's be real here. The only "real" multi-platform support Silverlight has right now is between the Mac OSX and Windows. There is a fledgling presence on Linux but that's hasn't impacted any deals that I'm aware of. The cross-browser story is better because between the two platforms, there is solid compatibility across FireFox, Chrome, Internet Explorer, and Safari. I believe this is a very valid point, as I've done many projects where the customer was most interested in the fact that Silverlight could easily target both platforms with one maintained code base. Of course, the original dream was for this reach to be extended but those hopes were largely dashed by the surge in popularity of the iPad that refused to run the plug-in. While this is a very important aspect of Silverlight, I don't buy that Windows 8 impacts this at all. Windows 8 is an operating system that will run new applications and boasts a new version of a web browser. It also runs the traditional browser and we've confirmed it fully supports Silverlight. So what is missing? The changes to Windows 8 don't remove the ability to drop Silverlight applications on to Mac or existing Windows machines, let alone the next version. It seems the only thing that could negatively impact this point would be lack of features (i.e. I'm missing something that I was expecting to come in a future version) or simply self-fulfilling prophecy, i.e. developers complain so much about it going away that people believe them and pull the plug.

Deployment and web-based Xaml Delivery

This is another sweet spot for Silverlight. The deployment strategy is insanely simple, and many large corporations embrace the easy of installation. This is a double-edged sword however, because for every shop that enjoys the fact that users can navigate to a web page and download the latest version of their application, there is another shop with complicated security policies that must make significant changes to their infrastructure in order to allow the plugin and make Silverlight applications available to employees. This really gets back to the traditional decisions used to drive technology and I don't see how Silverlight is really the primary ingredient. If you want to reach Macs and Windows machines, you will still have that option. If you need a different type of reach or want to take advantage of new innovations, the decision is the same it has always been: either build specific to the platforms you are targeting, with the trade-off that you must now have several teams and versions of the product but it provides a seamless, native experience, or compromise by using a technology like HTML5. That same trade-off existed with the previous version of HTML, it's just that Silverlight development was superior in many cases. I still see cases where HTML5 development is too painful compared to Silverlight, but what it were actually easier to build and deploy HTML5 apps with the same featureset as the Silverlight version? Why on earth would you even want to stick with Silverlight in that scenario?

Community

When I was younger and programmed the Commodore 64, there was a great Commodore community in the St. Petersburg, Florida area. We'd meet up, show each other how to crack open the bread box and solder the little red RadioShack reset button, then swap assembly snippets and chat about the latest VIC chip register hack. When the Commodore began to wane in popularity, people moved onto other platforms and built community around those. Ironically, there is still a strong, growing Commodore 64 community. I'm pretty sure community is more about the individuals in the community than the technology that drives it. Silverlight has a great community. If Silverlight goes away, that community will evolve. (OK, so there are always one or two who can't move on and are still stuck on Information Society breaking up and refuse to program on anything other than an Amiga).

Income

This is like community. First, let me say I know the financial impact of decisions is very real. Speculation about technology causes contracts to get canceled and people to lose jobs. However, if you believe your income is based on the success of Silverlight you are making a very, very big mistake. I remember when I received my fitness and sports nutrition certifications so I could coach people to lose weight. Many of the other "graduates" felt they should research what the pay ranges for trainers were, start at the lowest rate and work their way up. I felt like I should get paid what I was worth, not what the average income was, and had some success working with people so I started at the high end of the range and built a practice around that. My income wasn't based on the latest diet fad or exercise scam, it was based on results. When people lost weight and kept it off, they told others, and my practice grew. It was the value of my service that determined my rates, not industry averages or trends. Software development is the same way. Skilled developers provide value, the customer perceives that value, and they continue to deliver the best possible solutions based on the right technology for the job. If that technology changes, they change with it. Of course, if you want to focus all of your energy on complaining about how horrible it is that Microsoft shifts their strategies and let everyone know how much time and money you invested in learning dead technologies, you're welcome to. Complain away. The people I know who are successful in this industry move on. I'm not saying it's a good thing when you find a contract canceled because of a shift in technology, I'm saying you can either focus on the one that got away or figure out how to make sure it doesn't happen with the next one. Your choice.

P/Invoke

Really? "I don't want Silverlight to go away because it makes sense to run an abstraction layer dependent on a browser so I can go through another abstraction layer to talk back to native code." I just don't get it — is p/Invoke a vaid reason to worry about Silverlight's future? There's no equivalent on Mac OSX so you aren't doing it for cross platform. I'm not sure why you're doing it, really. I like programming in Silverlight: it's fast and it's easy, and p/Invoke opens up options. With the new development platform I can skip the p/Invoke, call the WinRT layer directly and save myself the overhead of importing DLLs and creating obscure structures or learning about how to marshal. To me this one just says, "If you're going heavy p/Invoke maybe it makes sense to look at Visual Studio 2011 and native applications instead."

C# Web App

I don't agree with this one at all. If you are bulding a web site, I think going with the web technologies is key - if I want an application, I'll build it. If I want a rich web site, I'll build it — but different approaches and different tools. Rich web applications still have nuances like page navigation, browser back buttons, and compability that make them different than applications. When I write Silverlight, I'm not writing a web application. I'm writing an application that is easily delivered over the web. That's why I don't use the navigation framework, because I don't think customers are used to navigating desktop applications using URLs. So if it's a web site I want to build and I want to use C#, why not MVC instead? If it's an application, let me use C# by all means ... and as I mentioned above, I may just lose the ease of deploying it over the web. Oh, by the way, did you notice that MVC 4 preview was released? Weird: it's not written in Metro, doesn't create Metro applications, yet Microsoft is still developing it and I don't hear people crying that MVC is dead.

Line of Business Applications

One key thing I see most people missing is that Windows 8 is two separate, distinct systems. Just launch the Visual Studio 2011 to see what I mean. That is not a Metro application. I like Metro, it works great on my phone and think it is the right way to build tablet-based applications, but there are just some things like development environments that don't and won't make sense. If you build for Metro you MUST follow the rules of the sand box, and you are limited. If you jump outside of that, it's back to the traditional stack. So I don't see this shifting gears. Personally the reason why I like Silverlight for line of business applications is because of Xaml and C#. I don't see that changing. I've converted a few applications to Windows 8 as well as walked through the examples and the gap is not huge. It's there, but not huge.

Bottom Line

I see myself having a choice. If I want to develop line of business applications that run on Mac OSX and are delivered over the web, I can develop Silverlight 5 applications. Regardless of whether someone labels that "legacy" it will be supported through 2020 (when the HTML5 spec will finally get ratified) and it will run on my target environments. If I'm building a rich, interactive line of business application, I'm going to want it in that environment. If I'm looking for a user-friendly, touch-first tablet interface, Metro doesn't change things for me. Today without Windows 8 my options are HTML5 or writing native iOS, Java, and Silverlight for Windows. With Windows 8, those options simply shift to HTML or native iOs, Java, and XAML/C#/WinRT. For many years to come, most of my customers will still be on Windows 7 and even Windows XP so guess what: Silverlight and WPF will still be our best options.

Silverlight development will be alive and strong for at least a decade even if no new version is in the pipeline, and longer if there is one. Even if it is the last version, though, as I'm writing my book I see that 90% of the topics covered are going to be the relevant to developing in the new Windows 8 runtime. Here's something that won't come as a surprise to seasoned developers: even if it does go away, there is no way it will ever happen overnight. As long as there is speculation, it's still around. When there is no more speculation, i.e. we know for a fact there is no vNext, there will be plenty of time to transition.

What's my point? My point is this: there are always people who are going to shout that the sky is falling and the world is coming to an end and air all of their woes to the world. The reality is we all have the same hours in the day and we can do with them as we choose. While I've been accused of being a blind, passionate follower of Silverlight for my optimism and enthusaism, I think they've got it wrong. I'm just optimistic and enthusiastic in spite of Silverlight. If it goes away I will adapt and continue to provide value where I can because at the end of the day I'm a developer and Silverlight is a tool in my arsenal. To me, moaning, whining, and complaining is a waste of time. If something's broke, it isn't going to fix itself. I'd like to see more posts on solutions and options moving forward rather than "Hey, I've got a flat, so let's sit on the side of the road, point at it and talk about all of the things that went wrong with my day."

That's my opinion, and not necessarily the opinion of my employer, and I'm sticking to it. What are your thoughts? Please sound off with comments below.

Jeremy Likness

If you are trying to follow the hash tag for the //BUILD conference you are probably dizzy by now. I don't blame you for trying to sort through all the messages about standing in line for the toilet or what someone is having for breakfast. I thought it might be a good time to step back and pull together what you need to know.

Hopefully this helps you sort through the firehose of information. Happy Windows 8!

Jeremy Likness

Yesterday I shared my predictions for Windows 8 at the Build conference. Today I can say that the keynote exceeded my expectations. There were a lot of amazing announcements that I'm excited to share with you. First, let's recap my predictions:

  • Microsoft will focus on Windows 8 as the platform for multiple devices and specifically address the tablet/slate competition space. To be convincing they'll need to address speed and responsiveness, but likely they'll focus on:
    • The richness of the OS - it's not just a big phone, but the full Windows enchilada
    • Security and policies that are lacking in iPad
    • The new HTML5+JavaScript option for development to draw in the developers who traditionally don't work with the Microsoft stack
    • Some lip service to writing it once and running it everywhere whether it's the desktop, laptop, or slate
    • The touch-first features of the new OS
  • Microsoft will emphasize that managed code and Silverlight are not dead and will be fully supported on Windows 8. I don't see the death of Silverlight any time soon (again, these are my predictions ... it will be interesting to see what really happens)
  • They almost have to address the community of developers concerned about managed code and emphasize that it is not going away. I'm guessing they'll talk about how managed code will work with Windows 8 and perhaps reveal some details about Xaml and C# either as Silverlight or something new for developing apps that target Windows 8
  • Microsoft will also address the unmanaged coders and focus on how C++ is coming back to front and center on the new platform, and likely cite some performance examples of why native code is important

I would say I hit the mark fairly close, in fact I underestimated what would be revealed. The main theme for the keynote was bold and re-imagined. While these words were repeated so many times they became a bit cliché, I would say they accomplished both.

The key points the keynote focused on were form factors, mobility, connectivity and sharing, and that services are intrinsic in modern applications. The keynote was divided into four distinct areas, and I'll cover those each.

The Windows 8 Experience

The new experience boasts a smaller memory foot print "up front" and small goodies like a gesture-based login. The main screen is touch-centric but not touch-specific and works fine with the keyboard and mouse. There is a new format that I'll call "clipboard plus" for integration between applications. This is incredible because a "photo chooser" can easily take you into Facebook for example to select social media pictures, without you coding a line of integration. The integration points are called "charms" and are consistent between apps. An example of a charm is integrated search that allows you to pass the single search phrase to multiple applications and get results based on Bing, social media, your file system or whatever else you like.

Building the Applications

I was worried we might not hear about the framework today, but I was wrong. The shell has been re-organized to feature a WinRT layer that supplies object-based APIs that are exposed to any language of your choice - C, C++, C#, VB, and of course the much-hyped JavaScript. A Visual Studio 2011 demo showed a photo application built with a few dozen lines of code using a new JavaScript, HTML5-based project. The project was then opened in Expression Blend which has been extended to support HTML5 just as well as it handles XAML. For those who thought it all would become HTML5, they then pulled down a Silverlight application and built it for the new platform. Just a few tweaks turned it into a native Metro application with full integration. XAML is right on top of the stack proving that the core Silverlight technologies are still very much a part of Windows 8.

The new application store is integrated directly into the development platform and allows direct publishing of applications. Sinofsky described as being as simple as "ordering a pizza." There is a visualization of the steps within the process and developers will have full access to the tools used to analyze and validate the applications that are published.

The most impressive feature I saw was the ability to take one code base and very easily and quickly build to the desktop, to Silverlight, and to the Windows Phone. This is exactly what people have been looking for and what addresses the unfounded fears that Silverlight technology would go away.

Hardware

I mentioned that one thing Build would need to address is the iPad. I think they did that well by not only showcasing some amazing UI features that make the iPad feel old, but by showcasing the hardware as well. The boot is ultra fast, taking only seconds. The bootstrapper includes malware detection and they showed an infected USB boot drive get halted because it contained a virus. A new "connected standby" mode wakes up periodically to process timer and network based addressed and then idles the power. All applications are hardware accelerated out of the box for the richest possible experience. Devices can be extended with miniature applets that integrate directly into your existing applications - for example, a print dialog that doesn't require you to "go somewhere else" to set up the printer settings. We saw super-thin laptops that were actually thinner than the legacy CAT-5 and USB connectors.

Integrated into the OS are options to refresh the system and remove malware and adware, as well as a command-line option to create a snapshot of the baseline and use that to restore the machine. There is an improved task manager, improved multi-monitor support, and Hyper-V built into the client. The onscreen keyboard is also very welcome and enables you to use a tablet to remote into a development machine and work (and no, I doubt I would be doing that very often).

Windows Live Integration

I did not expect them to address the iCloud but they did that through Windows LIve. There are settings to automatically synchronize between PCs and cloud-base email that automatically integrates across all devices. There are shared calendars, shared photos, and other repositories that synchronize to the cloud seamlessly from applications. A share charm allows you to integrate all of these items including between applications and to the cloud. You can also use the cloud to remote back to your devices. The key here is using the Live id to integrate all of the devices from your desktop and laptop to your Windows Phone and slate devices. This comes with a new API to make it very easy to integrate into your applications.

Conclusions

I am very excited about what I heard today. We can finally move on with the conversations about Silverlight. We will be able to use our investment in C# and XAML technology moving forward while allowing HTML5 and JavaScript developers to join the platform as well. The new platform looks exciting and responsive with a lot of features that put the customer experience first. I think these new devices and the new OS can absolutely compete with the likes of iPad because they provide an enhanced touch experience while carrying forward all of the security policies and features as well as supporting all of the legacy applications that came with Windows 7 and the 450 million people who have installed it. I believe this is a very exciting time and there is incredible opportunity now to build the next generation of applications using our existing knowledge and investment in Microsoft technologies.

Don't Forget to Download the Preview!

The preview, including the OS for both 32-bit and 64-bit, along with development tools will be available after 8pm PST on Tuesday, 9/13 at this link: http://dev.windows.com/.

Jeremy Likness

Tomorrow is the start of the major event that has been hyped as heralding the most significant changes to Windows in the past 15 years (the last was when Windows 95 was announced). There has been a lot of speculation around what will happen tomorrow. Some people claim it will be the death of Silverlight and even managed code, while others hope to see news about the next version of the Windows Phone operating system. While I am not able to attend the event, I will be watching the keynotes closely, collaborating with my associates in the field who are at the conference, and blogging my insights over the next few days.

I've been asked by many customers, fellow developers and Twitter followers to share my thoughts on the Build Conference and, as a Silverlight MVP, what I think about the future of Silverlight. I obviously have a stake in its future as I'm about 2/3 of the way through writing a book about building enterprise applications using Silverlight. So what are my thoughts?

Personally, I think there has been far too much read into the focus on HTML5 and JavaScript. I may be proven wrong, but based on what I've seen (and this is all public knowledge as I have no "insider information" about Windows 8) I believe the following will happen:

  • Microsoft will focus on Windows 8 as the platform for multiple devices and specifically address the tablet/slate competition space. To be convincing they'll need to address speed and responsiveness, but likely they'll focus on:
    • The richness of the OS - it's not just a big phone, but the full Windows enchilada
    • Security and policies that are lacking in iPad
    • The new HTML5+JavaScript option for development to draw in the developers who traditionally don't work with the Microsoft stack
    • Some lip service to writing it once and running it everywhere whether it's the desktop, laptop, or slate
    • The touch-first features of the new OS
  • Microsoft will emphasize that managed code and Silverlight are not dead and will be fully supported on Windows 8. I don't see the death of Silverlight any time soon (again, these are my predictions ... it will be interesting to see what really happens)
  • They almost have to address the community of developers concerned about managed code and emphasize that it is not going away. I'm guessing they'll talk about how managed code will work with Windows 8 and perhaps reveal some details about Xaml and C# either as Silverlight or something new for developing apps that target Windows 8
  • Microsoft will also address the unmanaged coders and focus on how C++ is coming back to front and center on the new platform, and likely cite some performance examples of why native code is important

Those are my predictions, for what they're worth. I wanted to post these today so I could take a look back over the next few days to see if I was close or completely missed the mark. I'm looking forward to an exciting conference and sharing my thoughts with you as it unfolds!

Jeremy Likness

More Posts Next page »