Latest Tweet:
  • Loading...

Last month I was lucky enough to both attend and speak at the Norwegian Developer Conference. It was a fantastic conference, and the conversations following the conference are still buzzing on twitter and in the blogosphere. For me NDC must have been one of the best conferences I’ve ever attended, offering a diverse range of topics from some of the best speakers in the industry. I’m humbled to be invited to speak at such a great event.

My session was on building Silverlight applications for the Windows Phone 7 platform. Instead of doing a feature tour of all the new APIs I decided to focus on some of the patterns and principles I find important when doing Silverlight development, and showing how to apply these in a Windows Phone 7 context. Some of the topics I covered in my talk included:

  • How to do TDD in Silverlight on WP7
  • The MVVM design pattern and MVVM Light Framework.
  • How to use dependency injection in a WP7 context and how it can help you inject stub implementations of APIs that isn’t available in the emulator.
  • Asynchronous web services using Rx (Reactive Extensions).
  • How to use the location APIs and how to make stub implementations for the emulator.
  • How to use the push notification API.
  • Making your views Blend-friendly by supplying design time data.
  • The Metro design language (look and feel of WP7 applications)

 

To best illustrate these concepts I’ve built a full Windows Phone 7 application that lets you monitor arrivals and departures from any Norwegian airport. The application consumes a set of REST services exposed by Avinor that lets you look up arrivals and departures for a given airport. I’ve made the entire application available on GitHub as open source, and I do plan to polish it enough to actually publish it on the app marked place as soon as the WP7 is released.

Screenshot

Most sessions from NDC2010 where recorded, and can be downloaded from the Tandberg streaming server or as a complete torrent with all the sessions. I’ve also uploaded my session to Vimeo (for my personal video archive), and to make it easier to embed it on my blog.

Silverlight Applications for Windows Phone 7 from Jonas Follesø on Vimeo.

The slides are available on Slide Share, and the source code is up on GitHub. I do plan to update the code as new versions of the WP7 platform is released, and hope the application can serve as a good example of how to architect a WP7 application.

Thanks to everyone who showed up for my session, and for the great feedback on Twitter, in person and through the conference evaluation system. Thanks to everyone I meet during the conference that I got a chance to talk to – it’s amazing how many talented people you meet at a conference like NDC. Also big thanks to the people behind NDC – they did an amazing job and I’m truly looking forward to next year’s conference!

 WindowsPhone7

Over the weekend I have had tons of fun playing around with the Windows Phone 7 Developers Tools. The platform looks awesome, both from an end user perspective as well as a developer perspective.

One of the scenarios I’ve been exploring involves some simple multitouch pinch and zoom gestures. It’s fairly simple to add custom touch functionality by subscribing to the Manipulation Events hanging off all UIElements. If you got a touch enabled Windows 7 computer you can even test multitouch directly in the emulator. However, I was a little bummed when I read that, unlike the Surface SDK, simulating multitouch input using multiple mice was not supported:

“The Windows Phone Emulator does not support multitouch input through the mouse, so you must test scale transforms on a development computer that supports touch input, or test on an actual device.”

This is not entirely true. When I read this I remembered this cool blog post from Szymon Kobalczyk on emulating a multitouch device in Windows 7. In his post Szymon talks about the MultiTouchVista project. It’s an open source piece of software that lets you install a Windows 7 touch driver. The driver talks to a multitouch service that can read input from multiple sources and turn them into standard Windows 7 multitouch events. Sources for input include things like multiple mice, web  cameras and Wii remotes. Since the MultiTouchVista application appears as a standard Windows 7 touch driver it will work in any Windows 7 touch-enabled application, like the Windows Phone 7 emulator.

For detailed installation instructions, check out the projects official CodePlex site. I have recorded a quick demo showing multitouch in Silverlight 3, MS Paint and the Windows Phone 7 emulator using two mice connected to my iMac.

Emulating Multitouch on the Windows Phone 7 Emulator using multiple mice from Jonas Follesø on Vimeo.

Last year I gave a presentation on the MVVM design pattern at the Norwegian Developer Conference. Most of the presentations from NDC2009 was recorded and made available online, including mine. However, the user experience of the video content on the NDC site isn’t the best. Playing a video requires multiple clicks, and the videos are only available in WMV format.

The feedback I’ve gotten on the presentation is so good that I decided to make it a bit more discoverable by uploading it to Vimeo. In addition to the MVVM presentation I have also uploaded my lightning talk from Smidig 2009 (in Norwegian) as well as my Silverlight talk from TechEd New Zealand 2008.

If you want to watch all the content from NDC2009 you can download it nicely packaged as one big torrent file. Oh, and I haven’t made an announcement on the blog yet, but I will be speaking at this year’s NDC.

MVVM Design Pattern NDC2009 from Jonas Follesø on Vimeo.

There has been lots of talk in the Silverlight community about what is the best way to implement the INotifyPropertyChanged interface. During Christmas I blogged about how you can use dynamic proxies to get INPC implemented automatically. Since then both Einar Ingebrigtsen and Justin Angel have blogged about an interesting approach to INPC using MSIL weaving. I really recommend checking out Justin’s post, as he covers some of the pros and cons of different INPC implementations, as well as purposing an elegant solution using post-build MSIL weaving.

One of the things Justin mentions as a drawback of the dynamic proxy approach is that you cannot simply new up your ViewModel directly and get change notification automatically. You have to explicitly create the ViewModel instance through a proxy creator. Einar also mentioned that he had a hard time finding a way to integrate the proxy creator with an IoC container.

When I write code I’m always careful about where I instantiate my objects, and lately all projects I’ve worked on have used some sort of IoC container. Having an IoC container gives you a single place in your code base to create- and register objects. If the dynamic proxy implementation of automatic INPC is going to be useful it has to be as simple requesting a ViewModel instance from the IoC container. In this blog post I’m going to show how you can combine automatic INPC using dynamic proxy with the Ninject IoC container.

If you have read my blog you may have noticed I got a soft spot for Ninject. I mean, who cannot love a framework whose name, graphic profile and code examples are all about Ninjas? When I first set out to integrate my automatic INPC interceptor with Ninject I wasn’t quite sure where to start. Ninject 1.0 had AOP concepts built in, but in 2.0 (which are under development) this has been moved out of the core and into a separate interception extension module. This is part of the new modular design of Ninject 2.0. Features you may not need all the time are moved out to separate extensions, leaving the core really small and simple (~90kb).

ninject-ninja

My first plan was to use the Ninject interception extension. The extension uses the LinFu framework for dynamic proxies, and I wasn’t sure how to get my Castle Dynamic Proxy based implementation to work directly. I later got contacted by Ian Davis, the owner of the interception-extension project. He asked if I needed some help getting automatic INPC working with Ninject. After some back-and-forth on Twitter Ian had an implementation of automatic INPC added to the Ninject.Extension.Interception project. The code is commited to the trunk, and is available on github if you want to check it out. Ian’s implementation is probably worth a blog post on its own.

A comment from Miguel Madero pointed me in the right direction to get my interceptor working with Ninject. Miguel had integrated it himself by implementing the interceptor as a Ninject Provider. Ninject lets you register types against providers which let you write code that creates the instance when the type is requested from the container. The interface is really simple, having one Create-method. In this method you have to create the instance being requested.

The implementation for the automatic INPC provider is fairly simply. It finds the largest constructor of the ViewModel being requested, creates instances of all constructor parameters, before calling the dynamic proxy creator I implemented in my previous two blog posts.

ProviderCode

In Ninject all configuration is done through code using an internal DSL. You configure the container by creating module classes specifying the bindings of the different types you want to be able to create. In this example I have a simple logging service (to demonstrate constructor injection combined with automatic INPC) as well as a simple ViewModel. The ViewModel is bound to the provider, which will call the proxy creator when the ViewModel is requested.

ConfigurationExample

This unit tests shows how to request an instance of the ViewModel from the container. When the Name-property is set the ViewModel will log the action to the fake logger which was injected into the ViewModel constructor.

ExampleUnitTestOfViewModelFromKernel

Having to register every single ViewModel against the provider is tedious and repetitive. Miguel Madero also suggested that you can override the GetBinding method of the Ninject StandardKernel and use convention over configuration. By overriding the GetBinding method we can check if the type being requested is a ViewModel, and if it is we can create a binding on the fly tying the ViewModel type against the automatic INPC provider.

The implementation of the AutoNotifyKernel is really simple. It checks if the name of the type being requested contains “ViewModel” and implements the IAutoNotifyPropertyChanged interface. If it does we create a binding for the type.

AutoNotifyKernel

Having a convention based approach in place we do not have to manually register every single ViewModel.

Some of this code might seem complicated, but I really wanted to cover the details of how to integrate it with Ninject, as similar approaches probably work for other containers. Once you got a framework for automatic INPC in place the usage becomes really simple. In the example application for automatic INPC the code needed to implement the ViewModel, configure the container and tie the ViewModel to the View looks something like this:

FullExample

It’s funny how such a simple interface can trigger so many different implementations. I hope you found my blog post on combining a dynamic proxy approach with an IoC container useful. It will be interesting to see which approach emerges as the most used, and which frameworks that will provide implementations of the different techniques.

Yesterday I published a post showing how we can use AOP and Castle Dynamic Proxy to get automatic change notification for ViewModels by intercepting property setters. One of the comments I got was from Krzysztof Koźmic who suggested that I should use ProxyGenerationHook to narrow down the scope of the proxy.

By implementing the IProxyGenerationHook we get to choose which methods to intercept. In my original implementation this logic was handled by the interceptor itself. The interceptor would check that the method being intercepted was indeed a property setter, that it was not of type ICommand, and that it was not marked for exclusion. By implementing a ProxyGenerationHook I could move all this code into a separate class, making my interceptor much cleaner. The ShouldInterceptMethod implementation of the ProxyGenerationHook now looks like this:

ProxyGenerationHookCode

I also got a good question from Anders Knutsen asking how to handle change notification for properties depending on another property. A typical scenario for a ViewModel might be to have a ZipCode-property with both setter and getter, and City and State properties with only getters. When you set the ZipCode you raise change notification for ZipCode, City and State. In the City- and State-getter you look up the values based on the ZipCode. This means that you must be able to raise multiple change notifications in a single setter.

I solved this by adding a new NotifyChangesFor-attribute that you can decorate properties with to trigger change notification for additional dependent properties.

NotifyChangeForAttributeCode

I have also updated the tests to document this behavior.

NotifiyChangesForTestCode

The sample code has been updated with the new ProxyGenerationHook and the new NotifyChangesFor-attribute.

As a WPF or Silverlight developer chances are you have implemented the INotifyPropertyChanged-interface more than once. The interface is simple enough, consisting of a single PropertyChanged-event. The data binding infrastructure in WPF and Silverlight will look for this interface and subscribe to the PropertyChanged-event. As a developer you have to write code in your property setters to raise the event whenever some property is changed. This is boring and repetitive code to write, that often contains magic strings (property names) and can really clutter your ViewModels. Finding an elegant implementation of the INotifyPropertyChanged-interface has become one of the holy-grails of WPF and Silverlight developers.

An idea I had some time back where to use AOP-techniques and dynamic proxies to get INotifyPropertyChanged implemented automatically. With the recent beta release of Castle Dynamic Proxy 2.2 with official support for Silverlight, combined with Christmas holiday, I figured this would be a good time to take a stab at this problem.

After doing some research I found a couple implementations of INPC using AOP. In August 2008 Gian Mari Ricci published two blog posts about automatic implementation of INPC. The first one he used Reflection.Emit and dynamic code generation, the second was a much simpler implementation using Castle Dynamic Proxy.

In June Ray Houston published an interesting post on how they had implemented auto wiring of INPC as part of the Fluent Silverlight framework. Fluent Silverlight is an open source framework by Ray Houston and Gabriel Schenker that provides a fluent interface for configuring data binding in a strongly typed manner using C#. Their implementation of automatic wiring of INPC is based on Castle Dynamic Proxy, and is really simple and elegant. Instead of trying to reinvent the wheel I decided to re-implement the automatic INPC parts from Fluent Silverlight, and walk you through the code in this blog post. I do not want to take credit for Ray and Gabriel’s work, and must emphasize that this should be considered a walkthrough of their implementation.

The first part of the implementation is a new IAutoNotifyPropertyChanged interface that extends the INotifyPropertyChanged interface with one new method. This interface will be implemented for any ViewModel where we want automatic change notification. The interface serves as both a marker interface for the interceptor, as well as providing a method that the interceptor can call to raise the PropertyChanged-event.

IAutoNotifyPropertyChanged Code Example (code download attached)

To create a new ViewModel we simply implement the interface, and make any property we want change notification for as virtual. The properties need to be virtual so that the generated proxy class can override the property setter method and call the interceptor. The implementation of the interface can off course be moved down to a base class, but I have included it in this sample to make it clear what is required by the ViewModel for automatic change notification.

PersonViewModelCode

With a ViewModel implementing the IAutoNotifyPropertyChanged-interface in place we can now write an interceptor that will add change notification for the properties on the ViewModel. Interceptors are a concept from AOP that enables us to intercept method calls and add new behavior dynamically. This is helpful as we can move cross-cutting concerns out of the business logic. Typical use cases for AOP often include authentication, logging, exception handling and other technical concerns. By having these concerns implemented outside our class we can keep our business logic nice and clean. In our case we are going to apply some of these techniques to keep the ViewModel free from change notification code cluttering the class.

The interceptor is defined as a generic class that intercepts classes implementing the IAutoNotifyPropertyChanged-interface. The interceptor implements IInterceptor-interface which defines a method that will be called for every method invocation, providing us a hook to add addition behavior to the method call. Our interceptor will start by letting the original method call (the property setter) run before checking if we should raise change notification. If the property being set isn’t marked for exclusion we call the OnPropertyChanged method on the IAutoNotifyPropertyChanged-interface, passing in the property name as the parameter.

InterceptorCode

The code to determine if we should raise change notification starts by checking if the method being invoked is in fact a property setter. This is done by checking the IsSpecialName-property on the MethodInfo object, as well as checking that the name of the method starts with “set_“. The second step is to check if the property is marked with a DoNotNotifyChanges-attribute. This is a marker attribute that can be applied on properties to prevent automatic change notification. The third step is to check if the property being set is of type ICommand. A common pattern when creating ViewModels is to expose operations as Commands hanging of the ViewModel as properties. You do not need change notification for commands, so they are ignored by the interceptor.

ShouldSurpressCode

Now that we have our change notification interceptor the only thing missing is a way to create the proxy object. To do this we create a new proxy creator. The proxy creator has a generic method that creates proxied instances of any class implementing the IAutoNotifyPropertyChanged-interface.

ProxyCreatorCode

This diagram illustrates how the View calls the property setter on the proxied ViewModel. The property setter gets intercepted, and the interceptor lets the original setter execute before raising the PropertyChanged-event.

AutoINPCDiagram

Now that we got the proxy creator it is really straight forward to create an instance of our ViewModel that will have automatic change-notification. I have included the tests documenting the behavior of the automatic change notification interceptor. The tests documents change notification for simple properties, as well as exclusion of commands and properties marked with the DoNotNotifyChanges-attribute.

AutoINPCTestsCode

Summary

Using dynamic proxies for automatic change notification is a good way to keep your ViewModels nice and tidy as well as not having to hand-write tedious, repetitive change notification code. In my next blog post I will explore how we can integrate the change-notification interceptor with the Ninject IoC-container. By integrating the interceptor with an IoC-container we can have any ViewModel retrieved from the container support automatic change notification.

For more information about Castle Dynamic Proxy I would recommend Krzysztof Koźmic excellent 15-part tutorial.

The example code for this blog post requires Silverlight 3, and includes the latest beta of Castle Dynamic Proxy 2.2. The code is experimental, and not intended for production use.

For me agile software projects is all about maximizing the customers’ value of the software being built by encouraging and incorporating feedback, new features and change requests as quickly and cheaply as possible. To achieve agility we adopt agile project process like Scrum, which helps us manage and prioritize the features of the software we are building into short iterations. To build a flexible code base that enables us to quickly add, remove or change features throughout the project we adopt agile development practices like Test Driven Development. We try to follow good design principles like SOLID, and we build and integrate our code frequently using Continuous Integration. But what can we do to become more agile in the way we build the User Experience (screen layout, navigation structure, colors and graphic design, imagery, error messages, texts and labels) of our application?

On most of the software projects I have worked on the User Experience have been left up to the developers to decide. Towards the end of the iteration we bring in the customer for a demonstration of what we have built, implemented as running HTML, Windows Forms or perhaps XAML code. In many cases the customer immediately starts focuses on the tiny (perhaps unimportant) details of the UX. Like, “the title should be bigger and bluer”, or “the save button should be 4 pixels to the left”. One of the reasons for this reaction might be that by demonstrating a complete implementation of the UX straight away the application looks too complete, and the customer might feel that it is too late in the project to make substantial changes to the UX of the software. However, if this does not happen and we do get good feedback, suggesting that we need to rethink the UX of the application, the reaction from the development team might be hesitation. If you have put lots of effort into building the UX of the application you don’t want to throw it away. And in contrast the business logic of the application we do not have the same refactoring and testing support for the UX of our application as we do for the other parts of the system, making it harder to make big changes with little effort.

One way to work efficiently with UX in an agile software team is to create low-fidelity prototypes. These prototypes can be created using pen and paper, or tools like Visio, PowerPoint, Balsamiq or SketchFlow. Low-fidelity prototypes feel less finished, but are at the same time concrete enough for the customer to really “get” the concepts being prototyped. Using low-fidelity prototypes the customer is more likely to give constructive feedback about the important aspects of the UX, like how the screen layout and navigation should work, which fields are needed, or how we are going to display error messages, than if they were presented with a high-fidelity prototype or near complete version of the software.

paperprototype Oppsett

The developers are going to be less attached to a low-fidelity prototype, as the amount of effort put into it is far less compared to a real implementation done in code. Using prototyping the development team and the customer can do multiple iterations trying out different ideas and concepts for the UX, hopefully coming up with a great solution in the end. After all, good design is all about exploring multiple ideas, before narrowing it down to the right design for the problem. Good design is not about picking the first solution that pops into a developers mind.

I think UX prototyping fits perfectly with agile software development, and should be a natural tool for any agile team building software that interacts directly with end-users. My next blog post is going to be more concrete, giving an introduction to two great prototyping tools: Balsamiq and Microsoft SketchFlow.

The videos from NDC2009 are now published on the conference agenda site. The site isn’t the easiest to navigate, so Mark Nijhof went through the effort of creating a simple list of all the videos grouped by speaker. There is tons of great content available and the videos should be a great way to do some (relaxed) learning in the summer heat.

There is a problem with some of the links, and the link to the video of my second talk on .NET RIA Services is broken. I’ll make a new post when that video becomes available.

JoansGivingMVVMTalk 

Click to view my Model-View-ViewModel presentation from NDC2009.

Earlier this month I was lucky enough to both attend and speak at the Norwegian Developer Conference 2009. What a blast! The NDC09 featured a perfect mix of content – everything from the latest in technology, to the core principles of software craftsmanship and agile development. The speaker lineup this year was AMAZING, and I feel humble to be invited among such a group of incredibly talented people. Hopefully I was able to keep up with the level of the rest the speakers.

JonasAndHaack

I gave two presentations at NDC09; one on the MVVM design pattern (more easily referred to as View Model) and one on .NET RIA Services. I think both talks went well – with the View Model talk being the strongest one, as this is something I’ve been presenting on many times before.

I’ve uploaded both the slides and the demos from my talks. The MVVM demo is basically a the Dive Log example application taken further, with multiple View Models communicating through an Event Aggregator and a touch of navigation using the Silverlight 3 navigation framework. The .NET RIA Services demo is a “plain” data centric application, as well as a second demo app which uses nHibernate and the XML Metadata Provider (something I have to revisit in a later blog post).

In addition to the technical content delivered at NDC09 it was great fun to hang out with old and new friends. Here are some of the highlights: Had some great conversations with Glenn Block about different aspects and approaches to the View Model pattern. Got to catch up with Andrew Browne, a good friend from the Melbourne developer community. Had dinner with Carl and Richard from .NET Rocks, Udi Dahan and Capgemini colleagues. Had tons of good conversations with fellow Norwegian developers. Went fishing with Tim Huckaby.

Thanks to all the speakers, organizers and attendees for making NDC2009 such an awesome event. Hope to see you all back there next year!

MVVM Design Pattern for Silverlight Applications

DiveLogMVVMScreenshot

Download slides:

Download demo

For a collection of more resources check out my MVVM tagged links on Delicious.

.NET RIA Services

Download slides

Download Fishbook Demo

Download Fishbook nHibernate Demo


For more resources check out my .NET RIA Services tagged links on Delicious, as well as the talk “.NET RIA Services - Building Data-Driven Applications with Microsoft Silverlight and Microsoft ASP.NET” and “Building Amazing Business Centric Applications with Microsoft Silverlight 3” from MIX09.

Wow. Friday 20th of March and MSDN Live Winter 2009 is now history. I delivered my last two talks on Silverlight during this round of MSDN Live in Oslo yesterday. Over the last two and a half week the MSDN Live road-show have visited Stavanger, Bergen, Trondheim and Oslo. It has been a great experience, and I’ve gotten to meet some interesting developers around the country. It has been great to hear how many people are starting to adopt Silverlight and WPF for their rich client applications, and I’m certain this trend is only going to continue.

As promised this blog post contains links to the Dive Log example application (which will be updated to Silverlight 3 shortly), as well as links to more information relevant to the two sessions I gave during MSDN Live. I've also included a Flickr Photomentury by Rune Grothaug showing a full day of MSDN Live.

Model-View-ViewModel

My first talk at MSDN was about building business focused applications using Silverlight 2. Throughout the talk I demonstrated how the MVVM pattern can help you achieve separation of concerns, and thus giving you more flexible, testable and designer friendly code. Some links to more information:

Silverlight Tips & Tricks

My second talk at MSDN was 6 different Silverlight Tips & Tricks showing how to solve some of the not-so-obvious problems in Silverlight.

  • Recompressing the XAP file to save download size
    A Silverlight XAP file is just a standard ZIP file. By recompressing it with you can save up to 25% download size. During my talk I demonstrated the ReXapper tool, which can be easily integrated to your project as a post-build command.
  • Deep linking in Silverlight applications
    Linking is a core concept of the web. With Rich Internet Applications in AJAX, Silverlight and Flash this becomes a challenge, as we no longer have different pages for each piece of information or screen in the application. Instead we load the application once, and then dynamically load pieces of information without navigating to a new page. This breaks the concept of linking, booking marking and back/forward navigation in the browser. To solve this we need to manually manage history state. In my blog post I use ASP.NET AJAX to solve this. Robby Ingebretsen has another approach using jQuery to manage the browser history.
  • Printing in Silverlight
    Silverlight looks great on screen but does not have a good print story. Printing in Silverlight can be solved by opening a new window showing a server-side rendered report, or you can use the HTML Bridge to generate a client side report.
  • Testing in Silverlight

Hopefully you enjoyed this round of MSDN Live and got a good introduction on how to build Silverlight 2 applications. If you have any questions related to the presentations feel free to post them in the comments section. The code and slides are available as downloads from my SkyDrive (embedded in the blog post).

Dive Log and Flickr Demo Slides for both presentations

I know. It’s been too long since my last post, and just to clarify; I’m not dead, nor have I been eaten by sharks or anything like that. I’ve just been busy rebooting my life back in Trondheim after coming back from Australia. I started working again in Trondheim in the beginning on January and went straight back on to a Windows Forms/WPF project I helped start up back in September 2007. It has been really fun to see how the code base has evolved over the year I’ve been gone. After getting back on the project I’ve spent most my time developing WPF components inside the Windows Forms client. It’s been an interesting experience, and I’m really happy with how well WPF integrates with existing Windows Forms applications. I will definitely be blogging about some of my experiences around WPF and Windows Forms in the weeks to come.

However, the main reason for the slowdown in posts is not work related. Hege and I just bought an apartment, and ever since we moved in all available time have gone to painting walls, shopping for furniture and all kinds of other things you need to get in order when moving into a new place. We are really happy with the apartment, and things are really starting to shape up. We finished painting the last room this weekend. I will be posting a “tour of the geek crib” once all the tech stuff (fun stuff) is in place.

Okay – enough excuses for not blogging. The more topic of this blog post is that I’m doing a series of talks on Silverlight 2 during the MSDN Live tour. First stop of the tour is Stavanger (05. March), before moving on to Bergen (10. March), Trondheim (12. March) and finally Oslo (19. March). I will be giving two sessions, one on developing data centric/business focused Silverlight 2 applications (similar to my Tech Ed Talk), and one on Silverlight 2 tips and tricks. The tips and tricks session will be 5-6 covering things like printing, deep linking, search engine optimization, design time support, continuous integration etc.

I’ve included the session abstract (in Norwegian):

msdnliveForretningsapplikasjoner i Silverlight 2
Silverlight 2 ble lansert nå i høst og legger et godt grunnlag for utviklere som ønsker å lage rike internett applikasjoner (RIA) basert på .NET. I denne sesjonen går vi i dypden på Silverlight 2 som utviklingsplattform og fordelene ved å velge Silverlight 2 som plattform for data-sentriske forretningsapplikasjoner. Sesjonen vil blandt annet dekke dataaksess via sikrede WCF tjenester, hvordan strukturere koden ved hjelp av Model-View-ViewModel patternet (MVVM), hvordan skrive kode designere kan jobbe med, og enkle Blend-tips for utviklere. Sesjonen vil bygges rundt en dykkeloggapplikasjon hvor koden vil bli gjort tilgjengelig etter presentasjonen.

Tips og triks for Silverlight 2-utviklere
denne andre sesjonen vil vi bygge videre på dykkeloggen og fokusere på en del konkrete tips og triks for Silverlight 2-utviklere. Tett integrasjon med nettleseren er viktig for en best mulig brukeropplevelse. Vi vil blant annet se på hvordan integrere med fram/tilbake knappene i nettleseren, hvordan optimalisere Silverlight applikasjoner for søkemotorer, hvordan bruke dyplenking i Silverlight og hvordan håndtere utskrift fra Silverlight. Presentasjonen vil gå i dybden på blant annet HTML-bridgen som brukes for å integrere Silverlight med JavaScript som allerede kjører på siden, eller for å aksessere nettleserens DOM.

One of the sad things about this round of MSDN Live is that Microsoft have to charge for it. Previously MSDN Live have been a free (and really popular) event, but Microsoft is feeling the financial crisis just like everyone else. So in order to be able to deliver MSDN Live this time they had to charge for it. Børge Hansen from Microsoft Norway and Jon Torresdal from NNUG Bergen have shared their thoughts on this decision. I was really bummed about this decision myself, but I really hope that you find the content presented at MSDN Live interesting, and that you get a chance to attend.

Since this post is about upcoming speaking engagement I figure I could finish the post by sharing a time lapse video of a Silverlight 2 presentation I did last week at the local university. The time lapse is created by Pete J Samuel, a colleague of mine at Capgemini Trondheim.

Hope to see you at MSDN Live in Stavanger, Bergen, Trondheim or Oslo!

One of the big themes of PDC this year was Windows Azure and Microsoft’s cloud computing initiative. Live Services is one of the building blocks of Windows Azure, and includes a set of services known as Live Mesh. I did a blog post about Live Mesh back in April when it was first announced. With lots of enthusiasm I speculated about how this would enable us to build offline/desktop enabled Silverlight applications. During the second day keynote Scott Guthrie, coding hero and vice president at Microsoft, announced that;

...in a few minutes you will learn about how you can actually run Silverlight both inside the browser and now outside the browser…
Photo by DBegley - check out original on Flickr

This announcement immediately caused a lot of buzz in the Twitter-sphere. What made the announcement even more interesting is that a lot of people didn’t quite get what Scott was talking about, or if they even showed Silverlight running outside the browser at all. So what was the Silverlight out-of-browser story at PDC? After Scotts keynote Anthony Rose entered stage and demoed their BBC iPlayer. He didn’t explicitly say that this was the “Silverlight running on the desktop”-story, but what he was showing was the iPlayer implemented as a Mesh-Enabled Silverlight application running on the desktop!

Anthony Rose
Photo by DBegley - check out the original on Flickr

In this blog post I’m going to show how I Mesh-enabled the Dive Log application using the Live Framework. I will also try to cover some of the benefits of using Live Mesh as an application platform for web application.

Where do you start?

To build Mesh-Enabled Web Applications you need access to the Live Framework SDK and Tools. The SDK is currently only available in a private CTP, and to get access you need to apply for a token through the Microsoft Connect site. I don’t know how many people they will let in on the CTP, or how long the process of getting a token takes.

Once you have downloaded and installed the SDK you get a new project type called Live Framework, which comes in two flavors; “Mesh-enabled Web Application” and “Silverlight Mesh-enabled Web Application”. The difference is that the first one is for writing JavaScript and HTML based Mesh-applications, while the second is for Silverlight applications that use the Live Framework libraries.

Live Framework Project Type

After selecting the “Silverlight Mesh-enabled Web Application” template you get a new solution with two projects; a Silverlight 2 project and a Live Framework project. The Live Framework project has a reference to the Silverlight project, and contains a simple HTML and JavaScript file to embed the Silverlight application on the HTML page. The project also contains an icon for the application, and an XML manifest file describing the application. The Silverlight project has references to two new assemblies; Microsoft.LiveFX.Client and Microsoft.LiveFX.ResourceModel. These are the Live Framework libraries that give you a managed API for Live Services. All Live Services are based on open protocols and standards like HTTP, ATOM, FeedSync and RSS, so you could write applications without these libraries, in any language or platform you like, but Live Framework makes it allot easier by providing a nice abstraction layer on top of the web services.

Live Framework Project Structure

Mesh-enabling the Dive Log application

meshappsicon The first thing I did after creating a new Live Framework project was to remove the automatically generated Silverlight 2 project. Instead I included my existing Dive Log Silverlight project and referenced the Live Framework Silverlight assemblies.

The Dive Log application was originally written as a demo for my TechEd talks back in September. One of the things I wanted to demonstrate was how to use the Model-View-ViewModel pattern in a Silverlight application, and how this can make your application easier to design in Expression Blend. The way I did that is to use dependency injection to inject a mock-implementation of any external dependencies, like web service proxies, into the view model. That way the mock service can generate sample data when the code is being consumed in Expression Blend. When the application is running in the browser the real web service will be used.

The benefit of this design is that I can easily configure my inversion of control container to use different implementations of different application services. So to first run the Dive Log application inside Live Mesh I simply configured the IoC container to always use the mock implementation of the web service. That way I could deploy my application to Live Mesh without having to prepare my web services for cross domain access.

After TechEd I have extended the Dive Log application with new features like printing support and support for back- and forward navigation in the browser. These features depend on the ASP.NET AJAX client library to be available on the page hosting the application. For my Mesh-enabled Dive Log I can’t depend on these libraries to be present, and I guess they don’t make sense when the application is deployed on the desktop anyway. So to disable these features I simply made an empty implementation of the IPrintDives and IManageHistory interfaces and configured my IoC container to use these to handle browser history and printing.

IoC container configuration code (available in download)

Once the application was configured to use the mock web service, and to disable printing and history, I could simply hit F5 to build and deploy the application to Live Mesh. The Live Framework project template includes a build task that will connect and deploy the application to Live Mesh. Currently there is no local development environment for Mesh-enabled web applications, something that can be a little bit bothersome as you have to redeploy the application to Live Mesh every time you make a change.

Application beeing deployed to Live Mesh

Mapping the Dive Log against the Live Framework Resource Model

The next step of Mesh-enabling the Dive Log application is to use the Live Framework Resource Model as the data storage for logged dives. The original application uses a web service to store dives remotely. This diagram shows a high level overview of the Live Framework Resource model. The blue boxes indicate the main components the Dive Log application will use.

Live Framework Resource Model Diagram

As I mentioned earlier the web service is an external dependency that is injected into the View Model using an IoC container. A trick I’ve used on many projects is to extract an interface defining the methods and events used on the web service client class. I then use a partial class to implement this interface on the automatically generated web service client class. This enables me to implement multiple versions of the interface, for instance for design time data or unit testing. This design enables me implement a new service that reads and writes dives to the Live Framework Resource Model. A simple configuration change of the IoC container will inject the Live Framework based service to the View Model. That way I don’t have to change any code in the UI or the View Model to use Live Mesh as my data storage.

IDiveLogServiceClient Diagram

The next challenge I faced was figuring out how to map my Dive Log application against the different concepts of the Live Framework Resource Model. After reading about the resource model my initial idea was to create one Mesh Object for each Dive Log, and then start adding items to a Data Feed. When I tried to create a new Mesh Object from my Silverlight application I got some weird exceptions. After discussion this on the Live Framework forum I learned that Mesh-enabled web applications don’t have permission to create new Mesh Objects. After some more trail-and-error, as well as watching sessions Live Framework sessions from PDC I came up with the following mapping of Dive Log concepts against the Live Framework Resource Model:

Dive Log to Live Framework Resource Model Mapping Diagram

The Mesh Object is the level of granularity for sharing, synchronization and authorization. In fact each instance of a Mesh-enabled web application is in itself a Mesh Object. This means that each Mesh-enabled web application got access to a single Mesh Object; the object representing the application instance. This enables you to share application instances with other users, and the Live Framework Client will synchronize the Mesh Object (application instance) across your devices. If you want to create two dive logs, one for hobby dives and one for professional dives, you simply create two application instances. This would create two Mesh Objects, one for each instance, which you could shared with other users and synchronize across devices. The following diagram illustrates the application sharing model. Each instance is a Mesh Object shared with another user, and both the application and its data get synchronized between users.

Live Framework Application Sharing Model

Coding against the Live Framework Resource Model

After working out how to map the Dive Log against the Live Framework Resource Model the next step was to write the actual implementation of the storage service. This was fairly straight forward as the Live Framework provides a nice API to work with the Live Services. In fact the complete implementation of the Live Framework backed storage service was less than 200 lines of code. One of the changes I had to make to my Dive-object was to add a new Mesh ID so that I could map Dive-objects against Sync Entry objects. When the user clicks the save button the code will create a new Sync Entry object and set the Dive-object as the user data. This enables you to serialize custom objects into a Mesh Sync/Data Entry. Both Sync- and Data Entries hang of a Data Feed. The main difference is that Sync Entries is the implementation of the Feed Sync standard. This helps you deal with synchronization of data across devices. This is helpful since multiple users could be writing data to the same application instance, some who might be offline and only synchronize data back into the cloud at a later stage.

The following piece of code shows the implementation of the save method. The code will iterate over each dive being saved and check if it has been changed. If the object is changed the code will see if it can find a Sync Entry matching the Dive. If it finds a Sync Entry it will update the object by calling SetUserData. If no Sync Entry can be found a new one is created and the dive object is stored by calling SetUserData on the new Sync Entry. Finally the Synchronize method is called on the Data Feed. This will push any changes made locally back into the cloud, as well as read any new objects added remotely by other users/devices.

Synchronizing dives back to Live Mesh

Benefits from Mesh-enabling the Dive Log application

Mesh-enabled web applications are a new type of applications. They are developed using web techniques like HTML, CSS, JavaScript or Silverlight, but can be deployed to the Live Mesh, and executed both inside the browser and on the desktop. This new application model opens up several new scenarios, and I think the Dive Log is a good example of an application that can benefit from being Mesh-enabled.

Screenshot of Dive Log Mesh on desktop

  • No need for server infrastructure
    As an application developer I can release the Dive Log application to the world without having to worry about server infrastructure. The application is deployed to Live Mesh, and all data is stored in the cloud. The user is in control of its own data and, and all dives are stored in an open ATOM based format that can be read by other applications.
  • Don’t have to worry about authentication and authorization
    I don’t have to worry about authentication, user management and authorization. All this is handled by Live Mesh and the Live Framework. The user authenticates using their Live ID, and authorization is managed by setting permissions on the Mesh-enabled application.
  • Transparent offline and online support
    My Dive Log application can work both offline and online. This is a big deal as a user might be interested in logging dives on his laptop onboard a boat far at sea. This would be hard to do in traditional web applications. With Mesh-enabled web applications the application is synchronized to the laptop, and any data added offline will be synchronized back into the cloud when a connection is available. The best thing is that you as an application developer don’t have to worry about it. The Live Framework client libraries will detect if the user is offline or online, and use the correct service endpoint (remote or local).
  • Making the Dive Log application social
    By Mesh-enabling the Dive Log application I get access to a big social network. Users can share their Dive Logs with friends, invite other users to use the application, and share news stories as the log new dives.

These are just some of the benefits from Mesh-enabling the Dive Log application. I think Live Mesh and Live Services are going to be an interesting application platform to watch as it matures. Currently the benefits for consumer based applications are obvious. It will be interesting to see if this platform can provide value for more business focused applications.

Download the Mesh-enabled Dive Log application

I have uploaded the source code of the Mesh-enabled Dive Log application. It is a simple Silverlight 2 application without the Live Framework project. You need to download and install the Live Framework SDK separately and then create a new Mesh-enabled Silverlight Project. Follow the steps described earlier in this post and add the Dive Log Silverlight application to your Live Framework project.

I have also published the Dive Log application to Live Mesh if you just want to run it as an end-user. You need to use the Live Mesh Tech Preview online environment, as well as download the Live Mesh Tech Preview client (if you want to run the application from your desktop and not only inside the browser).

I had originally planned that my Silverlight Designer & Developer Network presentation was going to be the last one I gave in Australia before flying back to Norway. But then me and Hege decided to do some traveling before going home, and we’re currently up in Byron Bay enjoying some diving and surfing. Wednesday we fly down to Sydney for a couple of days, and my good friend Adam Cogan asked if I could give a Silverlight talk at the Sydney .NET User Group. Off course I said yes – so Wednesday evening (December 10th) I’m giving a talk on business applications in Silverlight. The title and abstract goes as follow:

Building data-centric applications in Silverlight 2
In this presentation you will get a overview of how to build data-centric (line-of-business) applications in Silverlight 2 using LINQ to SQL and WCF on the server. The presentation will cover how to deal with authentication for your WCF services from a Silverlight application, tips on how to architect your Silverlight application, and how to build flexible, testable code your designers can work with. You will also get a sneak preview of an application framework Microsoft is working on to make building business applications easier.

For registration, time and location check out the Sydney .NET User Group web site. I expect the details to be published some time over the weekend.

While in Sydney we’re going to stay at our favorite accommodation in Coogee, which is going to be great. We plant to finally see the opera house (I’ve been to Sydney multiple times for work, but have never actually seen the building!). Friday we fly down to Canberra to spend the weekend with a friend, before flying back to Melbourne Monday, and then back to Norway Wednesday December 17th.

Hope to see you in Sydney!

Update: The details are now available on the SSW site and on their Facebook group.

Time and Place Date: Wednesday, December 10, 2008
Time: 6:00pm - 9:00pm
Location: Microsoft HQ, North Ryde
Street: 1 Epping Road, North Ryde NSW 2113
City/Town: Lane Cove, Australia

Last week the Melbourne Silverlight Designer and Developer Network kicked off with their first meeting. I was invited to give a talk on the latest news in Silverlight land, and any announcements made at the PDC. The first meeting turned out as a great success, with 90 people showing up for this first meeting. I focused on three things in my talk:

  1. Silverlight Toolkit
  2. Silverlight Mesh-enabled Web Applications
  3. Business Application Framework for Silverlight 2

I got some good feedback, and people where specially excited about the business application framework. It will be interesting to follow this as Microsoft starts making more information available. For now Jamie Cool’s presentation from PDC is your best source.

I’m currently working on a blog post covering how I mesh-enabled the Dive Log application, and that should be available shortly.

My presentation from SDDN is now available online, and the recording turned out quite nice. We used Camtasia for screen recording, and Philip Beadle filmed the presenters using a nice HD camera. Jordan Knight then composed all together into a nice webcast format available on the SDDN site.

Big thanks to everyone who showed up, and to Jordan, Philip and Mashesh for organizing the meeting.

The background for this article is a discussion thread on the Regional Director discussions list. One of my fellow RDs asked the question weather Silverlight 2 was ready for business applications or not. Based on my reply to the discussion Derek Hatchard asked me to turn it into an article he could publish on the "{You Shape} it" site. The article is now published, but since the {You Shape} it site doesn't support comments, and to make this article available to my subscribers who might not know of the site, I've decided to publish it on here as well. Microsoft Regional Director Rockford Lhotka has published a blog post with the same title as this article. I recommend reading it for his views on Silverlight for business applications. Rocky's post is written as a response to a Ivan Dragoev's post which suggest that the Silverlight 2 platform might not be ready for some serious business/data scenarios yet.

Introduction

With the initial release of Silverlight back in 2007 the focus was on building rich online media experiences with support for high definition video content in the browser. However, there were not many features addressing the needs of developers building data centric line of business applications. With the recent release of Silverlight 2 application developers are asking themselves if Silverlight is ready for business applications. Short answer: definitively yes! With Silverlight 2 you get the power of .NET in the browser, a rich control model, strong data binding support and a solid networking stack with support for WCF, ADO.NET Data Services and REST services. Essentially all the building blocks you need to start developing great Rich Internet Applications that solve business needs.

In this article I will try to highlight some of the strengths of Silverlight 2 as a platform for building data centric business applications, compared to traditional web applications. I will also try to address some of the challenges and concerns developers have around adopting Silverlight 2 today. Some of these concerns are around things like printing, search engine optimization, deep linking and bookmarking. All of these issues can be addressed using various techniques I will touch on in this article.

New Possibilities with Silverlight 2

I figured a good place to start would be by looking at some of the new scenarios enabled by Silverlight 2 that previously would have been impossible or really hard using regular web technologies such as HTML and JavaScript. For most developers, the greatest thing about Silverlight 2 is that you get .NET running in the browser on Windows and OS X (and Linux in the future). You can use your favorite programming language to build your application, supported by the productivity of Visual Studio 2008. You no longer have to use JavaScript to write code on the client (unless you want to). Tooling support for JavaScript was greatly improved in Visual Studio 2008 but still has a long way to go to match C# and VB.NET. Silverlight 2 supports C# and VB.NET out of the box, and you can also write Silverlight 2 applications using dynamic languages such as IronPython or IronRuby.

Having .NET in the browser lets you use the same skill set and programming languages on the client that you use on the server and provides a solid foundation for coding client side validation, business rules, and application logic.

Offline Storage of Data

Silverlight 2 supports offline storage through Isolated Storage, a protected area on the user's hard drive. Each application gets its own isolated space where it can read and write data. This can help application developers improve performance by serializing reference data to XML or JSON and stored it locally for later use. The next time the user loads the application startup time will be improved as reference data is read locally.

Another scenario where offline storage could improve user experience is by saving uncompleted forms. How many times have you accidently closed the browser before completing a web form or had to come back later to complete a form because you where missing some details? In those scenarios the application could save form values locally as the user types. If the user closes the browser and later comes back to complete the form, the application can read the form values from isolated storage.

Access to Local Files and Improved File Uploading

Security is a top priority in Silverlight 2 and there is no way you can read arbitrary files on the hard drive. However the user can choose to give Silverlight 2 access to a local file using the file open dialog. Unlike the standard HTML file input element, you can access the content of the file passed in locally. This can be used to create improved file uploaders that support multiple files at the same time with accurate progress indicators. Or you could use local file access to import and transform CSV or XML files locally before sending the data back to the server.

Multi Threading, Real-Time Networking, and Cross Domain Services

Silverlight 2 supports multi threaded programming, something currently not available in JavaScript. This allows for more complex work on the client without blocking the user interface. Examples of this could be financial calculators, complex validation logic, or other long running background tasks.

The Silverlight 2 networking stack allows real-time network communication over sockets. The client application can open a connection to the server, and the server can push data back to the client. This enables new scenarios, such as constantly up-to-date stock tickers and real-time monitoring of industrial processes or other physical equipment.

One of the limitations developers often run into when working with AJAX is calling web services from other domains than the one hosting the page. In Silverlight 2 cross domain networking is supported if the service explicitly allows this through a policy file. This enables you to call services such as Flickr, YouTube, and Amazon directly from the browser and even access web services hosted on other machines inside the enterprise.

Rich Control Framework for Great User Experiences

So far I have only covered non-visual aspects of Silverlight 2, and in fact all the features I have mentioned so far you could use in a traditional web application by hosting a non-visual Silverlight 2 application and integrate it using the HTML Bridge. But the place Silverlight 2 really shines is the presentation model. You get a control model similar to the one in WPF, and out of the box Silverlight 2 ships with the main controls you would expect like TextBox, Button, ListBox, ComboBox, DataGrid, Slider, DateTimePicker, and many more.

Having a strong set of controls is a key requirement in any data centric business application, and Microsoft has announced that they will continue to improve the Silverlight 2 control story by releasing additional controls as a Silverlight Toolkit hosted on CodePlex. The first batch of new controls will be made available at the PDC next week and will include controls such as TreeView, Expander, Label, Accordion, NumericUpDown, AutoComplete, and a couple more. This is just the first drop of controls and Scott Guthrie has hinted that they expect to ultimately have more than 100 controls available on CodePlex. If the controls from Microsoft do not meet your requirements there is already a large ecosystem of third party controls available.

All Silverlight 2 controls support data binding, making it easy to bind your user interface components against properties on your business objects. This greatly reduces the amount of code you have to write in the UI layer as you no longer have to write the repetitive code of moving values from your textboxes onto your business objects. By applying design patterns like Model-View-ViewModel you can build user interfaces with literally no code behind, making your application easier to unit test.

Strong data binding support combined with the power of .NET makes it easier to write complex validation rules on the client. This enables you to do more validation on the client side without having to do round-trips to the server to validate user input. This isn’t something new to Silverlight 2 and can be achieved using JavaScript. However, writing the validation rules in managed code is easier and more productive compared to JavaScript. In some cases you would also be able to reuse some of your business logic code between server and client. A framework like CSLA.NET can help you architect your application in such a way.

One of the strengths of the Silverlight 2 control model is the separation of visual representation and behavior. Using XAML you can redefine the look and feel of a control without losing its behavior. A slider control to set a visual indicator of air pressure in a tank can be restyled to look like a tank where you can drag content up and down. Checkboxes to set gender can be redesigned to use a male/female icon, but still keep the behavior of a checkbox. Similar things can be achieved using HTML and JavaScript, but Silverlight 2 makes scenarios like this real easy and the styling can be done by a designer without having to change the underlying code using the checkbox or slider control. The clean separation of XAML and interaction logic enables new designer-developer workflows previously hard to implement.

Visualizations and Animations

In addition to powerful controls, the Silverlight 2 presentation model has great support for vector graphics, multimedia, Deep Zoom imagery, and animations. Some might dismiss these features as something not suited for a business application. But who said a business application had to be boring? Using the vector drawing capabilities you can create graphics to visualize your business data in new ways. Already there are multiple charting and gauge controls available. Deep Zoom enables you to view gigapixel images over the Internet, opening up new possibilities for data visualization previously not possible. The Microsoft Health Common User Interface application demonstrates how a radiologist could examine and annotate x-ray imagery remotely using Deep Zoom and Silverlight 2.

Animations, when used appropriately, can greatly enhance the user experience of a traditional business application. Based on selections made by the user, animations can be applied to emphasize certain sections of the page, or to show or hide sections based on the selection. Billy Hollis recently did a DotNetRocksTV episode demonstrating a traditional business application where animations greatly help improve the user experience.

WPF Portability

Silverlight 2 uses a subset of the .NET runtime, and the presentation model is based on WPF. This allows for both code and skill reuse between platforms. Silverlight 2 is a web technology and there might be cases where you want a full desktop version of your application. Access to local resources, support for offline access, or integration with Microsoft Office could be reasons to use WPF. If you decide to make a WPF version of your Silverlight 2 application you will be able to reuse most of your business logic code directly. There are some differences in the XAML and control styling model between WPF and Silverlight 2 that you have to take into consideration when porting your user interface. Silverlight 2 uses a new Visual State Manager component to manage the look and feel of a control in different states. A checkbox, for instance, will have one look for the checked state and one look for the unchecked state. In WPF you manage different states using triggers, something currently not supported in Silverlight 2. Microsoft has announced that they will include the Visual State Model to the next version of WPF to align it with Silverlight 2. While waiting for the Visual State Model to be implemented in WPF you can use Microsoft Expression Studio architect John Gossman's implementation. This would help make portability of Silverlight 2 applications to WPF easier.

Since Silverlight 2 and WPF support the same vector graphics you will be able to reuse any graphic assets created in Expression Design or Adobe Illustrator. This is great for logos, icons, or any other illustration your designers would create for your project.

Arguably the most important piece of reusability between Silverlight 2 and WPF is skills / experience. The two platforms have so much in common that if you start out with Silverlight 2, the transition to WPF will be a lot easier. Silverlight 2 has a smaller feature set than WPF, making it a more approachable starting point.

If you want to learn more about WPF portability, I have a blog post describing the process of porting my Dive Log sample application from Silverlight 2 to WPF.

Deep Linking, Search Engine Optimization, and Printing

One question I get asked a lot is how search engines deal with Silverlight 2 content. From a business application point of view, this might not always be an issue as many applications will be hosted inside the enterprise behind password protected sites. However, there are scenarios where search engine optimization is important for Silverlight 2 business applications. One example could be an online product catalog created in Silverlight 2. I'm sure the marketing department would be rather concerned about the discoverability of their products using search engines. The two key things to think about for search engine optimization are indexability and relevance. Indexability is achieved by addressing what content is visible to the crawler and where the crawler should look. Relevance is achieved by providing deep linking to individual pieces of content so that people can link to your application.

In our product catalog example deep linking could be implemented by adding a parameter to the URL hosting the Silverlight 2 application indicating which product to load. When the Silverlight 2 application loads it could read the URL and load the correct product. This would enable users to share links directly to a specific product or add a bookmark. At the same time the web server rendering the initial page hosting the application could provide a HTML representation of the product page hidden underneath the Silverlight 2 control. The user would only see the Silverlight 2 representation of the product catalog, but the crawler could index the HTML content underneath. To help the crawler find all the products you could supply a sitemap file containing links to each individual product in the catalog. For more information on search engine optimization check out Nikhil Kothari's blog post on Search for Rich Internet Applications.

Printing in Silverlight 2

By default Internet Explorer 7 supports printing of Silverlight 2 content but other browsers such as Safari and Firefox currently don't. For our product catalog this would be a major issue. Rendering HTML content behind the Silverlight 2 control would not only improve indexability, it could also help us improve the printing experience. Using standard CSS print stylesheets, we could hide the Silverlight 2 container when printing the page and instead apply styles to show the HTML content sitting behind it. When the user browses the catalog and selects new products we could use the HTML Bridge in Silverlight 2 to dynamically upgrade the HTML content based on the currently selected product. This way the user always gets a nice looking printout in all browsers. I recently did a blog post describing this technique, as well as covering printing in Silverlight 2 in depth.

For some business applications with more advanced reporting requirements, CSS print stylesheets might not be enough. In those cases you could use the HTML Bridge to invoke JavaScript to open up a new browser window containing a server side generated report. The report could be any document, such as a PDF or XPS file, or simply an HTML page rendered on the server. Since the rendering is happening on the server you are free to choose any technology or reporting framework to create your reports.

Summary

With the recent release of Silverlight 2, now is a great time to start considering Silverlight 2 for your line of business applications. With .NET running in the browser and a powerful presentation model, you now have the building blocks needed to build compelling Rich Internet Applications for use internally or externally on the Internet. Silverlight 2 is a young piece of technology so best practices and patterns are still emerging. Thankfully the similarity with WPF gives us a great starting point, and already application frameworks like Prism and CSLA.NET are being ported over to Silverlight 2. I also expect Microsoft to start adding value on top of Silverlight 2 in terms of application frameworks, reference implementations, and sample applications.

Separation of concerns is a key principle in object oriented software design. For GUI applications the separated presentation patterns help you separate your View, Model and interaction logic. Personally I’m a big fan of the Model-View-ViewModel for Silverlight and WPF applications as it enables heavy use of data binding. However, in some cases it is useful to combine the MVVM pattern with other members of the separated presentation family of patterns.

I’ve done a fair bit of blogging about the Model-View-ViewModel pattern in a Silverlight 2 context and gotten some good feedback on that. One of the questions I get asked often is how to implement scenarios like multi page navigation, or complex user interactions like and drag and drop within a Model-View-ViewModel context. It turns out that in many cases the problem is that the developer is so focused on implementing the pattern that they fail to see alternative approaches to solve their problems. I’m as guilty of this as anyone – once you get a new hammer everything becomes a nail.

The Model-View-ViewModel belongs to a family of software patterns commonly referred to as separated presentation patterns. These are patterns that try to clearly separate the different concerns of your GUI application. In most cases they separate the View (user interface), the Model (domain and/or data model) and “something else”, which in many cases is the main different between these patterns. Model-View-Controller is one; perhaps the original separated presentation pattern, which has gotten a lot of attention lately as it is proven to be very effective in web development. The popular Ruby on Rails framework is based on this pattern, and Microsoft just released a beta of their ASP.NET MVC framework implementation. The stateless request-response nature of the web makes the MVC pattern a good fit for web applications. You may have a front controller routing an incoming web request to the correct Controller, which in turn makes a decision on what to do. The Controller may fetch some data from the Model and pass it onto a View which will render the HTML.

Another popular pattern is the Model-View-Presenter, which comes in two flavors; Passive View and Supervising Controller. This pattern has many applications and implementations. The Passive View is about reducing the View to a dumb slave driven by the Controller. The View implements a finely grained interface, with properties and methods like Name, Age, Address, without any references to UI framework specific types. The Controller drives the View by setting these properties. The benefit of this approach is that the Controller becomes highly testable, and you can reuse the same Controller in different UI environments. You may implement the View interface for different UI platforms, like web, a Windows client or even a mobile device. The drawback of the Passive View is that you may not leverage the power of the UI platform you are targeting, for instance by using data binding if you’re targeting WPF or Silverlight.

The Supervising Controller flavor of MVP lets the View deal with simple synchronization and mapping against the Model. User input and complex view logic is handled by a Supervising Controller class. This lets you leverage some of the capabilities of the UI platform by accessing the Model directly, while keeping complex code that needs unit tests in a separate class. Later I will show this pattern can be combined with the Model-View-ViewModel pattern to implement drag-and-drop behavior in a WPF application.

Flickr Uploader Sample Application

To show how the Supervising Controller and the Model-View-ViewModel pattern can be combined I’m going to create facetious Flickr Photo Uploading application. I’m not going to implement any real integration with Flickr, but rather focus on how to implement drag-and-drop of photos to upload and how this fits in with the MVVM and Supervising Controller patterns. I picked this sample because I was faced with this exact problem earlier this week on one of the projects I’m working on. It’s a WPF application where we’re using the MVVM pattern for most of it. One of the requirements of the application was support for drag-and-drop import of files from client’s computer. It was not entirely obvious how to implement this in a true MVVM way, and it turned out the addition of a Supervising Controller was a good solution this time.

I’m not going to spend too much time covering the Model-View-ViewModel pattern in depth as I have already done that earlier. I would also recommend checking out Nikhil Kothari and John Gossmans blog posts for more information about the Model-View-ViewModel pattern. However, I will briefly touch on the key concepts of the pattern. The ViewModel part of the pattern is a View-specific class that supports data binding. Each View gets its DataContext property set to an instance of a ViewModel. The different UI elements in the View are data bound to properties on the ViewModel class. The ViewModel notifies the View of any changes by implementing the INotifyPropertyChanged interface and fire the PropertyChanged event whenever the underlying Model changes, or by using an ObservableCollection<T> for collections of data. The View interacts with the ViewModel by executing Commands. For instance clicking the Submit Photos button will execute the SubmitPhotos Command, which will push data back to the underlying Model. The following illustration shows a screenshot of the sample application, and a diagram of how the MVVM pattern is implemented.

FlickrUploadrMVVM

FlickrUploadrXAML

The next piece of functionality that needs to be implemented is drag-and-drop. I want to be able to drag files from my hard drive and onto the application. To implement this I need to handle the DragOver and Drop events on my MainWindow class. In my implementation of the MVVM pattern my View holds a reference to the ViewModel, but the ViewModel does not reference the View. So there is no obvious way for my ViewModel to handle these events. I could extend my ViewModel and add a property to give the ViewModel a reference to the View consuming it. I’m not sure if this is a good idea, or if this functionality should be handled by the ViewModel in the first place. Instead I decide to use a Supervising Controller to implement this functionality. The Supervising Controller class accepts the View to control in its constructor. Instead of taking a dependency on the concrete View class I implement a simple IDragDropSurface interface, which has the DragOver and Drop events. The Supervising Controller is created in the View constructor.

FlickrUploadrMainWindowCodeBehind

The Supervising Controller is responsible for listening to the DragOver and Drop events. When the Drop event executes the Supervising Controller will execute the Import Photos command. This enables the Supervising Controller to communicate with the ViewModel in a loosely coupled way. The ViewModel is responsible for iterating over the list of files and creating FileInfo objects that gets added to the ObservableCollection of FileInfo objects. The View is data bound to this collection and the ItemsControl data template will display the imported photos.

DragDropPresenter

This is an updated diagram showing how the Supervising Controller relates to the view and the View Model.

FlickrUploadrDiagram

Summary

Applying separated presentation patterns in your GUI applications is a great way to achieve separation of concerns, decoupling of components and higher level of testability. In this blog post you’ve seen how the Supervising Controller pattern can be combined with a Model-View-ViewModel pattern to implement drag-and-drop functionality. The specific example uses WPF, but the same concepts apply for Silverlight 2 applications as well.

This blog post is one of three I’m posting to introducing some of the new features in the Silverlight Toolkit announced today at the PDC 2008. For more information about and downloads of the toolkit check out
http://www.codeplex.com/Silverlight.

Auto complete textboxes have become a common interaction model in both web and desktop applications. All the modern browsers have smart suggestions directly in the address bar. E-mail clients on the web and on your desktop will try to suggest the recipient by looking in your address book as you type. Leveraging auto complete in your application is a great way to improve the user experience by limiting errors and cutting down the amount of typing needed to complete a form.

One of the new controls in the Silverlight Toolkit is the AutoCompleteBox control, and in this post I’m going to show how to implement auto completion it in the Dive Log application. The AutoCompleteBox control supports both data bound suggestions as well as custom code to get suggestions asynchronously, for instance by calling a web service. I will cover both scenarios and show how the auto completion code fits in to the Model-View-ViewModel architecture of the Dive Log application.

The AutoCompleteBox control looks and feels like a textbox, and has a Text-property. This makes it easy to upgrade any existing application that uses textboxes to use the AutoCompleteBox control instead. In the Dive Log application I’m going to upgrade the location and buddy textboxes to AutoCompleteBox controls. The auto complete suggestions for dive buddy will be data bound to local values, while the suggestions for dive location will be retrieved from the Dive Log web service.

TextBoxes that needs AutoComplete

Data Bound Auto Complete Suggestions

For safety reasons you never dive alone and always have a buddy with you. There is a good chance you will do multiple dives with the same diver, and having to type in the full name every time you log a new dive can be bothersome. To improve the user experience I’m going to replace the textbox with the AutoCompleteBox control. The suggested values for auto completion are going to be a list of all the buddies the user previously has dived with. If this is the first time with a new buddy the user simply types in the name as in any textbox, and for the next dive this name will be included in the auto complete text box.

The Dive Log application uses the Model-View-ViewModel pattern to keep things nice and separated. All UI components on screen are data bound against properties on the ViewModel. One of the properties is a list of all the logged dives for the currently logged on user. For the AutoCompleteBox control we need to expose a new property returning a list of all dive buddies. This is implemented as a simple LINQ query. The ViewModel implements the INotifyPropertyChanged interface, so every time the list of dives changes we need to fire the event to signal that the list of Buddies has changed.

Property exposed by ViewModel with suggestions.

Now that we have prepared the ViewModel with this new property we can replace the buddy textbox with the AutoCompleteBox control. The AutoCompleteBox control has a Text-property just like the textbox. The name of the buddy for the selected dive is two-way data bound against the Text-property on the AutoCompleteBox control. The AutoCompleteBox has an ItemsSource-property that we bind against the new Buddies-property on the ViewModel.

Buddy TextBox replaced with AutoCompleteBox 

When we run the application and start typing the name of our dive buddy the AutoCompleteBox control will make suggestions based on the values in the data bound list. I haven’t applied any styling to the control, so that the moment the UI looks a little bit off. We will deal with that later.

AutoCompleteBox without styles applied

Auto Complete Suggestions from a web services

In some cases the list of possible matches is too big to be kept in memory and loaded when the application starts. Examples of this could be the Amazons book database or auto completion in an e-mail client where you have a shared address book with thousands of contacts. In these cases you need to query the server for auto complete suggestions as the user types to only get relevant suggestions. For the Dive Log application we’re going to implement code to call a web service to get suggestions for dive locations. There is a good chance that someone else have been to a location before you, so by querying the entire Dive Log database we can provide better auto complete suggestions, and at the same time save bandwidth as we don’t have to download everything at once.

To implement asynchronous suggestions in the AutoCompleteBox control you need to subscribe to the Populating-event of the control. This event will let you run code when the control is trying to populate the list of suggestions. In the event handler you need to set the Cancel-property on the event argument to false before calling your web service to get suggestions. The event argument also contains a Paramter-property holding whatever text the user has typed already. We pass this parameter to the web service to get dive locations that match the text the user have typed in.

AutoCompleteBox Populating Event Handler

I had some problems deciding where to put the code to populate the AutoCompleteBox control. The code needs to have a reference to the AutoCompleteBox control to hook the Populating-event, set the ItemsSource-property and call the PopulateComplete-method when the results are ready. The most obvious place to put this code is directly in the code behind of the page. However, I always try to keep the amount of code in View to an absolute minimum, so my second attempt was to put the code responsible for handling the event and calling the web service in a separate class. The class took the AutoCompleteBox control in the constructor to get a reference to the control. Then in code-behind I would simply instantiate the class and pass in the AutoCompleteBox control to wire things up. This is a better solution than having everything in code-behind, but I’m still not happy. The class responsible for managing auto complete suggestions also needs a reference to the web service client to get suggestions from the server, and to not break testability I want to provide this dependency in the constructor.

The solution I ended up with has a separate class responsible for managing auto complete suggestions, but the reference to the AutoCompleteBox control is set using a property instead of the constructor. In the setter the class will register the event listener for the Populating-event. The class also takes the IDiveServiceClient interface in the constructor so that I can use the Ninject IoC-container to create the object.

AutoCompleteBoxTarget property 

The final problem is how to set the AutoCompleteBox property saying which control the class is providing auto complete suggestions for. I implement an attached dependency property which allows me to use XAML to link the AutoCompleteBox control against the class responsible for managing auto complete suggestions. The implementation of the dependency property I similar to the Command-pattern implementation used in the Dive Log application. I’m not going to include the full implementation here, as the source code is available for download.

AutoCompleteBox AttachedProperty

The web service method returning suggestions is incredibly simple. It takes a prefix argument and runs a simple LINQ query getting all dive locations starting with that prefix.

GetLocations WebService Method

Styling the AutoCompleteBox

Styling the AutoCompleteBox to make it fit with the look and feel of the Dive Log application is really simple. If we use Expression Blend to edit a copy of the default control template we see that the core pieces of the AutoCompleteBox is a TextBox, a Popup and a ListBox. The Popup shows suggestions in the ListBox as the user types in the TextBox. So if you know how to style a TextBox and a ListBox you got the skills needed to style the AutoCompleteBox. I would recommend styling the ListBox independently, as you cannot see the suggestion ListBox in design mode.

Styling the AutoCompleteBox in Blend 2

Since the Dive Log application already have predefined styles for TextBoxes and ListBoxes it didn’t take long to make the AutoCompleteBox look just right. I simply had to apply the excising styles and tweak the border control around the ListBox to make it look nice.

AutoCompleteBox styled

Summary

The AutoCompleteBox control in the Silverlight Toolkit makes it really easy to enhance the user experience by providing auto complete behavior to your application. The control can easily replace excising textboxes where that makes sense. The control gives you the flexibility to use either data bound auto complete suggestions, or write custom code to access web services to get suggestions. The Dive Log application includes examples on how to do both. The Dive Log source code also contains an example of an attached dependency property that allows you to add asynchronous suggestions without cluttering your code-behind.

This blog post is one of three I’m posting to introducing some of the new features in the Silverlight Toolkit announced today at the PDC 2008. For more information about and downloads of the toolkit check out http://www.codeplex.com/Silverlight.

Good layout is a critical to the overall user experience of any application. Silverlight 2 comes with three layout controls; Canvas, Grid and StackPanel. You can also create your own layout controls by deriving from the Panel class. There are already several examples online of community implementations of layout controls. Dave Relyea has implemented an animated wrap panel, and Robby Ingebretsen has created an AnimatingPanelBase that makes it easy to implement animated layout controls.

In the Silverlight Toolkit Microsoft includes two new layout controls; DockPanel and WrapPanel, and one new decorator; the ViewBox. In this blog post I will introduce these controls in a Silverlight context, and give some examples of how to use them.

Make your controls Wrap using the WrapPanel control

The WrapPanel is similar to the StackPanel. In addition to stacking elements on top of each other it wraps them in rows and columns. This is similar to how the Windows Explorer works when you’re viewing a folder and resizing the window. Explorer will wrap any file icon to the next line as the window size decreases. This is layout behavior is useful in many situations, and for this example I’m going to update my YouCard example application to use the WrapPanel.

The YouCard application lets you view your Twitter friends, and each friend gets a card with name, bio and the most current tweet. The current implementation uses a StackPanel inside a ScrollViewer. If you add too many Twitter users you have to scroll horizontally.

This isn’t efficient use of screen real-estate as we have plenty of space above and below the line of cards. This is a good place to introduce the WrapPanel, as we could fit in multiple rows of users depending on the screen resolution. The list of cards is implemented using an ItemsControl that is data bound against a list of Twitter-user objects. The ItemsControl lets you specify an ItemsPanel and an ItemTemplate. The ItemsPanel let you specify which panel that controls the layout of all the child items. The ItemTemplate lets you specify which control to use for each item. When the control is data bound it will create one instance of the stuff inside the items template for each element, and add them to the panel defined in the ItemsPanel. To implement the WrapPanel instead of the StackPanel I simply have to change one line of XAML.

YouCard updated to use WrapPanel

When we run the application the behavior have changes. The WrapPanel will try to position as many cards as possible on screen. When one row is full it will wrap and create a new row. If I change the Orientation to Vertical it will create columns instead of rows. By using the WrapPanel we can fit more cards on screen at the same time without scrolling.

YouCard resizing

Dock your controls to one of the sides using the DockPanel Control

The DockPanel layout control enables docking of controls to any side of the container. The controls added to the DockPanel will take up the entire width or height depending on which side it’s docked to. You control the position of the children control by setting the attached Dock property. The children can be docked to Left, Right, Top and Bottom.

DockPanelCodeExample

In this example I’ve added five buttons, four of them docked to the sides of container. The last one doesn’t have a dock property, and will take up any space left inside the control because of the LastChildFill property (which is true by default). If you set the LastChildFill property to false, the fifth button will be docked to the left which is the default Dock value.

DockPanelExample 

The DockPanel control can be really useful in many situations, for instance when designing the top level layout of the user interface. You can dock your menu and header to the top, a copyright footer to the bottom, and a sidebar to the left or right.

Scalable UI using the Viewbox

The ViewBox isn’t really a layout control; it belongs to a family of controls called decorators. It’s a panel like control but only accepts one child element. The Border and the ScrollViewer are other examples of decorator controls. However, ViewBox can be really useful when dealing with the layout of your application so I think it fits nicely into this blog post.

The ViewBox addresses the challenge of scaling content relative to the available surrounding space. It’s quite a mouthful, but what it really does is make a control take up all the available space, without stretching it. Instead it applies a scaling transform to scale the content to use the available space. In many cases this is exactly the kind of behavior you want, and without the ViewBox you would have to write custom code to achieve that.

The Grid control is great for creating flexible user interfaces that will stretch and grow or shrink as the window size changes. The DockPanel behaves the same way. If we look at the screenshot of the buttons in the Dock panel example the buttons are all stretched to take up any available space. The text inside the buttons does not change size, and instead we end up with allot of empty. By simply wrapping the DockPanel inside a Viewbox the buttons will scale by zooming instead of stretching.

ViewBoxCodeExample

ViewBoxExample

By using the ViewBox to scale your UI you can really take advantage of the fact that all Silverlight 2 controls are based on vector graphics. When the ViewBox scale the buttons the quality doesn’t degenerate like it would if the graphics was bitmap. Instead the buttons remains crisp and comfortable to read.

Summary

The new layout controls in the Silverlight Toolkit adds some great value by adding the WrapPanel, DockPanel and ViewBox to our toolbox. These controls also help make Silverlight 2 more alligned with WPF where these controls are already available. Developers with a WPF background should feel comfortable with these new controls. Silverlight 2 developers who know the Canvas, StackPanel and Grid should definitely start exploring these controls and how they can help layout the user interface. Remember that you can combine and nest these controls however you like. You can have DockPanel laying out the top level UI, and then have some other container control take up the remaining space inside the DockPanel. The DockPanel and WrapPanel are also great examples of how to implement custom layout controls in Silverlight 2. If you have special layout requirements you can use the DockPanel or WrapPanel source code as a starting point for your own layout control. I also recommend checking out Dave Relyea’s two part series on the Silverlight 2 Layout System and Joseph Ghassan thorough walkthrough of Silverlight Layout Management

This blog post is one of three I’m posting to introducing some of the new features in the Silverlight Toolkit announced today at the PDC 2008. For more information about and downloads of the toolkit check out http://www.codeplex.com/Silverlight.

One of the strengths of WPF and Silverlight is the ability to change the style or template of any control. This gives the designer maximum flexibility to change the look and feel of an application, without breaking its behavior. The Silverlight 2 styling support has some major shortcomings, specifically around dynamic and implicit styles. Dynamic styling enables you to change the style of a control at runtime without having to recreate it. Implicit styling means applying styles to all controls based on type, and not a specific style name. Implicit styling is similar to applying CSS styles to a H1-element, instead of having to specify the CSS-class name of the element. The benefit of implicit styling is that you can change the look and feel of all the buttons, textboxes, checkboxes or any other control without having to apply a specific style key to all the elements. The Silverlight Toolkit introduces the ImplicitStyleManager which adds support for implicit styling and themes to Silverlight 2.

There are already quite a few good looking themes for Silverlight 2. Tim Heuer did a blog post earlier this month covering some of the themes available, and specifically the work of Corrina Barber and Dave Crawford comes to mind as great examples. Today these templates are deployed as XAML files, with instructions on which part of the file to copy and paste into your App.xaml file. You also have to apply the styles to every single control in your application, and the name of each style is often different. Dave calls his button style BlackGlossyButton, which is different from Corrina’s naming convention. That means that you have to go over and re-apply the style to all your controls if you want to use Corrina’s theme instead of Dave’s theme.

With the new ImplicitStyleManager designers like Corrina and Dave can style a button without having to give it a specific key. They can share their themes as resource dictionary file, and any developer who wants to use the theme simply includes this file and applies it using the ImplicitStyleManager. This is going to make theming of applications allot easier as you simply include a new XAML file to get a new look and feel of your application. Scott Guthrie has commented on his blog that they will be creating some form of online gallery where designers can share their Silverlight themes.

The way create themes is fairly straight forward. You add a new XAML file to your project and mark it as Content (and not as Page which is the default option). Next you build up your resource dictionary, and for your styles you no longer have to apply a key (unless you want to). You simply set the target type to style a button, textbox or any other control. The theme gets applied to your application by using the ImplicitStyleManager attached properties on any container control. All child elements inside that container will get the theme style applied.

ImplicitStyleManagerSample

For this example I have taken Dave’s glossy control theme and turned it into a Silverlight Toolkit theme. When I run the example code above, this is what my button looks like:

ImplicitStyleManagerHelloWorld

All I had to do to turn Dave’s glossy theme into a Silverlight Toolkit theme was remove the key on each on the style. That way I don’t have to specify the key for my button style, as the theme will be applied implicitly by the ImplicitStyleManager. The next screenshot shows a typical data entry screen using Dave’s theme and the Shiny Blue theme from the Silverlight Toolkit (one of the six included themes).

TwoAppliedThemes

In the above example I didn’t have to change any of the XAML of the application, or name of styles, in order to change the entire look and feel of my application. In the future I’m sure we will be seeing lots of new themes from the community as well as commercial vendors. The ImplicitStyleManager makes it easy to share themes and apply them to your application. There are still some shortcomings to the styling model. Support for dynamic resources is one of them. In order to change the theme while the application is running you have to recreate your UI before applying the theme. This is almost like having to “reboot” your user interface, and is not an optimal user experience. However, having Theme support is still a great way forward and opens up many new possibilities.

SDDN Logo

Earlier this week Australian Silverlight enthusiast Jordan Knight announced the Silverlight Designer and Developer Network initiative. This is a new user group starting up in Melbourne, focusing on the design and development aspects of Silverlight. First meeting is scheduled Thursday November 27 at 5:30 PM for a 6PM start. The venue is Microsoft Theatre, Level 5, Freshwater Place, Southbank. Microsoft User Experience Evangelist Shane Morris will be delivering a key note to kick off the group. I will be giving a presentation covering the current state of the Silverlight union. I will talk about any major Silverlight announcement from the PDC, what have been announced around the future, and some of the interesting community projects around Silverlight 2.

The SDDN is a great initiative for many reasons. Most importantly it creates a meeting forum to bring developers and designers together. Getting designers engaged is a key success factor for Silverlight. I really hope this initiative can help that happen. Secondly the Network-part of the name suggests this is more than user group meetings. The SDDN has ambition to build a strong online presence, with high quality recordings of all meetings. This is a great way to reach out to a wider audience, as well as developers and designers working in smaller/remote areas who might not have access to a user group like this. Big kudos to Jordan for making this effort!

Check out Jordan’s announcement post and the new (but still under construction) site for more details. Hope to see you at the first SDDN meeting!

Meet Me In Los Angeles With the SDDN announcement out of the way the next point on my agenda for this “what’s up” blog post is the PDC. I’m writing this while sitting at the gate waiting for my flight to Los Angeles. I will be attending PDC 2008! I had the pleasure of attending PDC back in 2005, and that was an amazing experience. This year I have high expectations to the PDC as it has been three years since last time. I tried to set up my agenda, and ended up with at least two conflicting sessions for each time slot! There is just so much great content. Thankfully Microsoft is putting a big effort into recording all sessions, so at least that’s a chance to catch up on the sessions I miss out on. I don’t know if the recordings will be made available publicly, but I sure hope so.

I’m looking forward to networking with fellow peers in the Microsoft and Silverlight development community. If you’re attending and want to catch up, drop me an e-mail at jonas@follesoe.no, or ping me on Twitter (@follesoe). See you in LA!

Silverlight 2 - No Longer in Beta! As most of you probably know by now Microsoft released Silverlight 2 with supporting tools earlier this week. I’ve been following the development of Silverlight closely, and it’s great to see it come out of beta. Hopefully this means more people will seriously consider Silverlight 2 for their applications. I also think we’ll see more and more content about frameworks, patterns and practices built on-top of the Silverlight 2 framework. Since Silverlight 2 have so much in common with WPF and .NET there already is lots of great stuff ported over, but I expect allot more to follow.

I have now upgraded my three main sample applications, WebCam, DiveLog and YouCard, to the RTW bits. It didn’t have to change any code, as I did the upgrade to RC0 when it released. The updated samples are available in my Windows Live Sky Drive folder, as well as embedded at the end of this post. I have also updated the release of Colorful Expression to clearly indicate that Expression Blend 2.0 SP1 is fully supported.

I did a talk at the Victoria .NET User Group about Silverlight this Tuesday, and hopefully got some new readers to this blog. I normally don’t do link-blogging so this is an exception. I’ve gone through my blog archive (27 posts tagged Silverlight) and picked some of the posts I’m most happy with and written a short summary.

Posts related to the Dive Log application

  • TechEd 2008 – Silverlight 2 for Developers
    I wrote the Dive Log application as a demo for my Tech Ed 2008 talk. The post introduces the projects, contains link to a video of my Tech Ed talk, as well as other relevant links.
  • Back and forward navigation in Silverlight 2 using ASP.NET AJAX
    A post that describes how to integrate with the browser history and back/forward buttons. By default Silverlight doesn't support this, but using the HTML Bridge and ASP.NET AJAX you can easily add back/forward navigation and bookmark support to your Silverlight application.
  • WCF Authentication Services, Silverlight and smelly cookies
    One of the great strengths of Silverlight 2 is the ability to easily port your application to the full version of WPF if the browser sandbox becomes to limiting. One of the issues I ran into while porting the Dive Log application to WPF was cookie based authentication against my web services. This posts shows how to authenticate against a ASP.NET Membership Provider from WCF.
  • Porting the Silverlight Dive Log application to WPF
    Once I had authentication working in WPF porting the actual Dive Log application was really easy. It probably didn't take more than a couple of hours, and this post describes some of the things I ran into while porting the app.
  • Printing in Silverlight 2 using CSS and ASP.NET AJAX 4
    Printing is a core requirement in many business applications. The Silverlight 2 printing support out of the box is really limiting, but using the HTML Bridge you can provide a better printing experience for your application. The post discusses different printing strategies, and show how to use ASP.NET AJAX 4 to generate HTML on the client that can be printed using CSS print style sheets.

Posts related to the YouCard application

  • YouCard Re-visited: Implementing the ViewModel pattern
    The YouCard application was a demo I wrote for REMIX Australia back in May. The focus was on the UI side of things, and initially I didn't pay too much attention to the architecture of the application. In this post I go back and refactor the code to use the Model-View-ViewModel / Presentation Model pattern.
  • YouCard Re-visited: Implementing Dependency Injection in Silverlight
    Inversion of Control using Dependency Injection is a really popular and powerful software pattern. It helps you separate your concerns, keep your code testable, loosely coupled and more flexible. In this post I show how you can use Dependency Injection in a Silverlight context using the Ninject framework. The post focuses on how Dependency Injection, combined with the MVVM/Presentation Model pattern can make your code easier to use for UX designers. By using mock-objects that provide design-time test data when the code is consumed inside Expression Blend the job of designing the UI, setting up Data Binding and Data Templates becomes allot easier.

Posts about testing, the HTML Bridge and other tips and tricks

  • Webcam in Silverlight 2 - MacGyver style!
    Silverlight 2 does not support webcam or microphone like Flash does. But if you put on your MacGyver hat, and use the HTML Bridge you can get some basic web cam support in Silverlight. This post shows how you can integrate Silverlight 2 and Flash using JavaScript. The example shows how to capture still images from the webcam in Flash, and use the images in Silverlight.
  • Unit testing asynchronous Silverlight code
    I'm a big fan of the Silverlight Testing Framework and how it support more advanced scenarios like testing asynchronous code. This post shows how to asynchronous features of
    the testing framework to test code that talks to Twitter and Flickr.
  • Silverlight 2 Continuous Integration Testing using WatiN
    Continuous Integration is a great practice I try to use on every project I'm involved with. In essence it's about automating what can be automated of your build- and deployment process. A common thing to integrate is automated unit testing on every checking. The problem is that the Silverlight Testing Framework has to execute inside the browser, making it more challenging to integrate it to an automated build process. This post shows how to use WatiN (Web Application Test in .NET) to drive Internet Explorer and detect if the Silverlight tests executes successfully or not. Using this technique you can call your Silverlight tests from a nUnit test, something that makes it allot easier to integrate into your build process.
  • Efficient testing in Silverlight 2 using tags
    The Silverlight Testing Framework makes it easy to write Unit Tests, Integration Tests and User Interface/Smoke Tests. However, you might not want to execute your integration tests every time you change your code. By using the new tagging feature you can categorize your tests and execute only tests that match a certain tag. The post shows how to pass in a tag from the query string to control which tests to execute.
  • Configuring Silverlight 2 applications using the WCF configuration file
    Silverlight 2 uses a configuration file for all it's WCF service references. It does not have the full configuration API from the .NET 3.5 Framework. However, there is nothing stopping you from adding your own custom XML elements to the configuration file, and write code to read it. This post shows how to add an appSettings-element to the configuration file, and build a class that looks and feels like the .NET Configuration Manager.

One of the frequently asked questions on forums, blogs and by conference attendees is how implement printing in Silverlight applications. Out of the box Silverlight 2 does not have any printer specific APIs, and it’s up to you as the developer to figure out how to deal with printing. If you use the print button in Internet Explorer 7 to print you’ll get a simple rendering of the page. If you try to print from Firefox or Safari you’ll get nothing but a blank page. Printing is a core requirement in many business applications and something you need to be addressed if you’re going to build a Silverlight 2 application. In this blog post I’m going to cover different strategies for printing, and show how we can use the HTML Bridge combined with some of the new features in ASP.NET AJAX 4.0 to implement printing from a Silverlight 2 application.

Print Preview of Silverlight content in IE7

Print preview from the Dive Log application. The Silverlight control is stretched since the container is sized to 100% width and height, and the print preview is in portrait mode. This is probably not what the user wants to print anyway.

Printing strategies

When dealing with printing in Silverlight, or perhaps in web applications in general, you have two main options; generating printouts server side or client side.

When building applications you often want to have printout reports that differ from the actual markup making up the UI of the application. In those cases a common solution for printing is to open a pop-up window that contains a server generated report ready to print. The report can be in any format depending on your requirements. You can show a PDF or XPS document, a Word document, or just a plain HTML document. When implementing server side generation of reports you are not limited to what’s available in the browser, and can choose whatever technology you want. You can use plain ASP.NET to generate HTML, or you can use a more advanced reporting solution such as SQL Reporting Services to generate PDF documents on the fly. The drawback of using server side generated reports for printing is that the user has to click a separate print button in your application to bring up the report. If the user simply clicks the print button in the browser toolbar they will get whatever HTML is available in the browser. This breaks the default user interaction models and is something we should try to avoid if possible. You’re also depending on server side resources to generate the report instead of leveraging the power of the client computer.

Client side printing simply means using the built-in functionality of the browser to provide printing in your application. For most content-centric sites, like blogs and news papers, this is the most obvious solution as the entire HTML is already available in the browser. However, you probably don’t want to print things like navigation elements or large header graphics. To solve this all modern browsers supports separate CSS style sheets for print. This enables the developer or designer to customize the look and feel of the page when printed. You can use CSS to hide navigation elements, large graphics, or other parts of the page you don’t want to include in your printout. This is great for HTML pages, but how does this apply to Silverlight 2 applications?

Silverlight is embedded onto the page using an object-tag, normally sitting inside some div-container. This allows us to apply CSS styles against the Silverlight container. In our CSS print style sheet we simply set the visibility to none to hide the Silverlight content when printing the page. At the same time we can change the visibility of another div-container that was hidden in the screen style sheet, but is now visible when printing the page. This enables us to swap visibility between the Silverlight application and other HTML content sitting behind it. Now we just need to populate this HTML element with meaningful content when printing. The way you interact between Silverlight 2 and the browser is through the HTML Bridge. The HTML Bridge lets you invoke JavaScript functions or manipulate the HTML-DOM from managed code in Silverlight 2. Using this API we can dynamically generate HTML on the client to populate the print div-container. The visibility and style of the printout is controlled by the print style sheet. The next question is how to best generate HTML from Silverlight 2. You have a couple of options;

  • Concatenate strings using the StringBuilder
    The perhaps most straight forward approach would be to write code that builds up a big HTML string in Silverlight 2, and then set the InnerHtml property of the container using the HTML Bridge. This would work just fine, but string concatenation is hard to maintain and easily leads to spaghetti code.
  • Use LINQ to XML to generate HTML
    In many cases this would be a good option as you could easily write LINQ queries against your objects, and then use LINQ to XML to dynamically build up the HTML document. This would be cleaner and easier to test and maintain than concatenating strings. The problem with generating the printout through code is that the look and feel of the printout is part of the user experience, and something that should be owned by the UX team and not the developers. Having to change LINQ to XML code to update report is not very flexible or designer friendly.
  • Use Client-side HTML controls for Silverlight 2
    Jeff Wilcox, the guy behind the Silverlight 2 Testing Frameworks, wrote an interesting post a few days back about a Client-side HTML controls library for Silverlight 2. This is something Jeff wrote for the testing framework to generate the test-report. He had the same problem of dynamically generating HTML from Silverlight, and solved it by implementing an abstraction layer on top of the HTML Bridge to build a client-side HTML control library. The library is built by extending the HtmlElement class to build higher level elements like Button, TextBox, Div, Headings, and even complex controls like a progress bar. This gives you an ASP.NET-like programming model running on the client. You can write clean, testable code against the controls, but you still have to build your reports through code. This makes things hard for your designers. The controls are currently only available through the testing framework, something that could make it hard to use in a production environment. But Jeff definitely got some interesting ideas around creating HTML content on the client that is well worth checking out.
  • ASP.NET AJAX 4.0 Client Templates
    An new and really interesting way of generating HTML on the client is using the new Client Templates introduced in the ASP.NET AJAX 4.0 preview release. The client templates let you define HTML fragments containing JavaScript binding expressions. The templates can later be applied to a JavaScript array to generate HTML on the client. This allows you to keep the HTML outside of your Silverlight code, and the only thing you have to pass over the HTML Bridge is the objects you want to use for your printout. This gives your designers the flexibility to work on the HTML and CSS for the printout while keeping your Silverlight 2 code nice and tidy. This is the approach I’ve taken for adding print support to the Dive Log example application.

Printing using ASP.NET AJAX 4.0 Client Templates

One of the really interesting features of the ASP.NET AJAX 4.0 preview is client templates. This enables you to write HTML fragments containing JavaScript binding expressions. The templates can be applied to JavaScript arrays to generate HTML on the client. I would recommend checking out Bertrand Le Roy’s two part blog post for a good introduction to client templates. Scott Hanselman also did a post showing how to use client templates together with jQuery to build dynamic HTML in an AJAX application. The October issue of MSDN Magazine also got a good article about new AJAX support for data driven web sites. The ASP.NET AJAX 4.0 is preview technology and things are likely to change. However the client template script is just a 50KB JavaScript file so using it shouldn’t make a big impact on your application.

The printing user experience I want to achieve for the Dive Log application is really simple. I don’t want to add a print button to the Silverlight 2 interface. Instead all printing should be done through whatever functionality is available in the browser. Most likely by clicking the print-button in the toolbar, or going to the file menu and selecting print or print preview. The printout shouldn’t contain the Silverlight 2 user interface. Instead it should contain a HTML table listing all logged dives.

The first thing we need to do is include two CSS style sheets, one for print and one for screen. The style sheets are responsible for toggling between showing/hiding the Silverlight 2 container and the print container.

Seperate style sheets for print and screen.

I use the ASP.NET Silverlight Control to render the HTML needed to show the Silverlight 2 application. Underneath the Silverlight control I have a separate HTML-div that will be the container for the dynamically generate print HTML.

Silverlight 2 container

The most interesting part of the print implementation is the client template used to generate the HTML. The meat of the template is a plain HTML table with columns for each of the fields we want to use from the dive log. The body of the table is marked with a special CSS class to indicate that this is a template, and the columns contain JavaScript binding expressions.

ASP.NET AJAX 4 Client Template

To populate the template with data we need some JavaScript. The script is kept in a separate file to keep things nice and clean. The script is responsible for instantiating the template based on the HTML markup. The script also registers a custom markup extension for the format expression used to bind the date column. This shows some of the power of using JavaScript binding expressions, and the extensibility of the client template framework. The final piece of JavaScript is a simple function to bind data against the template. The data is passed in as a JSON string from the Silverlight 2 application, and is de-serialized before the template is applied to the JavaScript array.

JavaScript to populate Client Template (available in seperate download)

The final piece of code needed is the Silverlight 2 code responsible for updating the print template with data. This is done by simply invoking the updatePrint-function passing in a list of Dive object serialized as JSON. The code is added to the View Model and is executed every time Dive Logs are retrieved from the server. The list of dives is serialized to JSON using a simple extensions method.

Using the HTML Bridge to update the print container.

When we run the application and click the print-preview button we no longer get a stretched Silverlight 2 user interface. Instead we get a nice HTML table listing all our logged dives. Since we’re using standard HTML and CSS to do printing it now works in all browsers, and not just IE7 which is the only one currently supporting printing of Silverlight 2 content.

Print preview with custom HTML instead of Silverlight 2 content.

Summary

Printing support is a key feature of most line of business application. Unfortunately this isn’t one of the strong sides of Silverlight 2. Hopefully this will improve in future versions of Silverlight. Microsoft hasn’t made any announcements, but I hope for better support for rich text and text layouts. WPF already has great support for documents, and hopefully some of these features will make it into Silverlight. But for now we have to use existing web technologies to solve printing.

In many cases server side generated report will be a good option. Using the HTML Bridge you can easily bring up a pop-up window where you pass in URL parameters to render the report. However, in some cases you should consider providing a good client side printing experience. Hopefully this blog post have given you some ideas to how to implement printing in Silverlight, and at the same shown some of the power of combining Silverlight with existing AJAX technologies. I did run into some minor challenges using this approach. One of them was figuring out when to update the print section with new HTML. Internet Explorer has a onbeforeprint-event you can listen to, but that one is not available in any other browser. Another option would be to listen to mouseout-events to try to detect when the user is moving up to the toolbar (and potentially could be clicking the print button). Non of these techniques where reliable enough, so I decided to simply update the content every time it's persisted/loaded from the server. This could lead to some inconsistence if the user edits a dive and click print before saving it back to the server. How you deal with this would depend on your application and requirements.

One added benefit to this approach is that you could render the initial HTML content of the print container on the server using ASP.NET. This would give search engines like Google something to index, making your Silverlight 2 application searchable. The search engines wouldn’t execute your Silverlight or JavaScript code, so this would only work for the initial rendering of the page.

I will post the updated version of the Dive Log application and source code tomorrow when Microsoft, according to rumors, will be releasing Silverlight 2.

Introduction

I have previously blogged about the Silverlight testing framework that was originally released as part of the Silverlight 2 Beta 1 control source. Jeff Willcox, the lead developer on the framework, recently announced an updated version of the framework for the Silverlight 2 Release Candidate. The updated version contains several interesting new features, which Jeff has covered in a great thorough blog post. I’m not going to re-iterate the feature list in this post, but rather focus on the one of the new features; tagging of tests.

Types of automated testing

Automated unit testing of code has become a common development practice, and as developers we have a wide variety of frameworks to pick from to help us do testing. A common misperception is that any test written using a testing framework is a unit test. That is not necessary true as there are multiple other types of test you can write for your code. Phil Haack, one of the program managers on ASP.NET MVC, wrote about the boundaries of unit tests on his blog a few months back. I recommend this post as a good overview of some of the considerations you should make when writing unit tests.

I’m quickly going to list the types of tests I normally write when building Silverlight applications.

  • Unit Test
    Tests a single unit of work. In most cases a single method in a single class. Normally don’t touch the database, the file system or the network. Should execute quickly with no side effects (changed global state).
  • Integration Test
    Tests how multiple classes integrate with each-other, or how a class integrates with the environment. I.e. parsing of an XML file, reading/writing to a database, or accessing data on the network.

  • Smoke Test
    Simulates an user interacting with the application. Tests multiple classes and can cross boundaries such as network, file system or database. In many cases you write your smoke tests by automating the user interface.

Even if your tests aren’t a true unit tests according to the list above, it’s perfectly fine to use a testing framework like nUnit to write your integration- or smoke tests. There are other types of tests as well, i.e. performance tests, stress tests and acceptance tests. For these types of tests you often use different tools or extensions to your testing framework.

One of the considerations you should make when writing your tests is to keep your unit, integration and smoke tests separated. You should try to keep your unit test running as quickly as possible, something that is easier to achieve if you focus on not crossing any process boundaries. If testing becomes slow and tedious developers might start cheating and not run the test suite as they change code. One way to separate your tests is to have different projects for each type of tests. This is a good solution in many cases, but for smaller projects (like all of my Silverlight demo applications) this may lead to a cluttered project structure. In the Silverlight testing framework you can organize your tests in a different way by adding tags to test classes and test methods.

Tagging tests

One of the new features that were introduced in the latest version of the Silverlight Testing Framework is support for tags. You can apply multiple Tag-attributes to any test class or method in your test suite. The Tag-attribute takes accepts a string, so it is up to you to decide how to organize your tests. As an example for this post I am going use the YouCard application I built for REMIX. The tags I am going to apply are based on the types of tests I listed above; Unit, Integration and Smoke. The YouCard test suite isn’t too big and only got 13 tests in it. But it got a little bit of everything, so it should be a good example.

The most obvious candidate for being tagged as a unit test is the value converters tests. A value is like a mini-adapter you can apply during data binding to convert from one value to another. It got two simple methods, Convert and ConvertBack, and no external dependencies.

Test tagged as unit test

The YouCard application uses the Model-View-ViewModel pattern, so the next set of tests to be tagged as a unit test is the ViewModel tests. The ViewModel class has two dependencies to a Flickr service and a Twitter service. Because these dependencies are implemented as interfaces and injected in the ViewModel constructor I can supply test mocks, making this a pure unit test and not an integration test.

Now that we’ve identified some unit tests it’s time to show some examples of integration tests. The two most obvious candidates are the classes responsible for accessing the Twitter and Flickr APIs. Both implementations are based on an interface, making it easy to mock the dependency when testing the ViewModel. However, we still want to write tests to verify that the code downloading and parsing the XML from Twitter and Flickr works as expected. This means accessing the network, and thus crossing the boundaries of what we consider a unit test.

Test tagged as integration test

The final type of test we want to identify and tag is a smoke test. The Silverlight Testing Framework runs inside the browser with full access to the Silverlight runtime, making it easy to write user interface tests. The YouCard test suite has one smoke test simulating a user entering Twitter usernames into the textbox and hitting the add-user button. The test waits about a second between each user interaction, and it uses real implementations of both the Twitter and Flickr interfaces. This makes the test fairly slow to execute, but still valuable as it gives us a verification that the application works as a whole when all the pieces are coupled together.

Executing tests based on tags

Now that the tests are categorized using tags, how do we execute specific tests based on the tags? In the Silverlight Testing Framework you create the test page in the Application Startup event in the application class. In CreateTestPage method accepts a UnitTestSettings object you can use to configure the test framework. One of the properties on the settings object is a TagExpression property. The name of the property hints that we can supply more than the name of a simple tag. Jeff hasn’t documented this feature yet, so I don’t know the limits of the expressions you can create. You can do things like “!Unit” to execute all tests except the once tagged as “Unit”. I don’t know if you can use more complex expressions and combinations of tags. But in most cases supplying a single tag should be enough.

Configuring test framework in Application Startup

Since configuration of the test framework is done through code it’s easy to make the tag expression dynamic. The example code looks for an initialization parameter called tag, and if found its value is applied as the tag expression. Initialization parameters are passed in when the Silverlight object is created in on the page. If you are using HTML to create the object you add the initialization parameters as a param-element to the object-tag. If you use the ASP.NET Silverlight server control you set the InitParameters property. In this example I have a Silverlight and some ASP.NET code to check the query string. If the query string contains a tag-element the value is passed to the Silverlight control as an initialization parameter. Using this technique you can simply change the URL to execute your test suite with different tag expressions applied.

Passing a tag from the query string to the init parameter.

To execute the code simply navigate to the page hosting the Silverlight tests. By default it will execute all tests, but if you add a tag-parameter in the query string you can control which tests to execute.

Executing tagged Silverlight tests.

Summary

The updated version of the Silverlight Testing Frameworks got lots of new useful features. Support for tagging is one of them. Hopefully this post gives you an introduction to how you can use tags to organize your tests. The deployed version of the DiveLog and YouCard application use this technique, and if you want to see how the test framework executes tests just click one of the links below.

For a little more than a week ago Microsoft released a Release Candidate of Silverlight 2. I’m not going to talk too much about this release, as it has been covered in great detail in the blogosphere. I have now updated my Silverlight 2 sample applications from Beta 2 to the Release Candidate. The RC is not a public release, and is intended as an interim release to give developers some time to get ready for the final release, which is expected shortly. You are not supposed to deploy RC versions of your Silverlight applications to the public, as this could fragment the user base even more and give a poor user experience. However, since the audience of this blog is mostly developers I’ve decided to uploaded fresh RC versions of my sample applications.

I didn’t bump into too many issues in the update. Most of the changes where small XAML modifications now that the ContentPresenter control derives FrameworkElement instead of Control. I discovered that Blend 2.0 SP1 Pre View did a far better job than Visual Studio 2008 to help me work out XAML changes.

The only real issue I ran into was my use of user control inside a DataTemplate in the YouCard application. I have a list of User objects that is bound to an ItemsControl. A common technique to keep the XAML clean is to use a UserControl inside a DataTemplate. That way you can encapsulate all the XAML needed to represent one item in a list into a separate control. In Beta 2 you had to explicitly set the DataContext on your user control to pass the object you want to display in your DataTemplate. If you do that in the RC your binding will fail. If you try to set a breakpoint and debug the DataContext property of your user control you will discover that it’s always null. It took some time to figure out the problem, but the solution was really simple. You simply don’t need to specify the DataContext for your user control inside the DataTemplate. The DataContext will automatically be set for you.

Code illustrating my DataContext problem.

I’ve uploaded new versions of YouCard, DiveLog and Webcam POC to my test page. The source code is available in my Code Samples SkyDrive folder. Now we just need to wait a few more weeks for the RTW!


Adobe Kuler is a great example of a Rich Internet Application that provide great value directly in the browser. Kuler is a tool that helps you create color themes by applying different rules to find matching colors. You start by selecting a base color, and Kuler will help you find four matching colors. You can even use Flickr photos as a basis for your color theme. Adobe Kuler has a social aspect to it as well. You can create an account and save your colors online and share them with the community. People can rate and commend on your themes, or create new color themes based on an excising one. Kuler is being a good Web 2.0 citizen and offers a REST-full API that lets you build your own applications using the colors of the community.

Screenshot of Adobe Kuler

Whenever I find a service I like with an open API I just can’t leave it alone. So today I’m announcing the Colorful Expression add-In.

Colorful Expression is an add-in for Expression Blend and Expression Design that brings you the Adobe Kuler community directly into your toolbox. It adds a new palette to your design environment, making it easy to leverage the community to find the perfect color theme for your application or design. The add-in also available as a standalone application, making it useful for web developers working in Visual Studio or Expression Web to select colors for your CSS style sheets.

Expression Design

Last week Jose Fajardo blogged and complained that Expression Design doesn’t get enough love. I totally agree, and am going to give it some love by making it more colorful.

Expression Design AddIn 

The key feature of the add-in is to select colors. The eyedropper tool in Design lets you click anywhere on the screen to select a color. Simply click the eyedropper in your color panel, and click on one of the colors in the Colorful Expression panel.

You can also copy colors to the clipboard by clicking the copy-button. When you paste the color theme onto the design surface you’ll get five rectangles and the name of the color. This lets you collect interesting themes directly in your design file by copying them onto the document.

Expression Blend supports exporting and importing color swatch libraries through a simple XML file format. Colorful Expression allows you to save a theme as a swatch library you can import into Design. The screenshot shows the “Buddah in Rain” theme imported to the swatch library.

Expression Design AddIn Screenshot

Expression Blend

The add-in works almost the same way in Blend as in Design but with some minor differences. In Blend you can use the Ctrl+C key combination to invoke the copy command, making it a lot easier to copy/paste themes onto the design surface. When you paste a theme onto the surface you will get a grid containing five rectangles and a text block. The rectangles are painted with a solid color brush resource, and each of the colors gets added to the resource collection of the page. If you go into XAML-view and paste the theme you will get five solid color brush resource elements you can add to any resource collection. The Blend add-in also supports drag and drop, letting you drag color themes onto the design surface.

Blend add-in screenshot

Standalone application

The standalone application gives you most of the same features as the Blend and Design add-in. You can copy or drag themes into Blend, and you can save Design swatch libraries. The stand alone application is useful if you don’t want to run the add-in all the time or if you don’t use Expression Studio. You can also hold down control and click a single color to copy it to the clipboard as a RGB HEX color. That way you can use the standalone application as a color picker for any application using HEX colors, such as CSS style sheets.

Standalone application screenshot

Ideas for next version

I want to keep the add-in simple and focused, but I do have some ideas for new features. The first thing I’m planning to implement is a color provider for the COLORLovers site. I also want deeper integration with Blend and Design, especially around managing resources in Blend.

It would also be nice to support Expression Web and Visual Studio 2008 so that web developers can use it to get CSS colors for their web projects.

Another feature missing is support for the light Expression Studio color theme. The current look and feel is based on Hadi Eskandari’s Expression Clone theme and only supports the dark theme. It should be fairly simple to create a new theme matching the light colors.

You can suggest new features in the discussion board or report bugs in the issue tracker.

Download and installation

The project is released on http://www.codeplex.com/colorful, and the initial release contains the compiled version of the add-in for Design 2.0, Blend 2.0, Blend 2.5 June CTP, Blend 2.0 SP1 Preview and as a standalone WPF application. To install the add-in simply copy the files into your Blend or Design director, and launch the EXE file with an extra parameter.

I.e: “Blend.exe –addin:Colorful.Blend.AddIn.dll” or “Design.exe –addin:Colorful.Design.AddIn.dll”.

You can also right click your application shortcut and select properties to change the target of the shortcut. Add the above parameters to the target to launch Blend or Design with the add-in every time you click the shortcut.

ShortcutProperties

Getting involved

If you would like to get involved in the project drop me an e-mail at jonas@follesoe.no. You can also suggest features or report bugs in the discussion forum and the issue tracker.

To build the project you need to have Expression Blend or/and Expression Design installed. The add-in has a dependency on Microsoft.Expression.Framework.dll, which in turn has a dependency on Microsoft.Expression.Diagnostics.dll, Microsoft.Expression.Interop.dll and Microsoft.Expression.Licensing.dll. For licensing reasons these assemblies are not checked into the source control three.

If you want to run the add-in from Visual Studio I recommend running Visual Studio 2008 as administrator and then change the output directory of your debug build to the installation folder of Blend/Design. Then change the startup application to the Blend.exe/Design.exe with the correct startup arguments. That way you can hit F5 inside Visual Studio to launch Blend/Design in debug mode. You can set breakpoints in your code and test/debug the add-in this way.

Happy coloring!

The most current developer build of the Google Chrome browser has fixes for some of the initial Silverlight problems reported when the beta was made available. The beta did load the Silverlight plug-in, but people experienced several bugs. On the sites I tried Chrome would render the application, but any interaction from keyboard or mouse wouldn’t get passed to the application. This is now fixed and Chrome now runs all the Silverlight 2 applications I’ve tried without any problem. I’ve tested it with the sample applications I’ve built (YouCard and DiveLog); as well as with some of the larger reference applications such as Hard Rock Memorabilia and the Microsoft Health CUI demo application. All of them work just fine. Even things like the browser navigation integration in the Dive Log application works as expected.

One of the cool things Google have done with Chrome is to make it really easy to run early developer builds. This 7-step tutorial explains how to enable what Google calls the Developer Channel. What this does is that Chrome will now check a different repository for updates and new releases than people using the Beta Channel (default). After running a tool that enables the Developer Channel you get fresh builds through the automatic update system (the about dialog).

This is great news for the Silverlight community as this clearly indicates that Chrome will have full Silverlight support when it comes out of beta. I've included some screenshots of Silverlight applications running in Chrome. If you want to stay on top of current builds of Google Chrome I also recommend following the Twitter user @GetGoogleChrome.

Update

YouCard running in Google Chrome YouCardSiteSpesificBrowser Dive Log running in Google Chrome Microsoft Health CUI running in Google Chrome Hard Rock Memorobilia running in Google Chrome

After some initial struggles with Authentication Services and cookies in WCF it turned out porting the Dive Log Silverlight application to WPF was fairly straight forward. Once I had figured out how to authenticate from WPF it didn’t take more than a few hours to bring the entire application over from Silverlight. I’ll list some of the gotchas I ran into while porting the code

Authentication
The Silverlight version is protected using Forms Authentication and an ASP.NET membership provider. The WPF version uses WCF authentication services, and needs to manage the authentication cookie manually. Details about this are covered in post I did this weekend. After figuring out how handle authentication implementing the login screen was straight forward. It uses the same Model-View-ViewModel design as the rest of the application.

DiveLogLogin

Presentation Models (ViewModel)
The Dive Log uses Presentation Model pattern (aka Model-View-ViewModel in WPF/Silverlight circles), so the majority of the application code is non-visual. I was able to port that code straight over to WPF with some minor adjustment. The WPF version has an extra dependency to a cookie manager (that’s how the Dive Log service gets the authentication cookie from the login service). I also had to change the event handlers for the commands.

Commands
In WPF commands are built into the framework so I could throw away some of the code from the Silverlight version. The command implementation used in the Silverlight application is very similar to the WPF commands, so porting the code wasn’t a big challenge.

Value Converters
Value Converters is the Swiss army knife of WPF and Silverlight programming. It lets you convert pieces of data during data binding. The Dive Log application has 8 value converters and I was able to port all of them straight to WPF with no code change.

IoC and Dependency Injection
The application uses Ninject for dependency injection. Ninject supports both Silverlight and WPF so I could reuse all that code. I had to make some changes in the configuration class. In Silverlight I use the HtmlPage.IsEnabled property to check if the code is consumed by Blend. In WPF you got a IsInDesignModeProperty dependency property you can use to check if the code is consumed by Blend or Cider.

The “basic” user interface version
The Dive Log application comes with two user interfaces, one done by a developer, one done with the help of a designer. The simple UI version ported nicely over to WPF, with a few minor changes. The first thing I had to change is that WPF supports Windows, while the top level element in Silverlight is a user control. Silverlight also got a couple of controls currently not available in WPF. One of these is the date time picker. In the WPF version I used a simple textbox instead. Other than that the UI pretty much just worked out of the box. It looked a little different since some of the default styles for some of the controls are a little different.

 Dive Log Silverlight vs WPF

The “full” user interface version
The richer version of the user interface contains several template controls and I didn’t expect to be able to reuse a lot of the XAML. But since the styles and templates are defined as resources I was still able to copy-paste the skeleton of the UI with only a couple minor changes. The screen shot below shows the WPF version after a rough copy-paste. The problem with porting the UI is that Silverlight uses the Visual State Manager for styling and templates, while WPF uses triggers. So for this part of the application I had to do a lot of hand coding of the XAML, moving each template over piece by piece. I was still able to reuse a lot of the individual pieces, such as the XAML graphics used for the weather check boxes, the customized slider control, and some of the other graphical elements.

Dive Log app after initial XAML port.

Conclusion
The Dive Log application is a fairly trivial application, yet complex enough to give a decent indication of what it would take to port an application from Silverlight to WPF. I was pleasantly surprised with how easy it was to port the application to WPF. However you will have to do some manual work, especially around styled controls. Patterns like the Model-View-ViewModel pattern make it easy to reuse your ViewModel classes between WPF and Silverlight, and code-only elements such as value converters ports straight over to WPF. But I think the biggest thing you gain from working with both Silverlight and WPF is reuse of skills. With little WPF knowledge I was able to build a fairly rich application using what I know from working with Blend 2.5 and Silverlight, which is huge! I've uploaded the current source code, as well as a compiled version of the WPF application if you want to try it. They're available as embedded downloads from Windows Live Sky Drive (might not be visible in your RSS reader).

Dive Log WPF version

Downloads

This blog post was supposed to be about porting the Dive Log Silverlight application to WPF and how easy that transition was. Well, turned out I got stuck with WCF problems long before I could even start touching the XAML. Before diving into the problem, lets step back and refresh how authentication and data access is handled in the Dive Log Silverlight application.

The database schema for the application is really straight forward; it consists of a user table and a dives table. On top of the user table I’ve implemented a simple ASP.NET Membership Provider and configured it in web.config. I’ve also added authorization rules to my configuration file limiting access to the web service and the web page hosting the Silverlight content. The web service used by the Silverlight application is created using the “Silverlight-enabled WCF service” template. That the template does is to create a WCF service that is configured to use the basicHttpBinding and with ASP.NET compatibility turned on. WCF is built to be agnostic to the hosting environment, but by turning on ASP.NET compatibility you get access to the HttpContext object, and other web related stuff like cookies and headers. Since the service is protected using the membership provider I can access the currently authenticated user by accessing the the HttpContext.Current.User.Identity.Name property.

So how does Silverlight deal with authentication? Well, the cool thing is that it normally doesn’t! The Silverlight control is hosted on a web page that is protected by the membership provider. That means that you have to logon before you can run the application. When you logon the ASP.NET Forms Authentication mechanism will write an authentication cookie in the browser. When Silverlight loads and starts making requests back to the server any request goes through the browsers networking stack. The browser will add any cookies or authentication headers set in the browser before sending the request. In our case the request back to the WCF service will contain our authentication cookie, and we can access the current authenticated user. All good!

SilverlightAuthentication

When I started porting the application to WPF I wanted to reuse the same WCF service used by Silverlight. But since I’m not going to logon using my browser I know that I had to provide some authentication mechanism for my WPF application. I assumed this should be fairly trivial, since one of the new features of .NET 3.5 and Visual Studio 2008 is the Client Application Services. This is a set of services enabling you to reuse your ASP.NET membership- role- and profile providers from client applications such as AJAX or Windows Forms/WPF applications. You get a full client side API to authenticate users, check their roles, or store settings online. This is handy, but I don’t quite get the point of the Membership functionality. There is no obvious way to authenticate the user using the Client Application Services and then use the same identity on other services on the same domain. All the tutorials online are limited to show how the user can change some setting and persist this using the profile services. I tried messing around with the System.Web.Security.Membership class, but couldn’t find a way to grab the authentication cookie and add it to my other service clients.

While researching what I can do with the Client Application Services I came across the WCF Authentication Service. This is part of the Client App Services, and is basically a service sitting on top of your membership provider. The service is implemented by the class System.Web.ApplicationServices.AuthenticationService, and to enable an authentication service all you have to do is configure a WCF end-point. I’m not going into all the details, but enabling the service isn’t too hard. It contains methods like login and logout, and will use whatever membership provider you have configured for your web application. It works similar to the Client App Services, and when you login it will write an authentication cookie, taking us back to the original problem of getting that cookie added to our other service clients. Thankfully it is possible to access the request and response cookies from WCF, even if it’s not really obvious how to do it. Or it could just be me not having done much WCF work… The following code calls the authentication service and logs in and grabs the authentication cookie. Next step is to add the authentication header to the other service client before calling the Dive Log service. The code smells like a little like dog-poo, but that’s what it takes to make it work.

SmellyWCFCode

I don’t know if this is the only way to use the authentication service and grab the authentication cookie. Some more experienced WCF developers recommended that I should add a new service endpoint with a wsHttpBinding (the ws-deathstar binding). You can configure your wsHttpBinding to use a membership provider for authentication, but it kind of sucks that you can’t just port a Silverlight app to the desktop without having to change your server code. While messing around with the cookie handling I remembered that this stuff used to be a lot easier before we got WCF. You can use the old web service stack from .NET 2.0 and you can even add a new web reference (not service reference) in Visual Studio 2008. However you need to dig a little before you find the dialog. You find under the advanced button in the service reference dialog, and then by clicking the add web reference button.

AddWebReference

After adding a web reference you get two folders, one for service references and one for web references. So using the old .NET 2.0 Web Services the code to authenticate and use the same cookie for the Dive Log service is a lot more compact.

WebReferenceCookieCode

I’m sure some WCF experts have a better solution for this, and I would love to hear suggestions in the comments. However I do think this is a quite common scenario if you have a set of services built using the Silverlight WCF template that you want to use in a WPF version of your application. In other cases you might not be the one controlling the server side, and I think WCF should support those scenarios. WCF have made a lot of advances, adding support for REST style services and support for username/password authentication etc. However, in cases like this where you depend on cookies for authentication it really isn’t obvious how to do that using WCF.

One of the common problems in Rich Internet Applications is browser navigation. Users are used to clicking links, moving between pages and being able to get back to where they came from by clicking the browsers back button. In Rich Internet Applications this is often not the case. You spend all your time on one page, and user interaction normally don’t navigate away from the page but invoke small web service calls back to the server. If the user clicks the back button they might end up on the login page or the page they visited before, which is not what the user expected.

There are different techniques to control the back and forward navigation in AJAX applications, but because of differences between browsers getting consistent behavior can get quite hard. Thankfully support for navigation history was added to ASP.NET AJAX in .NET 3.5 SP1, giving us a browser agnostic way of dealing with navigation history. At Tech Ed Sydney Jordan Knight gave a chalk talk showing how to use the ASP.NET AJAX client scripts from Silverlight to add browser navigation support to a Silverlight application. Jordan has now made his presentation available on his blog both as a blog post and as a screen cast.

In Jordan’s approach he uses a separate JavaScript class that encapsulates the ASP.NET AJAX functionality, and acts as a proxy object between Silverlight and the ASP.NET AJAX client library. This works really nicely, and let you reuse the same JavaScript class for non-Silverlight purposes as well. The drawback is that the code is not self-contained inside the Silverlight application, and you have to include an external JavaScript file on the page. Another problem is that his example currently only supports a single key-value pair for the history state. The AJAX framework supports any JavaScript object literal to store navigation state, something that can be useful if you need to keep track of more than one value. For example you might want to keep track of both customer id, and which view you have opened for that specific customer. In that case you would have to keep track of multiple history state values. The ASP.NET AJAX library will encode the state object into the URL of the page whenever the user adds a new history point. This means that you have some limitations to the size of the state object, as well as the complexity of the state object. You can’t have deep object structures or complex types to represent history.

I decided to see if I could find a way to add browser navigation to my Dive Log sample application without introducing more JavaScript than absolutely necessary. I also want a generic implementation that can be reused in any Silverlight application with little effort. The behavior I want to achieve is to add a history point every time the user selects a dive. When the user clicks back and forward in the browser, the application should select the previous selected dive. I also want the browser navigation code to fit nicely with the Model-View-ViewModel architecture of the application.

The first thing I did was to define the interface I want to use for the history manager. Programming against interfaces is good practice, and helps you decouple your components. The interface is straight forward, and mimics the history management functionality of the ASP.NET AJAX client library.

IHistoryManager (code available as download)

The interface has a method to add a new history point, and an event that executes when the user navigates back or forward. The interface uses a generic type for the state object.

To manage history I’ve implemented the interface on a history manager class. This class is also generic, giving the consumer of the class freedom to choose any object to represent navigation state.

HistoryManager class definition (code available as download)

The constructor adds an event handler to the ASP.NET AJAX navigate event. We want the HistoryManager class to handle the event, so the HandleNavigate method marked as a scriptable member. This means that JavaScript can access that member when the HistoryObject is passed to the browser. The code to add the event listener is based on a blog post from Rai Kaimal who uses a similar technique.

HistoryManager Constructor (code available as download)

The first thing the constructor does is to registering the HistoryManager class as a scriptable object. That means that you can start coding against the CLR object from JavaScript. The next piece of code is a string holding a chunk of JavaScript. The JavaScript does two things. First it creates a Function object, which is a concept of ASP.NET AJAX that gives you delegate-like functionality. The function points to the HandleNavigate method on the HistoryManager object we exposed to the browser. The second thing it does is to add this function as the handler for navigate event exposed by the Sys.Application object. The event was added in .NET 3.5 SP1. The final step in the constructor is to tell the browser to evaluate the JavaScript. Once the script is evaluated the HandleNavigation method will fire on the CLR HistoryManager class whenever navigation occurs.

The HandleNavigate method accepts one ScriptObject parameter which will contain the navigation state. ScriptObject is the type used for any object passed between Silverlight and JavaScript. The cool thing about the ScriptObject is that you can convert it back to a real CLR type if you know the shape of the object. In our case we convert it back to the generic type. Next step is to create the generic event argument and trigger the Navigate event.

HistoryManager HandleNavigate method (code available as download)

The next piece of code in the HistoryManager class is the AddHistoryPoint method. This method gets called whenever the Silverlight application wants to record a new point in the browser navigation history.

 HistoryManager AddHistoryPoint (code available as download)

We use the same technique to build a string of JavaScript and tell the browser to evaluate it. The JavaScript string contains a JSON representation of the state object. The ToJson method is an extension method that gives easy access to JSON serialization of any object. Preferably I would like to pass the state object directly to the JavaScript function, but because of problems with the type-system introduced in ASP.NET AJAX the parameter validation fails when I pass in a CLR type directly.

Now that the HistoryManager class is ready we can start using it in the Dive Log application. At first thought it might be a good idea to add the HistoryManager as a property on the Application object, but this would cause problems with testing. The Application object will be different when executing in a unit testing context than when executing as a standalone application. Instead I decided to make the IManageHistory interface a new dependency on the PageViewModel. This was done by simply adding a new parameter to the constructor. I also specify which type I want to use to represent the navigation state.

PageViewModel constructor (code available as download)

The Dive Log application uses Ninject for dependency injection, so next step is to register the HistoryManager in the Ninject container. This is done by adding a new line to the Ninject module configuration class.

Ninject binding (code available as download)

One interesting point about the configuration is the binding behavior. We specify that we want to use a singleton behavior for our HistoryManager. Ninject will make sure that there will be only one instance of the HistoryManager object that will be shared between any classes that has the IManageHistory interface as a dependency. For more information about binding behaviors in Ninject check out the Ninject Dojo.

Now that we have set up the binding and the Viewmodel has a reference to the HistoryManager we can start tracking navigation. In the Dive Log application we want to add a history point whenever the selected dive changes. When the navigate event fires we want to get the ID of the dive from the state object and select that dive. To make navigation work for new dives that hasn’t been assigned an ID yet we use the hash-code to identify the object. The history tracking code is added to the setter of the SelectedDive property in the ViewModel.

PageViewModel Add History Point (code available in download)

In the navigate event handler we use a simple LINQ query to check if we can find the dive and if so select it.

PageViewMode lHandleNavigate event (code available in download)

When we run the application and select dives we can see how the back and forward buttons light up. If click the pulldown menu we can see each point, and when we click the buttons we navigate between dives.

Showing history points in IE and FireFox

Summary
Deep integration with the browser is important to give an optimal user experience. There are multiple approaches to do this, but the APS.NET AJAX client library in .NET 3.5 SP1 makes it really easy. By using generic classes and interfaces we get a history manager class that is strongly typed, making it really easy to pass your own state objects between your C# Silverlight code and the ASP.NET AJAX client library.

I have deployed a new version of the Dive Log application you can play with online. You can also download the updated source code that now contains the history management classes. The code should be easy to refactor and use in your own project. Everything is self contained, making it easier to maintain and deploy your Silverlight application. The only requirement is that you have .NET 3.5 SP1 installed and a ScriptManager with history tracking turned on.

I’m back in Melbourne after 9 days on the road for Tech Ed New Zealand and Tech Ed Sydney. I had a great time, meet lots of interesting people and had many great conversations. I’ve already blogged about my Silverlight session, and all the content is now available online. Thanks to everyone who came to the session, and for the good evaluations.

Microsoft New Zealand have also published a lot of content on their Tech Ed Live site, and you can now watch my full Silverlight session online. So if you missed the session, or want the full story behind the Dive Log sample I recommend checking out the video.

In addition to my Silverlight session I also sat on a “the next 18 months - the future of the web” panel. Suzanne Tindal from ZDNet picked up some of the discussion around JavaScript and has written an article questioning if Chrome’s JavaScript poses a challenge to Silverlight. On the panel we started talking about how JavaScript is getting faster and faster, and how Chrome is upping the performance bar with its JIT compilation and JavaScript Virtual Machine. I got quoted several places in the article, which is really cool. As most of you guys who read my blog know I’m deeply into Silverlight and I have no doubt that it’s going to be an important technology in the years to come. That being said I do think that JavaScript will turn out to be a bigger competitor to Silverlight than Flash for developers deciding which technology to use for their rich Internet applications.

The ZDNet article is well written and should be an interesting read if you want to learn more about mine, Scott Hanselman and Harry Piersons perspectives on the future of JavaScript, web applications and Silverlight. The ZDNet  article also got cross posted on CNet. Paul Glazowski followed up with a new article about Silverlight battling Flash AND JavaScript over at at BuzzYa and Mashable.

With Tech Ed ANZ now being history the next big event is the Microsoft PDC conference in LA in October. I’m going and hope to see many of you guys there!

Me and Adam Cogan Jordan Knight giving a chalk talk
Playing with Surface Sydney Aquarium
Future of the web panel Auckland View 
Bondi Beach
Speaker pass Speaking

Earlier today I gave my “Silverlight 2 for Developers” talk at TechEd New Zealand. I know the title is a little bit vague, but the session was generally trying to give developers who want to build “real applications” a good starting point. It’s a level 300 talk (advanced), so it skips the basic introduction. That being said you don’t need to be a Silverlight expert to find the session useful. The talk covered things like CRUD applications using WCF, how to implement a Presentation Model/ViewModel, how to use IoC and DI in Silverlight, and how to do unit testing in Silverlight.

 Presenting at TechEd

The theme of the talk was diving, and for the demos I worked on a dive log application. The application is fairly complete, and I’ve made it available online for anyone to play with. The code should also be a good sample application for anyone who wants to get into building data centric Silverlight applications. I’m planning on building on the dive log sample in future blog posts, and already have several ideas in the pipeline.

You can run the application by clicking the screenshot. You will be asked to login, and any username and password will be valid. If the user doesn’t exist it will be created when you login. You can even run the unit tests directly from your browser if you want.

Dive Log Screenshot

Slides

I've uploaded the slides to Slide Share, or you can download the full presentation from my Sky Drive.

Links and resources

Unit Testing in Silverlight

Presentation Model / View Model

Dependency Injection

CodeCamp2008AKL Yesterday I gave a Silverlight presentation and CodeCamp Auckland. The presentation was focusing on how to apply dependency injection in Silverlight using Ninject, unit testing and the presentation model pattern. Towards the end I threw in a little HTML-bridge fun, and demonstrated the webcam in Silverlight implementation I did some time back. Rob Fonesca-Ensor had done a great job of introducing TDD, IoC and DI on an earlier presentation, so I could focus on how to apply the techniques in a Silverlight context. Ivan Towlson did a presentation on “thinking in WPF” and did a good job of explaining why you need to take a different approach to building WPF application than what you’re used to from traditional Windows Forms. I tried to tie my YouCard demo back to some of the ideas introduced by Ivan, and hope these three sessions together gave people who want to start building Silverlight and WPF applications a good starting point.

Owen Evans and Scott Hanselman had the ASP.NET part of the CodeCamp covered. Owen talked about ASP.NET MVC while Scott did a session on ASP.NET Dynamic Data. There more I see of Dynamic Data, the more intrigued I am by it. I think people easily dismiss Dynamic Data as just scaffolding and code generation. Scott made a point of this, and really went through the details of how a Dynamic Data application is built up. No magic or code generation, all meta-programming.

All in all this was an excellent CodeCamp, the second one I’ve attended. I presented at the Australian CodeCamp back in April. Kirk Jackson and gang did a great job of organizing the CodeCamp. I think we need to get a CodeCamp started back in Norway as well.

I’ve put together some references and links if you want to dive deeper in some of the topics I covered in my talk, as well as download links to the demo applications.

Unit Testing in Silverlight

Presentation Model / View Model

Dependency Injection and Ninject

HTML Bridge

Demos
You can download both the Web Cam and YouCard demo applications from my Windows Live Sky Drive. I've also uploaded the demos so that you can play the Sliding Puzzle Game or check out your friends using YouCard. You can even run the unit tests directly from your browser! Hope you found my presentation useful. Feel free to post any questions, comments or feedback.


On the Silverlight.net forums there are several questions about how to configure Silverlight applications. A common question is how to change the URL of a WCF service you are consuming. Another common question is how pass in some user defined configuration settings. There are several interesting solutions, and a couple of days ago Bill Reiss posted an article about “Calling WCF on the server of origin from Silverlight”. Bills solution involves using the HTML Bridge to grab the current URI, and building up the URL of the web service, and then creating the service client using one of the constructors allowing you to manually specify binding and endpoint. This is all cool and really helpful in many cases, but the ServiceReferences.ClientConfig file is there for a reason. I think a lot of developers are a bit confused about how to use this file. And I don’t blame them. In Silverlight 2 Beta 1 this file was generated by Visual Studio, but was not read by the WCF runtime. In Beta 2 this was fixed, and the WCF runtime will now read and use the configuration file.

A lot of developers are afraid they have to rebuild their application to change web service configurations; something Bill also write in his blog post:

This is fine if you're hitting a service like Digg or one of the other public web service APIs out there, but not if you want to be able to test on your own machine and also deploy the same XAP to your server without rebuilding.

You could go ahead and change this to the URI on your server and rebuild, but then it won't work locally for testing unless you have a crossdomain file on your server, and you would be hitting your server's web service, not your local one while testing.

When building a Silverlight 2 application Visual Studio 2008 will spit out a XAP file in the Client Bin directory. The XAP file is just a standard ZIP archive containing some assemblies, the configuration file, a manifest file, and any resources you might have added to your project and market as content. It’s completely safe to rename it to ZIP, unpack it, make changes to the ServiceReference.ClientConfig file and package it all back together to a XAP file. Turns out repacking your XAP file is actually a good idea. Back in May Valeri Hristov discovered that he could chop 1MB of a 3MB large Telerik example application by repackaging it using the 7Zip application. Later David Anson followed up with some more examples showing a 22% average saving by repacking the XAP file… Why Microsoft is using such an inefficient ZIP implementation I don’t know –hopefully this will be fixed before release. Until then creating a post-build event that repackages your XAP will probably be the easiest 22% savings you will get all day.

Content of a XAP file

Anyway, let’s get back to configuration. Now that we can reconfigure our Silverlight application without rebuilding it we might be able to use the configuration file for more useful stuff. Silverlight does not come with a full configuration API like the full .NET framework. You do have the System.Configuration namespace, but it only contains some internal, abstract classes used by the Silverlight WCF stack. If you search for “configuration” in Reflector targeting Silverlight 2.0 you get some hits in the System.ServiceModel.Configuration namespace as well. It got configuration section handlers used by WCF to read information about your web service bindings and end points. All classes are internal and not really helpful for handling general application configuration.

Since the ServiceReference.ClientConfig is a plain XML file there is nothing stopping us from adding our own elements to the file. I decided to use the application setting convention we’re used to from .NET, and added an appSettings element with a bunch of key-value pairs elements. The application continued to run just fine with these additional elements. I also tried adding and removing service references from Visual Studio to see if it would screw up my changes. Thankfully Visual Studio only touched the serviceModel element, and didn’t care about our appSettings element. The ServiceReference.ClientConfig file now looks something like this:

configsample1

This is quite handy, as we can keep all application settings in one file using a format developers know. Next step is writing some code to read the configuration file. I decided to mimic how things work in the full .NET framework by creating a ConfigurationManager class with an AppSettings property. To parse the configuration file I used LINQ to XML which made it really easy to extract the key-value pairs.

configsample2

In the full framework the AppSettings property is of type NameValueCollection. This collection does not exist in Silverlight, so instead of re-implemented it I created a simple class backed by dictionary, exposed as an index property.

configsample3 

You read the application settings the same way you are used to from any .NET application:

configsample4

Hopefully this post gives you a better understanding how Silverlight 2 applications are packaged, and how to configure your application without rebuilding it. If I was consuming WCF services in my project I would add configuration management to my automated build process. It would be fairly simple to write a build script that repackages the XAP with a more efficient ZIP implementation, as well as building different versions for test, staging and deployment.

Back in may I posted about a way to get basic webcam support in Silverlight by integrating Flash. The post got some good feedback, and lately I’ve gotten a few requests to update the application for Silverlight 2 Beta 2. I have now done that, as well as adding a new sample application using the webcam support for something (somewhat) useful.

The new example application is called “Webcam Sliding Puzzle” and extends a picture puzzle game written by Cigdem Patlak and adds support for capturing pictures from your local webcam. The original game supported reading images from your local computer using the open file dialog in Silverlight, so adding support for webcam images was fairly straight forward. Click the screenshot to try out the game.

Webcam Sliding Puzzle

If you want to learn how to add webcam support in Silverlight I recommend checking out my older post “Webcam in Silverlight 2 - MacGyver style!” For more details on integrating Silverlight and Flash check out the article “Silverlight and Flash Interoperability using HTML Bridge and ExternalInterface API” I wrote for www.silverlightshow.net.

The iPhone showed that it is possible to squeeze the real web into the users’ pockets. But there are still limitations, the big one being support for third party plug-ins such as Flash, Silverlight and different media players.

An article on TechCrunch showing how to access the NBC Olympics Silverlight 2 player from a Nokia phone really caught my attention. Sure, Nokia have announced Silverlight Mobile support, but no details are available yet, and certainly not a public beta. It turns out Skyfire, the browser used to watch Silverlight 2 content on the mobile, takes a completely different approach to mobile browsing than the iPhone. On the iPhone you’re running the full Safari browser, doing all the heavy lifting on the device. The Skyfire browser uses remote rendering of the page. This is similar to the Operas successful mobile browser, which uses a proxy that downloads the page and recompresses images and re-arranges the HTML to a format better suited for mobile devices. The Skyfire takes this approach one step further and does all the rendering on the server and having the mobile device act as some sort of remote desktop client. Their FAQ is fairly cryptic about the details of how the rendering is done, and they obviously have done some smart things to make this fast enough to stream to a mobile device.

Skyfire Logo

Q: How is Skyfire able to render the PC Web?
A: Skyfire's proprietary technology enables us to support the real web both now and in the future as new web technologies are implemented. We have created a brand new architecture that's server assisted. It's an asymmetric distributed approach where the server does the heavy lifting so the client is high performing.

Q: Seriously, how does Skyfire do all of this?
A: The only way we can tell you this is if you join our team. We're hiring bright, passionate folks who want to completely change the way the Internet works on mobile phones.

Skyfire is currently in private beta, running on Nokia Series 60 phones and Windows Mobile 5 and 6. I’m using the iPhone, and haven’t been able to try the browser myself. But I strongly recommend checking out this video showing the NBC Olympics Silverlight player on a Nokia device.

Is this the future of mobile browsing? I don’t know – And I have no idea if this would be able to scale. I’m not sure if Skyfire is talking to their back-end server which does the rendering, or if Skyfire includes both a mobile client, and something you have to install on your local PC to get it to render your page, upload it to Skyfire servers, and then stream it down to your device... No matter which approach they take, the demos do look impressive.

The session catalog for Tech Ed Australia and Tech Ed New Zealand has been available online for a few weeks now, but I haven’t gotten around to blog about me speaking at TechEd. I will be speaking about “Silverlight 2 for Developers”, as well as sitting on a panel discussing “Web Futures - the next 18 months”. The panel will also be comprised of Scott Hanselman, Nigel Parker, and Trent Mankelow. In Sydney I have a 10 minute quest appearance in the Visual Studio track showing my favorite .NET 3.5 SP1 feature.

The abstract for my Silverlight talk goes like this:

Silverlight 2 enables you to build some stunning web applications. But it's not all about eye candy. Silverlight 2 brings the power of .NET to the browser. This requires some new thinking in the way we build web applications. In this session we will focus on Silverlight 2 from a developer's point of view. This session will show you how to write code that both you and your designers can work with, by separating out business- and data access logic and leveraging the power of data binding in Silverlight. The session will also cover development practices such as unit testing and continuous integration, as well as more technical topics such as network- and data access, local storage and more. You will also learn a few tips on how you as a developer can leverage Blend 2.5

As you can see by the description I don’t want the session to be yet another “introduction to Silverlight 2” presentation. I will cover concrete things such as how to build a data driven CRUD application in Silverlight, talking to web services and using features like data binding and the visual state manager. However, I also want to cover design patterns and development practices that can help you build more flexible, testable and designable (as in UI design) code.

CodeCampNZ Logo The day before Tech Ed the New Zealand development community is putting together Auckland Code Camp 2008. Since I’m in town I got invited to do a presentation, and I had such good time at CodeCampOZ earlier this year that I couldn’t say no to that invitation. Robert Fonseca-Ensor is doing a TDD and DI/IoC talk in the morning, so I will use part of my session to build on that and show how to use Ninject to do dependency injection in Silverlight 2. I will also cover some more advanced Silverlight 2 testing scenarios, such as writing asynchronous tests, before finishing up with some HTML Bridge fun.

Tech Ed New Zealand, Auckland (1– 3 September 2008)

WEB304 - Web Futures - the next 18 months (02/09/2008 10:45AM-12:00PM)
Where is the web going over the next 18 months and what is in the pipeline from Microsoft to cater for and drive this? Is Microsoft up to the challenge? How is Microsoft working with the part of the web that is not MS based? How is Microsoft changing to cater for emerging trends? Submit your questions and hear the answers from the experts.

WEB309 - Silverlight 2 for developers (03/09/2008 9:00AM-10:15AM)
See description above...

Tech Ed Australia, Sydney (2 – 5 September 2008)

WEB309 - Silverlight 2 for developers (04/09/2008 8:30AM-9:45AM )
See description above...

WEB304 - Web Futures - the next 18 months (05/09/2008 10:15AM-11:30AM)
See description above...

DEV210 - The Hour of Power: 6 of the Best - Best of the Best in VS2008, Fx 3.5 inc SP1 (05/09/2008 8:30AM-9:45AM)
Rock on up to the “Hour of Power” this will be a fun energy packed session presented by 6 speakers each speaking for 10 minutes on their favourite feature(s) in Visual Studio 2008 and Fx 3.5 including SP1. It’s a must see session and a great way to pick up a few new tips and tricks!!

Going to TechEd Australia or New Zealand? Or got any questions, suggestions or ideas to things you want me to cover? If so, it would be awesome if you drop me a comment.

When building line-of-business (Smart Clients or Rich Internet Applications) you normally talk to some back-end web service responsible for enforcing business rules, authentication, and storing your data in some database. When implementing your client application you often end up re-implementing some of these business rules to give the user a better experience. Instead of having to pass an Order-object to the web service just to get an exception saying that the order date field is a required, you should try to enforce these validation rules directly in your user interface. How do you best implement these rules across your tiers?

Sharing is caring!

In his January 2004 MSDN article title "A Guide to Developing and Running Connected Systems with Indigo" Don Box presented four rules for connected systems, later often referred to as “the four tenets of SOA”. The rules are as following:

  • Boundaries are explicit
  • Services are autonomous
  • Services share schema and contract, not class
  • Service compatibility is determined based on policy

Especially rule number three is relevant when talking about implementing business rules on both server and client. In traditional object oriented design you would implement your domain- or business objects and let them encapsulate your rules and logic. One of the advantages of web services is that they work across boundaries and platforms. They also help you make your systems loosely coupled, only depending on the service contract and not a specific binary component. Web services use open standards such as HTTP, SOAP and XML to achieve interoperability and louse coupling.

Services do not deal in types or classes per se; rather, only with machine readable and verifiable descriptions of the legal "ins and outs" the service supports. The emphasis on machine verifiability and validation is important given the inherently distributed nature of how a service-oriented application is developed and deployed. Unlike a traditional class library, a service must be exceedingly careful about validating the input data that arrives in each message. Basing the architecture on machine-validatible schema and contract gives both developers and infrastructure the hints they need to protect the integrity of an individual service as well as the overall application as a whole. – Don Box

Blindly following the rule about not sharing class can lead to developers and architects forgetting what they know about object oriented design. This is something I have experienced on several projects. However, there is nothing in Don Box reasoning stopping you from building some really smart classes or libraries to help you consume and talk to these web services. Most development platforms have some sort of tool support to automatically generating proxies to create the SOAP messages needed to communicate with the service. However, since these classes are all generated based on WSDL and XSD definitions they don’t contain any "smarts", like validation rules, authorization, or computed properties.

There are different techniques to achieve sharing of some logic between server and client. An old trick is to move all your business entities into a separate assembly and use this on both server and client. After Visual Studio have generated a web service proxy you remove any generated types and include a using statement to the namespace containing your business entities. When the proxy de-serializes an Order-object from your web service it will create a "real" Order-object instead of an auto generated type. This object will have any validation rules or computed properties, which would be lost in the auto generated type. In Visual Studio 2003 and 2005 you had to do this by hand, which was bothersome, and something you had to redo every time you update your service reference. In Visual Studio 2008 this pattern is supported by the tool. When adding a new service reference you can choose to reuse any types in referenced assemblies, letting you use real objects instead of automatically generated proxy objects.

When working with Silverlight this is a little bit harder. The problem is that the client Silverlight .NET runtime is different from the server .NET runtime. You can’t directly reference a Silverlight class library in your web service application, or reference a traditional .NET class library in your Silverlight application. There are workarounds to help you share code between a .NET server application and a Silverlight client application. You can create two different class libraries, one for Silverlight and one for the server, and link the class files between them. You have one copy of the file, but it’s added to two different projects, letting you compile the same class into two different assemblies. Since Silverlight is a subset from .NET you may not be able to do all the same things in the client library as in the server library. You can separate out Silverlight and .NET specific code using compiler directives or partial classes.

#If Silverlight then 
	// Silverlight only code 
#Else 
	// .NET only code #End If 

This is the approach taken by Rockford Lhotka in CSLA Light, a trimmed down version for Silverlight of his CSLA.NET application framework. He recently started blogging about how CSLA Light helps you reuse business objects between tiers. This approach might be difficult if your server code have many external dependencies, for instance to ORM tools or other frameworks you don’t have a Silverlight version for.

Extending the automatically generated types

The web service proxies generated by Visual Studio have gotten better and better, and the classes generated by Visual Studio 2008 are quite useful. Sure, they won’t know about server specific rules, but the generated objects use properties, implements change notification and use observable collections for lists. This enables you to data bind against the proxy objects, which is really handy. However the solution isn’t perfect. One of the features added in Silverlight 2 Beta 2 is the support for binding validation. This enables you to detect if the data entered by the user in a data bound field breaks any validation rules. When the binding validation event fires you can highlight the field, for instance by changing background color. The way binding validation works in Silverlight 2 Beta 2 is by exceptions thrown in the setter of a property. If you bind against the automatically generated proxy objects you can’t change the setter to implement your validation rules.

Another example where you want to extend the proxy objects with additional functionality is for computed properties. Since I just got back from a dive trip I’m going to use that as an example. When logging a dive you enter date, time in water, bottom time and time out of water. If I were to implement a dive log application I would store the time the diver entered the water and the bottom time in the database. The time out of water would be a computed property, computed adding the bottom time (minutes) to the time the entered the water time. If I did this on my server, the data would get passed to the client, but the automatically generated proxy object would see this as any other "dumb" property. It wouldn’t understand the relationship between time-in water, bottom time and time-out of water. If I change the bottom time, the time out of water property wouldn’t change.

To solve these problems you have two options. You can choose to treat your web service objects as simple data transfer objects, and wrap them in your own custom client side objects. This can be done by creating a new DiveLogClient-object that takes the DiveLog proxy object in the constructor, and creates new properties for any field used by the UI. This approach gives you full flexibility but involves doing a lot of extra work. Another option is to create a partial class that extends the automatically generated proxy object. This class could add new properties, like TimeInClient, TimeOutClient and BottomTimeClient, which use the same private backing fields as the generated properties, but have additional logic needed to understand the relationship between time-in, bottom time and time-out. Your user interface would bind against the new properties instead of the generated properties, but since they use the same backing fields for their values you can still send the object back to the server to store any changes.

Is Microsoft doing anything to help?

Wanting to share some logic between the server and client is a common pattern. Surely Microsoft must be thinking about how they can help. By improving the service reference tool in Visual Studio Microsoft made it easier to share types across boundaries. But there is still allot that can be done. The Smart Client Software Factory contains functionality to map between service entities and business entities, which let you build richer business entities on the client, and get some framework support to map between the different types. But I’m sure they can do better…

Yesterday Microsoft announced 50 new session abstracts for PDC 2008 held in October. It’s really interesting to read the session abstract to get some ideas of unannounced products and project they are working. One of the sessions that caught my attention is "Microsoft Silverlight: Building Business Applications":

What if you could develop your solutions with the ease pioneered by Microsoft Office Access, deploy them like an Internet application, and take advantage of the power of Microsoft .NET? Learn about an exciting new technology that is all about making business applications for RIA (Rich Internet Applications) much easier to build. In this session, hear how we've made n-tier application development as simple as traditional 2-tier, provided application level solutions to developers, and how we're doing all of this with the same .NET platform and tools on both the client and server.

I guess it’s safe to assume that Microsoft have some really cool stuff in the works. Which approach they take to make n-tier development as simple as traditional 2-tier development I don’t know. But I wouldn’t be surprised to see some kind of smart sharing of linked code files, with partial classes or compiler directives to separate server and client code. It’s also interesting that SOA-expert Pat Helland has been working on a project in the area of RIAs, so hopefully he has been able to provide some valuable input on how to architect RIAs.

Which approach do I use?

Well, it depends… For larger Silverlight projects I tend to consider the automatically generated proxy objects as dumb data transfer objects that I wrap in business objects used by my Silverlight application. The advantage is that I get full control over the object, but the drawback is that I have to do more manual work… For smaller projects where I need minor changes I tend to use partial classes to extend the proxy objects with additional properties used by the client, but backed by the same fields as the properties that get serialized when sending the object back to the server. In the long run I’m a strong believer in tools or frameworks that help us reuse code between server and client in a clean way giving us something smarter than the proxies generated by Visual Studio. Frameworks like CSLA Light or the tools Microsoft will announce at PDC will probably help to deliver this. I expect the announcements at PDC to be to Silverlight what ASP.NET Dynamic Data is to web application. Dynamic Data lets you scaffold a complete data driven application, but without compromising customizability or generating tons of hard to maintain crappy code.

How do you share business logic between server and client?

In an earlier post this week I wrote about implementing the Model-View-ViewModel pattern in the YouCard application. In this post I’m going to build on that and implement Inversion of Control Containers and the Dependency Injection pattern. Lots have been written about dependency injection, so the focus of this post will be on using dependency injection in a Silverlight context, and specifically how to implement it using the Ninject framework. For an excellent introduction to the pattern I strongly recommend Fowlers essay on the topic.

When getting into dependency injection you might get intimidated by the number of frameworks available to help you implement the pattern. It might give you the impression that dependency injection is something big and complicated, which is going to have a huge impact on how you build your software. The later might be true, but not necessary because of the framework but rather by the flexibility gained by introducing this pattern. In its simplest form dependency injection is about how you supply external dependencies to your application classes. In the previous blog post I refactored the Twitter and Flickr integration into external classes that complies with an interface. Depending on if the code was executed inside Blend or the browser I either use the real implementation, or a mock implementation providing some dummy data at design time.

Code sample 1

The problem with the above code is the coupling between the YouCardData class and the four classes implementing the IMicroBlog and IPhotoService interfaces. This high level of coupling between the view-model (YouCardData) and its external dependencies (Twitter and Flickr) makes the code less flexible. Coding against interfaces enables me to implement other services, such as a Picasa photo service, or a Tumblr micro blog service. The problem is how I get the YouCardData class to use these alternative implementations. The code is also hard to unit test as I can’t provide a mock implementation of the external services. We could refactor our code to take the external dependencies as constructor parameters like this:

Code sample 2

By doing this we allow the consumer of the YouCardData class to inject the external dependencies through the constructor. And in essence this is constructor based dependency injection, by hand. The above change gives us greater flexibility to provide alternative implementations of the services, either for testing purposes, or to provide new functionality. But there is still a problem with the code. If you want to create an instance of the class from XAML, for instance when setting the data context, a default parameter less constructor will be used. You could solve this limitation by adding an additional constructor like this:

Code sample 3 

This would solve the XAML problem, as any instance crated declaratively would use the Twitter and Flickr implementation, but for testing purposes we could provide our own mock implementation. But the solution still isn’t perfect. In the first constructor we had code to check if the class was consumed inside Blend or not. Depending on this we used different implementations of the external services. We could have kept this constructor, but instead we’re going to use an Inversion of Control container to help us build our objects.

Ninject

Lately I’ve been doing some research on UI frameworks and patterns, and many of these use some sort of dependency injection framework. The Prism-AG framework, a Silverlight port of the Composite WPF framework, uses a small dependency injection framework called DLLite. Another dependency injection ported to Silverlight is Unity, another framework from the Microsoft patterns and practices group. But my personal favorite so far is Ninject, the ninja of dependency injection. This framework caught my attention after listening to Nate Kohari in episode 5 and 6 of the AltDotNet podcast. Ninject describes itself the following way:

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

You shall feel my wrath as I rip you apart to inject my powers into you!

The footprint of the compiled framework is only 110KB, and you only need a single reference to Ninject.Core.dll too getting what you need in most scenarios. Strength of Ninject is the focus of configuration through code instead of XML. Most other IoC containers have a strong emphasis on XML based configuration of object dependencies. This has its advantages if your deployment environment varies a lot between installations, but in many cases this adds additional configuration pain.

  1. Your configuration can get more complex and verbose since you often have to write out fully qualified assembly names for each type.
  2. Its easer to break the application through simple typing mistakes.
  3. If the rules describing how to write your application together gets complex this might be hard to express through XML.

In comparison, Ninject uses a fluent interface, or sometimes referred to as "embedded domain-specific language". This lets you take advantage of the programming language to build up the wiring of your application. You can express complex rules of how the wiring should happen, and there is nothing stopping you from writing code that reads a configuration file if some of the wiring depends on user configuration.

"… There are cases where it’s easier to use program code to do the assembly. One case is where you have a simple application that’s not got a lot of deployment variation. In this case a bit of code can be clearer than separate XML file.

A contrasting case is where the assembly is quite complex, involving conditional steps. Once you start getting close to programming language then XML starts breaking down and it’s better to use a real language that has all the syntax to write a clear program.

…My advice here is to always provide a way to do all configurations easily with a programmatic interface, and then treat separate configuration file as an optional feature. – Martin Fowler"

Another cool aspect of Ninject is that it support Silverlight “out of the box”, and is not a port or a trimmed down version of a larger framework. Ninject was small to begin with.

Dependency Injection with Ninject

Adding Ninject support is fairly straight forward. The first thing we need to do is add is marking all constructors that take the dependencies, and mark it with a simple attribute.

Code sample 4

We also want to inject a persistence service into the main page view-model, the one controlling all the cards on screen. The persistence service is used to store all the users added, so that we don’t have to add them again when we come back to the application.

Code sample 5

If we use the Twitter service implementation we also want to inject a proxy URL. This is because Twitter doesn’t allow cross-domain callers and we need to proxy the request through our own server.

Code sample 6

The next thing we need to do is to wire the view-models to the services they need. In many IoC containers this is done through XML configuration, but in Ninject this is done through code and a fluent interfaces. Ninject uses a concept of modules to wire things together. One kernel (the container) can host multiple modules. For the YouCard application we need only one module.

Code sample 7

The benefit of fluent interfaces is increased readability of the code, so I’m not going to spend too much time describing the class line by line. The class derives from StandardModule, and overrides the Load method. In the Load method we set up the binding between the services and the concrete types. If you read the binding as “English”, from left to right, the binding rules should be fairly straight forward. Also worth notice is how I take advantage of configuration through code when I decide which implementation to use when the code is running inside Blend. I add a condition saying that the Twitter service should be used when executing inside the browser, while the mock service should be used from Blend.

To use the module I simply have to create a Ninject Kernel and pass it the module.

Code sample 8 

Notice how I don’t have to worry about constructing the YouCardData object. The kernel takes care of instantiating the object, and injects any dependency based on the bindings configured in the YouCardModule.

Data binding to objects built by Ninject

Now that we have configured our Ninject kernel the next challenge is getting our view-model objects out of the kernel and into the views, without breaking the design time experience in Blend. Setting the data context through code would be fairly simple. We could create the kernel in the application class, and then get it doing something like this.

Code sample 9 

That would enable us to have one kernel for the application (something you typically do). But it still wouldn’t solve how to set the data context of a user control to view-model built by Ninject, using declarative XAML code. This troubled me for a few days, and after thinking it through, trying some different approaches, and talking discussing it with Nate Kohari the solution turned out to be Service Locators. This is a different pattern used to implement Inversion of Control, and often you decide to use either service locators or dependency injection. I recommend reading the section on service locators vs. dependency injection in Fowlers essay for a good description of the pattern.

The short version of the pattern is that a service locator is a registry holding references to all the services used by your application. A class, such as the view-models in YouCard, can ask the service locator to give them an implementation of IPhotoService or ITwitterService. The big difference between service locators and dependency injection is that with SL your classes asks for an implementation, but with DI they are given an implementation (pull vs. push). Nate has blogged about how Ninject plays nicely with service locators.

"I don’t think that service locators and dependency injection are mutually exclusive; in fact, I’ve found that it can actually be very effective when used in conjunction with a dependency injection framework like Ninject. – Nate Kohari"

The service locator I’ve created for YouCard is fairly straight forward.

Code sample 10

In many cases you implement the service locator as a static class. That was not an option, as Silverlight 2 doesn’t support data binding to static classes. The way I solved this was to make a static constructor, and a private, static kernel field. The static constructor is the first thing executed in the class, before any standard constructors. The static constructor checks if we have a kernel and if not it instantiates one using module containing our binding configuration. By making the kernel field static we can ensure that we have only one instance of it in our application. The class has two instance properties that surface our view-models from the kernel, as well as a generic instance method to get any object from the container.

Before introducing dependency injection we bound our views to the view-model declaratively like this:

Code sample 11

After introducing a service locator we need to change this around a little. The first thing we do is to instantiate the service locator as an application level resource:

Code sample 12

Then for each of the views we need to change how they get their data context.

Code sample 13

Each of the views gets their view-model by data binding to properties on the service locator. The coolest thing about this approach is that we still get full Blend design time support with sample data provided through the mock services.

Conclusion

Introducing dependency injection in Silverlight isn’t any harder than in other .NET applications. The strong focus on keeping the framework light weight and extremely fast makes Ninject a perfect fit for Silverlight. However, one could argue that for a simple example like this Ninject isn’t really necessary. I could hand-write the dependency injection code inside my service locator, and eliminate the Ninject dependency, and still get the flexibility of dependency injection. On the other hand, Ninject is only 110KB (before it’s zipped into the XAP file), and isn’t going to add a lot of download weight to your application. 100KB is less than half the size of the images used as illustrations in this blog post...

Seperation of Concerns - The way of a true master

By using dependency injection you keep your code more flexible and testable, something that is just as important for Silverlight applications, perhaps even more, are UI requirements are likely to change a lot as you discover the power of Silverlight. I strongly believe in providing designers with a best possible experience inside Blend, and there is no reason for dependency injection to change that.

The Model-View-Control (MVC) pattern is more popular than ever. Microsoft has now jumped the bandwagon with its ASP.NET MVC framework. Other popular frameworks like Ruby on Rails, Django (Python) and the Spring MVC Framework (Java) all implement this popular pattern. The MVC pattern fits nicely into the request-response based nature of the web. As a request comes in, the controller makes a decision on what needs to be done, talks to the model and hands of the rendering responsibility to a view engine.

Silverlight on the other hand, even if it is running inside the, has more in common with rich client application frameworks like Windows Presentation Foundation than traditional web applications. This requires different thinking when it comes to architecting the application. In this post I’m going to talk about the View-Model-ViewModel (MVVM) pattern or as Fowler call it; the Presentation Model. As an example I’m going to re-factor my YouCard application to use this pattern.

Jon Gossman and Dan Crevier have blogged about the MVVM pattern in a WPF context, and recently Nikhil Kothari wrote an excellent post titled "ViewModel Pattern in Silverlight using Behaviors". Martin Fowler has also written about this pattern, but under a different name; the Presentation Model. What makes ViewModel so interesting for Silverlight and WPF applications is that it lets you take full advantage of the strong data binding support in Silverlight and WPF. One of the key concepts of the MVVM-pattern is to define specialized models that are tailored for a specific view (user interface). The view-model may contain special fields like IsDiscountingEnabled, or PageTitle that may be based on one or more fields form your under laying domain model. Your IsDiscountEnabled field might be based on whether or not the logged on user belongs to a specific group that have the permission to give discounts, but the actual view does not know or care about this. The view only cares about the IsDiscountEnabled field of the view-model, and is not coupled to the domain model. The view and the view-model are highly synchronized, while synchronization between the view model and the domain model only happen at certain points, like when the user hits the Apply or Save button. How you implement this synchronization between your view and your view model depends on the technology you use, but even Fowler suggests that this can be done through data binding:

Probably the most annoying part of Presentation Model is the synchronization between Presentation Model and view. It's simple code to write, but I always like to minimize this kind of boring repetitive code. Ideally some kind of framework could handle this, which I'm hoping will happen someday with technologies like .NET's data binding. – Martin Fowler

The synchronization code Fowler is talking about is the code where you move values from the name-textbox to the name-property on your Person object. I’m sure we’ve all written that code and can agree that it’s both boring and repetitive! Thankfully data binding has improved a lot since the .NET 1.1 and Windows Forms days, and in WPF and Silverlight data binding is a natural choice for implementing this synchronization.

YouCard Screenshot

The application I’m going to use as an example of this pattern is my YouCard application from REMIX Australia. At REMIX I talked about Silverlight 2 for designers. The focus of the talk was about using Blend 2.5 to build and design applications. The core of the application is a YouCard user control, which is data bound to a YouCardData class. This class contains functionality to retrieve data from Twitter and Flickr, and acts both as the model and the view-model for the application. It contains View-specific fields like Tweet, Name and Bio, which all are extracted from the Twitter-feed downloaded from Twitter using HTTP requests. The YouCardData class starts a timer that downloads new data from the Twitter or Flickr at given intervals. To follow good programming principles like single responsibility, I’m going to split the Twitter and Flickr functionality out to external classes. These classes will be our Model. The responsibility of these classes will be to download and parse XML into objects. The YouCardData class will become our ViewModel and will be responsible for using the Twitter and Flickr service in a way that makes sense for the View, and surface up any fields needed by the UI. Since the original design of the YouCardData class was built to highlight the strong support for data binding- and design time support in Blend 2.5, we have a good starting point for this refactoring job. The following diagram shows the current design (left) and the desired design after some refactoring:

youcardviewmodeldiagram

The first thing that needs to be done is to define some interfaces for the external services. Instead of defining an ITwitter or an IFlickr interface I have decided to use more generic names like IMicroBlog and IPhotoService. That makes more sense if we ever want to support FriendFeed, Picasa or perhaps Windows Live Photo Gallery. I am going to refactor the existing code into two concrete implementations of each interface, one for the real online service, and one mock implementation with dummy data. As I mentioned earlier this application was written as a demo for the creative track at REMIX, and to provide a good design-time experience in Blend we need to generate dummy data when the code is being consumed by the designer. If you are going to benefit from the designer-developer workflow XAML enables, you need to start thinking about how your code behaves inside the design tool. In the current implementation dummy data is provided in the YouCardData class through an if-statement in the constructor checking if we’re running inside Blend or not. If we’re running inside Blend the YouCardData class will use a mock implementation of the Twitter and Flickr services. If it’s running inside the browser it will start a timer and begin to download data from Twitter and Flickr using the real implementations. The important part of the YouCardData constructor now looks something like this:

 Code sample 1

You might notice that this code screams for some dependency injection, and that is exactly what I’m going to cover in my next blog post. We check the type of the current application object. Blend provides its own application object, while actually running the application gives us our own application object.

The next piece of the application that needs some refactoring is the main user interface. By that I mean everything around the cards. Today the application contains one text box where you enter in a Twitter-username, and an add-button to add a new card. In the click-event handler we instantiate a new YouCard user control and add it to a stack panel. We also hook up an event handler listening for a close-event fired by the YouCard control. If the event fires we remove it from the stack panel. This approach is bad for a number of reasons. The main problem is that we are building too much behavior and logic into the view (the code behind of the XAML page). For instance the designer doesn’t have the freedom to change from a stack panel to a flow panel without changing the code. It’s also hard to unit test the code since much of the application logic is bound to specific UI-controls and UI-events.

To solve this problem we create a new view-model that contains an observable collection of YouCardData objects called Users. This collection is bound to an items presenter control, which uses the YouCard user control as its data template.

Code sample 2

With both pieces of UI bound to view-models we have now control over how we display data. But this is just half the story of an application. We also need a way to interact with the view-model as the user adds or removes cards.

YouCard interaction photo

In the YouCard application there are two points of interaction that affects the view-models, the textbox and button to add a new user, and the red button to remove a card from the list. The user can type in a username and hit enter, or click the add button to add a new item to the Users collection. The add button should only be enabled if the user name is valid. When the user clicks the close button of a card we need to remove the item from the collection in the view-model. In this case it involves communicating from one view to the view-model of a different view. The YouCard user control needs to tell the view-model for the main UI to remove itself from the list.

The most obvious solution could be to add a click event listener on the add button, and call methods on the view-model to add a new users. We could listen to the text changed event of the textbox to validate the input and enable/disable the textbox based on the text. We could also add an event to the YouCard control that gets fired when the user clicks the red button. The main view could listen to this event, and remove the corresponding card from its view-model. The problem with this solution is again that we will be baking logic and behavior into the views, which should be owned by the designer. It also makes it harder to unit test things like the validation rules, and that any users added or removed is persisted to the local machine using isolated storage (the application stores the list of cards you have added).

To solve the interaction between the view and view-model we’re going to apply the command pattern. The command pattern enables us to encapsulate an action into a command object. The command object normally contains an execute method, a name and description, and some information about whether or not the command is enabled. A single command can be attached to multiple UI elements. You might want to invoke the open-file-command from a button, a keyboard shortcut and a menu item. WPF have built-in support for Commands, but this is not included in Silverlight 2.

Nikhil introduces some really cool ideas on how to enable command-like functionality through Silverlight behaviors. This is the same concept used to extend ASP.NET controls with AJAX behaviors. In his first ViewModel post Nikhil uses the following syntax to invoke commands from XAML:

Code sample 3

Using an attached property he adds a behavior to the button which invokes the Search-method on the view-model, passing in the text property of the search textbox as the parameter. In a follow-up post Nikhil shows how he managed to get the syntax even more compact using the Dynamic Language Runtime:

Code sample 4

The cool thing about this approach is that you can write any dynamic language expression into the attached click event. This can include method invocations and getting parameters from other elements on the page. This gives you amazing flexibility to link your view to your view-model. The problem with this approach is that you get a dependency to the dynamic language runtime, which will affect the size of your Silverlight application. But more importantly for me it breaks design time support in Blend 2.5, so we need to find an alternative approach.

I decided to use a more classic command pattern implementation found in the "Silverlight Extensions" project on CodePlex. The project contains controls, helper classes, extension methods and more. Since we’re only interested in the command pattern implementation I decided to move those classes into the YouCard project. The XAML for our textbox and button now looks like this:

Code sample 5

The textbox is bound to a Username-property on the view-model. Both controls invoke the AddCard-command, using the username of the view-model as the command parameter.

The commands are defined like this:

Code sample 6

The static Commands-class holds a reference to all the commands available in the application. When instantiating a new Command-object it gets added to a static dictionary on the Command-object, caching any command object created by the application. When using the CommandService-attribute from XAML, the CommandService class will link the UI-element with the correct command using a CommandSubscription class. When the user clicks the Add User-button, or hit enter in the textbox, the CommandSubscription-class will listen for the correct UI-event and trigger the Executed-event for the correct Command-object. Any class that wants to take action when this command executes simply listens to the Executed-event of the Command object. In our case we want to handle adding or removing cards in the view-model class:

Code sample 7

Also worth mentioning is the enabling/disabling of the Add User-button. This is done through data binding the IsEnabled-property of the button to an IsAddEnabled-property of the view-model. The IsAddEnabled-property looks like this:

mvvp-code8

The textbox is bound to the Username-property, which will trigger the PropertyChanged-event for the IsAddEnabled-property. In the getter of the property we apply the validation rules that decide whether or not the button should be enabled.

Hopefully this post gives you another example of how the Model-View-ViewModel can help you keep as much code as possible out of your user interface. The strong data binding support in WPF and Silverlight makes this pattern particularly interesting, as you don’t have to worry about synchronizing your view and your view-model through hand written code. Using commands you can separate the actions of your application from the concrete UI-element invoking it. This gives your designers the freedom to choose which UI elements to use to invoke different actions in your application. Best of all, we’ve been able to do all this without breaking design-time support in Blend. In my next post we’ll continue on improving the YouCard application making it more testable by introducing dependency injection.

youcardinblend

In my previous post I talked about Silverlight 2 unit testing, and I decided the next natural step was to figure out how to integrate Silverlight testing in a continuous integration process. Personally I’m a big fan of this development practice, and have practiced it with great success on several projects. One of the challenges of integrating Silverlight tests into a CI process is the fact that the Silverlight test framework runs inside the browser and you cannot write Silverlight tests using your favorite test framework like NUnit or MSTEST. The power of CI is to build your software as new code is added to the source control, run automated tests, package the software and deploy it to a testing environment. If the tests fail you stop the deployment and alert the development team.

There are several tools you can use to set up a CI server. Personally I use CruiseControl.NET, but CI is more about a practice than a specific tool or technology. CruiceControl.NET supports several testing frameworks. For this example I’m going to use NUnit. When including Silverlight tests into your build process you need a way to fail the build if one of the Silverlight tests fails. To do that I’m going to launch the Silverlight tests from NUnit, and use WatiN to have NUnit “look inside” the browser to see if the Silverlight tests succeeded or failed.

WatiN (Web Application Testing in .NET) is a framework inspired by WatiR (… in Ruby), and is basically a way of automating Internet Explorer or Firefox. WatiN gives you a simple API to control IE at run time. You can point it at an URL, navigate the HTML DOM, enter text into text boxes and click buttons. As you automate real usage of your web application you can do assertions to verify that your web application behaves like you expect. I’ve previously used WatiR for doing "smoke tests" of an application, but this is my first experience with WatiN and I’m pretty happy with the framework so far. To give you a quick feel for the framework and what you can do I’ve included a really simple test for searching for my name at Live.com.

Search-for-me
As you can see the WatiN API is straight forward, you can grab hold of form elements and interact with them. Since the Silverlight unit tests are executed inside the browser we can use the same technique to navigate to the web page containing the Silverlight tests and inspect the browser to determine of the test was a success or not.

Basic-Silverlight-test
In this example test we’re not checking each individual Silverlight test; we’re simply failing the NUnit test if any of the Silverlight tests fails. This is good enough in most cases, but it would be nice to get some additional information about what went wrong when executing the tests from NUnit (or inside a build server). The Silverlight testing frameworks currently doesn’t provide any hooks to extract this information, but using WatiN we can reach into the HTML doom and pick out the pieces of information we’re interested in.

Full-Silverlight-Test-Thumb


When running the tests from the NUnit test runner we can now look in the Console.Error section to view additional information about failing Silverlight tests.

Silverlight-in-NUnit

Now that I have Silverlight tests failing NUnit it’s straight forward to include the NUnit tests in my CruiseControl.NET project configuration. When a Silverlight test fails, the entire build fails and the developers will get notified. If the Silverlight app is part of a larger web application you can use WatiN to do functional testing of other aspects of your web application as well, to give you another layer of testing in addition to "traditional" unit tests.

As Silverlight 2 Beta 2 finally shipped this weekend I’ve upgraded my YouCard demo to Beta 2. You can also execute the unit tests your self if you want.

Jeff Wilcox, who worked on the Silverlight testing framework, wrote a post about unit testing in Silverlight 2 Beta 2. In essence you can continue to use the testing framework that shipped with the Silverlight 2 Beta 1 controls, but you need new project templates (if you don’t want to set up testing by hand). He also mentions that there will be an update to the testing framework. Jeff also hints that there will be support for CI in Team Foundation Build and CruiseControl.NET. I did some Facebook messaging with Jeff about this, and I think his approach is going to be quite different to mine, so it will be interesting to see his take on CI.

Testability is becoming a common design goal. Patterns like dependency injection help us build code that is easier to test, and design for testability is something Microsoft is embracing in ASP.NET MVC framework. I was pleasant surprised to discover some of the testing capabilities in Silverlight 2 Beta 1. It’s not as baked into the product as with ASP.NET MVC, but as part of the Silverlight 2 controls download you get a full Silverlight unit testing framework you can start using today. It’s the same framework Microsoft uses to test their Silverlight controls, and the source download of the Silverlight Controls include the entire test suite.

YouCardUnitTestRun

Jeff Wilcox works on the Silverlight Controls, and has written an excellent tutorial on unit testing with Silverlight 2. It covers the basics of setting up the test framework, as well as how to write API and UI tests for Silverlight. If you want to read up on the basics I strongly recommend his blog post. If you want to print the tutorial Jeff also made the tutorial available as a downloadable PDF.

Jeff does not go into some of the more "advanced" testing scenarios, like how to test asynchronous code, so this post picks up where he left. Most unit testing frameworks makes you write your test methods as public parameter less methods that return nothing. You tag your method with some kind of testing attribute to tell the test runner that this method is a test. When your test method returns the test framework moves on to next test and execute it. This behavior is causing some challenges when writing tests for asynchronous code.

Back in September 2007 I wrote a post on how to unit test event-based asynchronous code using the ManualResetEvent object for synchronization. The even-based asynchronous pattern was introduced in .NET 2.0 and makes it easier to do common asynchronous tasks like calling web services or downloading content from the web. If you add a reference to a web service that has a "GetOrders" method, you will an additional "GetOrdersAsync" method on our proxy class, as well as a "GetOrdersCompleted" event which is the callback event.

Silverlight 2 uses the same model, but takes it one step further as you now only get asynchronous versions of the methods on your web service proxies. The same is true for the WebClient class, or the HttpWebRequest class you might use to talk to REST services. The reason for this behavior is that the Silverlight 2 network stack is built on top of the browser networking stack, and behaves the same way you’re used to from writing AJAX pages (after all ,the A in AJAX stands for asynchronous). The reason to do asynchronous network calls is to not block the UI thread, and give the user a better experience.

Over the last couple of months I’ve been doing Silverlight 2 development fulltime, and so far the focus has been on building "working prototypes" and exploring UI ideas rather than building production reading code. Now with Beta 2 just days away we’re ready to take the project into the next face, and need to make sure we do proper testing. This week I’ve been playing with the Silverlight 2 testing framework, and I figured I could share some of the experiences around writing asynchronous tests.

The application I’m going to use for my examples is the YouCard demo from REMIX. It was written without testing in mind, so I figured it would be an interesting exercise to go back and try to test the code. The main class in the YouCard application is the YouCardData class. By using data binding I got some separation concern from the start, and the responsibility of the YouCardData class is to talk to Twitter and Flickr and download information about a specific user. Whenever the data changes the YouCardData object will notify the UI through the INotifyPropertyChanged interface as well as updating ObservableCollection<T> collections.

YouCardScreenshot

The first test I want to use as an example is a test to verify that changing the Twitter username on the YouCardData object is going to download the Twitter feed and update the user information. The web request to get the Twitter feed is asynchronous, and therefore we need a way to "hold" the test until we’re ready to do assertions on the data we got back. To write an asynchronous test you need to derive from this SilverlightTest class, as well as mark your method with an Asynchronous attribute. By deriving from the SilverlightTest class you get access to several "EnqueueXXX" methods. These methods let you "queue" up code blocks (delegates) with the code you want to execute asynchronous. In the example below we queue one method to change the twitter username, then we use the "EnqueueConditional" which will wait for a condition to be true before executing the next block in the queue. In this case we’re using a flag to tell if the data is returned from the server. If so we execute two code blocks containing our assertions, before calling EnqueueTestComplete to let the test framework know our test is complete.

TwitterDataTest-Code-Sample

The second test I want to show is a UI test simulating a user entering two Twitter users, clicking the add button, and then clicking the close button on the YouCard control to remove the user. To do this I had to change the protection level for my click handler from private to internal, and add the InternalsVisibleTo attribute to the application. Jeff has the details covered in his introduction tutorial. The reason this test is asynchronous is that we run a "shrink" animation before actually closing the card. So we have to wait for the animation to complete before we can do assertions on the numbers of cards on the page.

YouCard-UI-Test-Code-Sample

Another thing worth mentioning when doing UI testing (Jeff also covered this in his tutorial) is that all application specific resources (such as styles and templates) needs to be either copied over to the Test application project, or made local to the user control using the resource. So if you’re getting resource not found exceptions check what you got in your App.xaml in the application you’re testing, and make sure you got the same stuff in the App.xaml of your test project.

I’ve uploaded a new version of my YouCard sample application, including the test libraries (so you don’t have to download the Silverlight 2 Control Source to test the app), as well as the test project containing 9 tests. The tests include both API tests for Flickr and Twitter as well as UI tests for adding/removing cards and accessing local storage.

One of the cool things about the Silverlight test framework is that the test runner is actually the browser and Silverlight itself. I actually deployed the tests to my server so you can see what the test framework looks like when executing the tests.

I've previously blogged about mine and Jose's presentation at REMIX 08 Australia. Jose did an awesome 15 minute DeepZoom demo. If you missed it, or want to see it again, Michael Kordahi from Microsoft Australia have done a DG.TV episode with Jose. Personally I love the co-viewing demo, using Silverlight 2 sockets support.

One of the things Jose talked about is Deep Zoom-enable any image on a web site, and how that is possible to implement today using a API. Since he only had 15 minutes he didn't have time to go into the technical details around this. A question from @andythompy came up on the Silverlight forums about weather or not there actually is a Deep Zoom API, as he couldn't find any information about this online… I figured I'd write this post to clarify and provide some resources to developers who are eager to start building dynamic, automated DeepZoom applications today.

First to clarify, there is currently no Deep Zoom API or SDK - but we do got the second best thing; a command line tool called "SparseImageTool.exe". This is the "nuts-and-bolts" behind the Deep Zoom Composer and does the actual work of taking the images and compositions you specify in the designer and turning them into Deep Zoom collections. The "SparseImageTool.exe" takes a bunch of parameters, including an XML file containing the list of images to include in the composition. I'm not going into details on how to automate this tool, but my friend Giorgio Sardo from Imagine Cup 2006, currently working for Microsoft UK, have written a C# proof-of-concept application taking a folder as input parameter and outputting a Deep Zoom collections of all images in the folder. The source, as well as details about the SparseImageTool.exe can be found in his blog post titled "Deep Zoom Batch Export (Programmaticly using C#)".

So what about future versions - will there be a Deep Zoom SDK? I haven't found any official announcements from Microsoft, but when asked this question on the Expression blog Kirupa Chinnathambi (developer on the Expression team) wrote this:

deef - we are working on that [DeepZoom API], and you can do that already with a lot of trickery using the SparseImageTool.exe found in the Deep Zoom Composer's Program Files folder.

An example of what you suggest can be seen on a public preview site called PhotoZoom: http://photozoom.mslivelabs.com/"

The description on the PhotoZoom site is as following:

PhotoZoom is an experimental site developed at Microsoft, running on the Microsoft Live Labs Incubation Platform. It uses the Deep Zoom technology in Silverlight 2 Beta 1 to create photo albums with user uploaded photographs.

One of the nice features of Photo Zoom is the RSS/ATOM import. I gave it a try by pointing it to my Flickr RSS feed. After less then a minute waiting I had a Deep Zoomable Flickr Set.

PhotoZoom

This is a cool example of what is possible today using the SparseImageTool.exe  and gives you some idea  of what's possible in the future. Hopefully this posts clarifies the current state of automatic Deep Zoom and points you in the right direction if you're planning on building your own application.

Update: At yesterdays TechED US keynote Microsoft announced that Silverlight 2 Beta 2 will be available this week. Laurence Moroney blogged about this, and included some interesting Deep Zoom hints:

Deep Zoom -- this has been hugely updated. The file format is now XML instead of a binary format, so the ability to generate your own Deep Zoom images and collections server side will become easier. There's also some nice new event models around zoom/pan state.

This is a post I've been looking forward to write for quite some time, but I've just been to busy with work, CodeCampOz and REMIX to get around to do it… At the MVP Summit in Seattle some weeks back I had dinner with a group of friends, including fellow RD and co-worker Sondre Bjellås, and long time IRC-friend Wilco Bauwer (now working at Microsoft). Like when ever a group of programmers get together the talk soon was about Silverlight, C# and programming an general. We started discussing Silverlight and what features we would love to se in future versions. One of the things Sondre felt was missing is support for microphone and webcam. I don't know why Sondre think this is a big deal (but he DO read Love and Sex with robots… btw, Sondre, you should write a book review!). Wilco have worked on the HTML-bridge in Silverlight, so we started talking if it might be possible to "cheat" basic webcam support by bridging Silverlight and Flash. Without knowing the details we all agreed that it was probably possible to do.

When I got back from Seattle I started doing some initial research, like learning how to program against the webcam in Flash, what kind of HTML-bridging  capabilities you got and so on. A video tutorial titled "Webcams, PNG and AIR", combined with a blog post titled "Use JavaScript to Take a Screenshot of a Flash movie", gave me all the pieces to build webcam support for Silverlight (using Flash). So I asked my self: "What would MacGyver do", and decided to glue everything together into a proof-of-concept of webcam support in Silverlight 2.

The video tutorial covers the basics of how to create a camera object, attach it to a video and grab a video frame as a BitmapData object. It also covers how to use the as3core library, a set of open source extensions to ActionScript3, which includes a PNG-encoder class. The PNGEncoder encodes a BitmapData object into a ByteArray. Once I had the ByteArray I needed a way to pass it back to the browser. Since the set of types you can marshal between ActionScript and the browser (at least to my knowledge) is limited, I figured a Base64 encoded string would be the way to go. The blog post about taking screenshots used this technique to pass an image from Flash to JavaScript. It also covered how to expose ActionScript functions to JavaScript using the ExternalInterface APIs.

Once I had the Base64 encoded PNG image in JavaScript I could simply return it back to Silverlight, which then would use the Convert.FromBase64String method to create a byte array. With the image stored in a byte array I could simply load it into a MemoryStream, and then set the MemoryStream as the source of a BitmapImage object.  I'll let MacGyver show you how it all comes together:

MacGyverUML

It literally didn't take more than 20 lines of ActionScript, 5 lines of JavaScript and 5 lines of C# to get a single frame from my webcam onto a Silverlight image control.  This first piece of code is the ActionScript needed to start the webcam, capture a frame, set the mode and expose two functions to the browser:

WebcamActionscript

The next part is the JavaScript needed to grab the object/elem tag containing the Flash player, and calling the ActionScript functions to grab a snapshot from the webcam. The Base64 string is just returned from the function, as this function is being called from C#:

WebcamJavascript

The final part is the C# code using the HTML bridge to invoke the JavaScript function, grab the Base64 string, decode it, and then load the PNG image:

WebcamCSharp

Using the basic webcam integration I created two sample applications. The first one is a "performance test" to see how many frames per second I'm able to transmit to Silverlight. Since I'm not able to pas the raw stream from the camera, and have to PNG encode each frame, it's all CPU bound. The application uses a timer, which will grab a frame and measure the time it takes. Once it got the frame it will adjust the interval of the timer to the amount of time spent on the previous frame + 50 milliseconds (to give the UI thread some room to handle input events etc). I was able to get roughly 12fps 180x140, but on higher resolutions it starts to get sluggish. Also note that when using all the CPU power to capture frames you don't have CPU left to do Silverlight animations etc, so doing "live" video is really something you don't want to do. Click the image to check out the sample:

WebcamLiveVideo

The second sample is a Silverlight "Photo Booth" application, with out any of the cool features of the real Apple Photo Booth app. The interesting part about this sample is how I overlay the Flash container on top of Silverlight. This way my Silverlight application don't need to use CPU power to pre-view the video, and I only grab photos when the user clicks the button. Each image is also added to the thumbnail control, which I re-used from my YouCard demo. Click the image to check out the sample:

WebcamPhotobooth

I've made the code available for everyone to play with, including the Flash webcam wrapper. In order to build the Flash app you need Adobe Flash CS3. If you don't have Adobe Flash CS3 you can still build the app in Visual Studio and use the prebuilt WebcamWrapper.swf file. The code is not optimized in any way, and probably contains some bugs. But, this initial post is meant as a proof-of-concept, and I'll probably revisit this topic later.

And to summarize: THIS is how MacGyver would have built webcam support for Silverlight 2!

The Sydney REMIX08 Keynote is just about to start, and in about an hour I'll be presenting "What's new in Silverlight 2" together with Jose Fajardo. The main demo of my part of the talk is YouCard, a Silverlight 2 application aggregating content about your friends from Twitter and Flickr. The idea is basically to create something similar to Xbox 360 Gamer Cards to give you a quick summary of your friends latest tweet and pictures.

The application touches on many of the concepts of Silverlight 2, such as:

  • Layout controls
  • User controls
  • Styling and skinning
  • Local storage
  • Network access
  • Data binding
  • Animations and 2D graphics

youcardscreenshot

You can try the application at http://follesoe.no/silverlight/youcard (or click the picture). Enter your friends Twitter name and click add. Flip the card to enter their Flickr feed URL. If you like it, check out the source code as well.

If you have any questions or comments about the session or code just drop me a comment.

See you at REMIX08!

One of the cool features of Silverlight 2 is the support for cross-domain web requests. This enables you to call web APIs directly from your Silverlight client without proxying the request through your own server. The service you’re calling must provide a policy file permitting cross-domain callers. This is the same security mechanism used by Flash to make cross-domain calls, and in fact Silverlight 2 respects the same crossdomain.xml format as Flash. Any service callable by Flash is now callable by Silverlight 2. If you want to learn more about Silverlight networking and cross-domain calls check out Karen Corby excellent three part series on the Silverlight HTTP Network stack.

Several popular Web 2.0 services, like Flickr, have a crossdomain.xml file that allows for cross-domain Silverlight clients. Others, like Twitter, have a more restricted crossdomain.xml file that only allows callers from certain domains. Most sites however don’t provide a crossdomain.xml, so for instance if you want to consume their RSS feed you need to proxy the request through your server. 

Today I started on a new Silverligh project where we want to consume RSS feed, and I was just about to add my “standard” WCF proxy to the project when my old friend Yahoo Pipes came to mind. I’ve previously blogged about how I use Yahoo Pipes to merge my blog posts with my mobile photos on Flickr and then import it to Facebook. Yahoo Pipes is a really cool service that let’s you define fairly complex web integrations using drag-and-drop. You drag different sources, filters and operations on a design service and “connect” the pipes together to pipe and transform the data. When I checked http://pipes.yahoo.com/crossdomain.xml I was a little disappointed to get a 404, but after digging around a little it turns out Yahoo host their APIs on a different URL: http://pipes.yahooapis.com/crossdomain.xml. Yahoo Pipes supports cross-domain callers!

 yahoopipefeedproxy

I quickly created a really simple pipe. It uses the URL input module to retrieve the URL of the feed, the Feed-Fetch module to read the feed and then output it. Click for an example of my feed proxyed through Yahoo Pipes. The following code shows how to consume the feed in Silverlight 2:

private void DownloadFeed()
{
    string pipeUrl = "http://pipes.yahooapis.com/pipes/pipe.run?_id=4rBri9Ef3RG8CEGLLe2fWQ&_render=rss&feedUrl=";
    string feedUrl = "http://feeds.feedburner.com/follesoe";
    string url = string.Concat(pipeUrl, HttpUtility.UrlEncode(feedUrl));

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.BeginGetResponse(new AsyncCallback(ResponseHandler), request);
}

private void ResponseHandler(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

    if (response.StatusCode == HttpStatusCode.OK)
    {
        XmlReader reader = XmlReader.Create(response.GetResponseStream());
        SyndicationFeed newFeed = SyndicationFeed.Load(reader);
    }
}

I tried to make a more general purpose proxy-pipe using the “fetch data” module which can fetch XML, RSS, KML and iCal data. Unfortunately Yahoo Pipes can only output RSS, JSON or serialized PHP, but not plain XML. I tried piping my public Twitter feed (XML) through it, and it works fine. The only problem is that it makes some changes to the output, like adding the name of the pipe, the number of elements etc. So it’s not a “raw” data proxy, something you have to take in account when consuming the output of the pipe. Click for my Twitter feed outputted as a JSON array of tweets.

Below is a simple RSS reader (hosted on Silverlight streaming) I wiped up in 45 minutes that consumes any RSS feed through Yahoo Pipes! The code is off course available for download. For more Silverlight godness - come to REMIX!

Microsoft Expression Studio One year after the initial release of Expression Studio second version is now ready. That’s right, new versions of all products in the entire suite, including Blend, Web, Media, Encoder and Design. I’m not going to list all the new features, but rather highlight some of the features I find more interesting.

The two biggies in Blend 2 is support for .NET 3.5, Visual Studio 2008 projects and Silverlight 1.0. In terms of Silverlight features you now got full design time support for layout out your application, creating animations and editing the JavaScript code. That’s right, Blend now have a JavaScript editor built in.

Another Expression tool I’ve played around with a little bit is Expression Web. Before 2008 I used Expression Web for all my CSS editing, but after the features got included in VS2008 I haven’t used it that much. The big news in Expression Web 2 is support for PHP. Yep, Microsoft now has a supported PHP editing tool! The cool thing about the PHP support is that you get to preview your site with out having to run IIS or Apache. This is big news for the PHP guys! Another important feature is offcourse support for including Silverlight in your web application. A subtle is the new black theme which aligns Expression Web UI more with the rest of the suite.

I haven’t played that much with the other tools in the Expression Suite, but I really want to pick up drawing again and learn how to do 2D vector graphics in Design.

As for availability and pricing you can pick up Expression Suite for $699 from retailers such as Amazon and Best Buy beginning mid may. If you’re based in Australia another good idea is to attend REMIX in Sydney or Melbourne ($199) and receive a free copy of Expression Studio 2.

Now to the tricky part… The big thing that’s missing from Blend 2 is Silverlight 2 support, which is pretty obvious since Silverlight 2 is currently in Beta 1. So personally I’ve already moved to Blend 2.5 March CTP where I do all my app design. Microsoft hasn’t made any announcement on what the upgrade path will be for Expression Studio 2 customers. One possible approach could be to release Silverlight 2 support as a service pack to Blend 2, or perhaps offer a cheap/easy upgrade path from Blend 2 to 2.5. Hopefully this is something Microsoft will clarify.

There is also a new Expression site up which has all the details about the new release, what’s new in each product as well as links to downloads.

For all the details about this release, check out the official announcement.

Dinner with Andrew, Jon, Tom and Ian This week I attended CodeCampOz in Wagga Wagga, a five hour drive from Melbourne and Sydney. Code camp is a free to attend, community driven developer conference. I had an fantastic time in Wagga, made some new friends, learned a few things and had a blast. The content was really top notch, with 17 sessions (including pre-conf) spanning a wide variety of topics such as SQL Server 2008, Silverlight, WPF, UX, Facebook, Visual Studio, SyncLinq and more, presented by some of Australia's most talented developers and speakers.

I had the pleasure of kicking off the conference with the first session on how to build interactive video applications using Silverlight. The session was about how you can encode script commands into a video file using Expression Media Encoder and program against the markers. The session was one large demo building up the video player using Expression Blend 2.5. The video I used is a dive video from our holiday in Egypt back in 2007. When ever there is a fish on the screen an event occur, and the app call out to Wikipedia to get facts about the fish. To retrieve the data from Wikipedia I use an open API from Futef. I've embedded the final video player in this post, as well as a link to the source code if you want to play with it your self. The play/pause/forward/backward buttons are taken from Jose Fajardo's amazing blog where he re-does many of the popular UI's like iTunes, Media Player and MSN Messenger in Silverlight.

encoderscreenshot 

A big thanks to Andrew Browne and Ian Thomas for the drive to Wagga, Greg Low and Mitch Denny for organizing an amazing event, and to everyone for all the good conversations. For a full recap of what went down in Wagga check out the Twitter hash-tag, and the Flickr tag for pictures.

Because of cross-domain scripting limitations the embedded player does not include map integration. Check out these two links for alternative versions:

download Download Interactive dive video in Silverlight

This weekend I've finally got a chance to sit down and play with Siverlight (formerly known as WPF/E). Friday night me and Gøran, my partner in crime and code over so many years, sat down with lots of coke and snacks and played with the beta. We're helping out Rune Grothaug, a good friend of mine working for Microsoft Norway on their MSDN team, building a simple Silverlight video player to use on the Norwegian MSDN site.

We decided to use one of the samples from the SDK as a starting point for the player. The SDK includes a bunch of samples, where one of them is a nice video player. After playing with the sample for some time I was a bit disappointed. It looks like the sample is designed partly in Blend 1 and Expression Design, and then glued together by hand in an XML editor. I downloaded the Blend 2 CTP and tried to open up the sample, but it was quite messed up…

So we ended up hand-coding the player, and messing with different XAML elements to get the look and feel we wanted. The second non-pleasant experience was the JavaScript editing. In the 1.0 release of Silverlight you don't have the cross platform CLR, so all your interaction logic has to be written in JavaScript. The 1.1 alpha supports .NET languages, but doesn't have a go-live license, so we decided to stick with 1.0. With out intellisense it's quite hard to learn a new programming model. This is something that's greatly improved in the "Orcas" version of Visual Studio.

Even tough the Silverlight developer experience can be a little harsh at first I still have great belief in the platform. I also think that if you have a solid WPF understanding, and some experience using Blend, you'll do fine. Another tip is to download "Orcas" and use that for JavaScript editing (I'll post more on that later).

I've uploaded an early version if the player if you want to give it a go. For a nice summary list of Silverlight resources, check out Robert Burke's or Scott Guthrie's blogs.

NDC2010 - Patterns and techniques for building Windows Phone 7 applications
Simulating multitouch on the Windows Phone 7 Emulator
MVVM presentation from NDC2009 on Vimeo
Automatic INPC using dynamic proxy and Ninject
Automatic change notification for dependent properties
Automatic INotifyPropertyChanged using Dynamic Proxy
Agile UX development using low-fidelity prototypes
Recording of my MVVM talk at NDC2009 is now online
NDC 2009 is history – What a blast!
MSDN Live Winter 2009 is now history!
Speaking at MSDN Live next month
Mesh-enabling the Dive Log Silverlight Application
Last User Group Presentation in Australia
Silverlight Designer and Developer Network Presentation
Is Silverlight 2 Ready for Business Applications?
Combining different Separated Presentation Patterns
Improve your user experience using the AutoCompleteBox
New layout controls in the Silverlight Toolkit
Change the look of your Silverlight application using Themes
Speaking at Silverlight Designer and Developer Network and attending PDC 2008
Updated samples and some nuggets from the archive
Printing in Silverlight 2 using CSS and ASP.NET AJAX 4
Efficient testing in Silverlight 2 using tags
YouCard, DiveLog and WebcamPOC updated for Silverlight 2 RC0
Announcing Colorful Expression Studio Add-In
Developer Build of Chrome (1251) fixes Silverlight 2 bugs
Porting the Silverlight Dive Log application to WPF
WCF Authentication Services, Silverlight and smelly cookies
Back and forward navigation in Silverlight 2 using ASP.NET AJAX
Tech Ed ANZ is over and I got quoted on ZDNet
TechEd 2008 – Silverlight 2 for Developers
Unit Testing, Presentation Model and the HTML Bridge at CodeCamp NZ
Configuring Silverlight 2 applications using the WCF configuration file
Webcam in Silverlight 2 – Sliding Puzzle Game
Skyfire: the PC web on a phone, including Silverlight 2
Speaking at Tech Ed ANZ and CodeCamp NZ
Sharing logic between server and client
YouCard Re-visited: Implementing Dependency Injection in Silverlight
YouCard Re-visited: Implementing the ViewModel pattern
Silverlight 2 Continuous Integration Testing using WatiN
Unit testing asynchronous Silverlight code
Generating DeepZoom images programmatically
Webcam in Silverlight 2 - MacGyver style!
REMIX08 YouCard Demo
Using Yahoo Pipes as a Silverlight Cross Domain Proxy
Microsoft Expression Studio 2 Ships
Interactive video using Silverlight @ CodeCampOz
My first Silverlight developer experience
<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789