RIA, Silverlight, .NET »

[14 Apr 2011 | 0 Comments]

At MIX11 today, Silverlight 5 beta was released.  It includes a whole load of new features (most of which were already known by people who watched the Firestarter event last December), you can find the full list at Tim Heuers’ blog.


One of the small, yet pretty interesting additions in my opinion are Markup Extensions.  Tim quickly mentions it, but there’s no example to be found on Silverlight.NET, so I figured: why not try it out myself? :-)


With custom markup extensions, you can in essence execute your own code instead of the default Binding markup extension, which will provide the correct desired value for the property you’re using the markup exension for.  One of the typical uses for this could be for multi-language apps: getting the correct text in the correct language from your resource dictionaries. 


Up until now, I had to provide quite a bit of code to enable my app to handle multiple languages: I would typically create some kind of resource wrapper, make that available through App.XAML or a resource dictionary, reference the resource on all my Views and bind to the resource wrapper + resourceKey property of that wrapper.


With markup extensions, this becomes a lot easier.  Start out by creating a new SL project, and add 2 resx-files: one default, one with the .nl extension for Dutch translations.  Then, add a new  class to your project, and make it implement the IMarkupExtension<T> interface, where T is the type of object you want to get back from the code.  In that class, you can add a bunch of properties, methods, … to your liking.  In this case, all I need is a string property, ResourceKey.  The ProvideValue method is what gets executed to get the desired value, which, in this case, comes down to getting the translation with key ResourceKey from the resx file.  That’s no more than a few lines of code:


public class TranslationExtension : IMarkupExtension<string>
    public string ResourceKey { get; set; }

    public string ProvideValue(IServiceProvider serviceProvider)
        // get the ResourceKey value from translations
        return SL5MarkupExtensions.TranslationResources


Next, we need to use this in XAML.  Import the correct namespace, and call the Markup Extension from XAML, passing in the ResourceKey parameter:


<TextBlock Text="{me:TranslationExtension ResourceKey=DemoResourceKey}"/>


And… that’s it.  Really.  Instead of having to create all I described in the beginning, all I need are these few lines of code.  To check if it still works when changing the language, I added a button which will set the culture to “nl”, and navigate to another View, containing a TextBlock using the markup extension with the same ResourceKey.


This is one really short example to show you how easy it is to use markup extensions, but I ‘m pretty sure you can already see how it can prove useful.  For example, you might use it to get the correct ViewModel for your View, if you’re using MVVM.


By the way, in case you’re wondering why I’m navigating to another View: I want to make sure the markup extension code gets executed again.  If you want true on-the-fly language changing in your app, you’ll have to provide a way to notify your app it should re-execute the extension.  This goes beyond the point of this blog post, but there already are quite a few implementations for this available for WPF, like this one, which should be easy to port if you really need it.


That’s it!  You can download the source code here.  Happy coding! :-)

.NET, Featured, General, RIA, Silverlight »

[12 Apr 2011 | 1 Comments]

I've just seen the MIX11 keynote, and followed my first session at MIX (HTML5 for Silverlight Devs :-)). Everyone who's here or who's following online will already have noticed there's a heavy focus on HTML5 this year - you can feel it in the Day 1 keynote (in tomorrow’s keynote, we’ll get some Silverlight 5 / Windows Phone 7 stuff), you can grasp it from the amount of sessions about HTML5. We're getting demo's showing off some CSS features, graphic features, video features, animations, …


Hold on. Let me rephrase that: we're getting demo's of how these features work great in IE9 & IE10 (get the preview now), and don't run all that great in, say, Chrome.


The problem? I build business apps, and for these apps, I'm not buying it. It's too early. It's immature. There's not enough browser support.


Interestingly enough, Dean started his keynote by stating that what people want are native apps on their devices. I tend to agree with him on this one - but that means that, for your mobile devices, you will want to write a native app in whatever tech it is that's supported on that device - you'll have to write iPhone apps, WP7 apps, Android apps , … in their native development languages. I agree, but that makes me wonder: why all that talk about "write your app in HTML (5) so it works on each device," when in essence it will offer you a sub-par experience, a fallback experience really?


If you want to offer the best experience to your consumers, you will have to write a native app for each device. But this post isn't about that - I'll write another one with my thoughts on building apps for multiple devices & multiple form factors in the near future.


I've seen some pretty cool stuff today. Jumplists from Facebook (needs IE9 & Windows 7). A FourSquare playground built in HTML5 (needs IE9 & Windows 7). CSS gradients. Auto resizing grids (runs great in… IE10). Are you catching my drift here?


We've got Canvas. We've got SVG. We've got native sound. We've got the video tag. But it won't work across browsers. It won't work in older browsers. It won't work natively at all for most of the people & devices out there.


As said, I've seen pretty cool stuff, but I've mainly seen UI features – UI features that are already available in plugin-based technologies.  What's more: I've seen that native cross-browser support for these features is nothing more but a distant dream; and even if the features are supported, they seem to run fast in a certain browser, but run like crap in any other one.


Do you really want this for your apps?


Now, of course you can write your sites to gradually decrease as far as UI capabilities are concerned, or you can use something like Modernizr to "fake" HTML5 features using JavaScript / ECMA Script 5 (input elements are a nice example of why you’d want to use this), or at least to check if a certain feature is supported by the users’ browser.


But again, I'm not building sites, I'm building business apps.


So let's step away from the great, pretty, flashy, gradient-y HTML5 features. The real power of HTML5 are, in my opinion, its state/dev-related features; and these are either available or not: you can't use something like Modernizr to magically enable them on older browsers. 'm talking Local Storage, Session Storage, File API, WebSQL API, WebSockets, Offline Apps, … the stuff we've got in plugin-based approaches but are missing from HTML. This is the stuff that makes HTML5 great.


Problem is: I can't use these features. Not all of them are implemented at the moment, not even in the latest preview builds of most browsers. There's not enough browser support for this, my users probably won't have the correct version of the correct browsers, and there's no way to gradually adapt my app for older browsers when using these features: they either fully support them natively, or they don't.


So what are we left with, from a business app point of view? Flashy semi-supported, semi-fast or slow (depending on your browser) features, poor cross-browser support & not enough market penetration to start using the interesting features. And I'm not even talking about tooling support for these features. I need support for these features across browsers, and I need a substantial amount of users having a modern browser which supports them.


Are you really going to build a business application today, using HTML5?  I won't.


Don't get me wrong: I like where the new HTML spec is going. You'll probably see me blogging about the latest cool HTML5-based business application we're building at my job… in about three years or so. But not now.


So, what should you use to build your business apps today? In my opinion: use a plugin-based approach (Silverlight, for example) if you need it to run on the web (or on the desktop, cross-platform even).


What if that’s not an option?  Use ASP .NET MVC + jQuery if you need your app to be HTML-based, pairing it with something like Modernizr to enable you to use some of the UI-related HTML5 features.


Need it to run on mobile devices or devices with another form factor?  Build them natively in the technology the device supports (but as said, more on that in another post).


But don't get caught up in the HTML5 hype. There’s cool stuff underway.  It will get there, but it's not there yet. Not now. Not today. Not in the near future.

.NET, General, Presentations and sessions »

[1 Apr 2011 | 0 Comments]

clip_image001I’m happy to announce I’m going to do a session at the Norwegian Developer Conference in Oslo, June 8 – 10.  The session will be an in-depth session on architecting Silverlight solutions with WCF RIA Services and MVVM, and I’m quite excited about it; sessions like this are much more fun to prepare & deliver than high-level sessions, in my opinion..  If you’ve got things you absolutely want to know about these techs/frameworks, don’t hesitate to drop me a line – I’ll try to fit them into the session :)


In case you don’t know NDC, here’s some info straight from their site:


NDC 2010 was an unqualified success, with more than 1,300 participants and a range of Partners from leading IT companies. We are now about to repeat the success by organising NDC2011



Leaders in the field

Again in 2011, participants will be able to learn from the leaders in the field.

The conference promoters are ProgramUtvikling AS. Their vision is to provide developers with the very latest in practical expertise in technology and project performance. Norwegian developers are already well–respected for their abilities, and the aim of the conference is to stimulate the environment in Norway even further, so that Norwegian developers can maintain and enhance their sound position. The way this is being done is by establishing an international conferencing environment in Oslo and focusing on seminars of the highest quality.



Norway’s largest agile program development conference

NDC is Norway’s largest conference dedicated to .NET and Agile development. Along with ProgramUtvikling, Microsoft Norge AS is also supporting the conference and doing its bit to make the event a real boost for developers in the industry.



Access to new technology

Over many years, Microsoft has been focused on giving developers access to the latest technology – as demonstrated at NDC 2008, 2009 and 2010. For 2011, it has been decided that, as before, the conference should feature seven different specialist tracks, each including a series of relevant talks.


Hope to see you there?

Featured, Silverlight, Headline, WCF RIA Services »

[17 Mar 2011 | 0 Comments]

A lot of business applications that are being developed in Silverlight today are built with the help of WCF RIA Services. This should come as no surprise, as it’s a really powerful, extensible framework which provides us with a lot of features out of the box (validation, authentication, authorization, …) that otherwise would require quite a lot of custom code, workarounds & plumbing. In WCF RIA Services, you’re going to be working with a client-side Domain Context instance.


When you’re going to be working with this, there are several approaches you can take: you can work with one shared Domain Context instance, you can work with one instance per ViewModel, you can combine both, …


All strategies come with certain (dis)advantages, so if you’re architecting a new Silverlight solution, it’s important to know what these are (and how you can handle them).


For Silverlight Show, I wrote a two-part article series on this.  The first part has just been published, so if you’re interested in this, go check it out! :-)


Update: as of Saturday 19/03, the second part has been published as well.


Happy coding!

.NET, Silverlight »

[24 Feb 2011 | 0 Comments]

One of the projects I’ve worked on, 360 review, is a Silverlight application consisting of an intranet & extranet part, design to automate 360 review of employees, creating questionnaires, generating reports, …  in a Software as a Service model.


Silverlight Show, one of the leading Silverlight sites, asked me to write a white paper on this, as it might be of interest to various project teams around the world who are thinking about creating large line of business Silverlight applications.


The white paper tackles questions like why we made certain technology choices, what a project team for a Silverlight application should look like, problems we’ve encountered during development, etc.  To read about this, and more, head over to Silverlight Show!

.NET, Featured, Silverlight, Headline, WCF »

[18 Feb 2011 | 0 Comments]

cow_clipartAfter my previous post on how to use a Channel Factory in Silverlight, I received quite a few questions through Twitter, the main one being: “how do you pass in parameters to an operation?”  Next to that, someone also suggested to use a custom binding with binary encoding instead of the default basicHttpBinding.  So I decided to write a post explaining how to achieve those two things – welcome to part 2: binary cows & new-born calves! :)


First up: passing in parameters to the operation.  To keep in theme with the last solution, we’re going to allow the user to create a new-born calve on the client, and send that to the server.  For the sake of the demo, the only thing we’ll do on the server is fill out the correct ImageUri, and we’ll send the resulting Cow object back to the client. 


public Domain.Cow AddCow(Domain.Cow newBorn)
    newBorn.ImageUri = new Uri(http://localhost:5873/calve_clipart.png, 
    return newBorn;


The part that confused some people was how to write the correct async signature to match the regular operation contract.  It’s actually quite simple: in the Begin method, you should add the parameter(s) you want to pass in before the IAsyncResult and state parameters:


[OperationContract(AsyncPattern = true)]
IAsyncResult BeginAddCow(Cow newBorn, AsyncCallback callback, Object state);

Cow EndAddCow(IAsyncResult result);


To call this method, you should write code like this:


private void AddCowExecution()
    Cow newBorn = new Cow() { Name = "New born" };

    // call CowService WCF service
    ICowService channel = GetCowServiceFactoryChannel();

    var y = channel.BeginAddCow(newBorn,
       (asyncResult) =>
           // add Cow
           var returnVal = channel.EndAddCow(asyncResult);

           Deployment.Current.Dispatcher.BeginInvoke(() =>
               // add to collection
       ,  null);


Now, how do you make sure you use binary encoded messages through a custom binding?  Two things should be done for this: when creating the Channel Factory on the client, you should create your custom binding and pass that in.  On the server, you need an endpoint that uses the same kind of custom binding.  That means you have to change two things: first, the client-side code: we create a custom binding and add the necessary binding elements (binary encoding over http transport):


CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());

EndpointAddress endpointAddress = new EndpointAddress(CowServiceEndpointAddress);
CowServiceChannelFactory = new ChannelFactory<ICowService>
(customBinding, endpointAddress);


… and then the web.config to make sure it has a correct endpoint: define the custom binding, and add the binding & binding configuration elements to your endpoint:


        <binding name="ChannelFactoryWithCows.CustomBinaryBinding">
            <binaryMessageEncoding />
            <httpTransport />




<service name="ChannelFactoryWithCows.Web.CowService">
    <endpoint address="" binding="customBinding" 
              contract="ChannelFactoryWithCows.Contracts.ICowService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />


So there we go – we now have a cow farm, compressing the cows before travel and allowing new calves to be born :-)  You can download the source code here.

.NET, Featured, Silverlight, WCF, Headline »

[7 Feb 2011 | 0 Comments]

cow_clipartFor a lot of application scenarios, adding a service reference to easily access a service from Silverlight is the way it’s done (note: I’m not going to get into a discussion on whether this is good or evil, I’m just stating a fact ;-)) – you don’t have to worry too much about proxy creation, for example, that’s done for you.  However, in quite a few scenarios, this approach isn’t feasible: if you’re writing a framework, you typically don’t want service references in your Silverlight class libraries.  If you want to make your app pluggable or extendable – for example: through a provider pattern – you might want to create channels conforming to a contract and call the methods as such.  Or you might just not like the generated code you get when adding a service reference.


Well, you can avoid using service references by working with a Channel Factory.  Included with this post is a small application which calls a service method, using a Channel Factory, to populate a list of cows.  What?   Cows.



Disclaimer: I’m not exactly sure who’s blog it was that contained sample code with cow entities, but I kinda liked the idea (at least it’s a nice change from the typical AdventureWorks entities :)). 


By the way, did you know a cow only becomes a cow once it starts giving milk?  Which farmers make sure they do by impregnating them regularly (or, to be more precise: they let bulls take care of that part for them :))?  I actually thought that was quite cruel when I found out.  Anyway, enough of this bucolic intermezzo, on to the code ;-)


This is what the application looks like:




The service itself is pretty straightforward: a standard WCF service, using basicHttpBinding, implementing the ICowService interface, containing one operation: GetCow(), returning a Cow entity.


namespace ChannelFactoryWithCows.Contracts
    [ServiceContract(Name = "ICowService")]
    public interface ICowService
        Cow GetCow();


Now, what do we need to create a channel?  We need to know the binding – check.  We need to know the endpoint address – check.  And we need to know the contract – and this is where the fun starts.  We can’t just create a channel of type ICowService, as this is a sync contract, and as you know: service calls in Silverlight are async.  What we need to do is create a client side contract with async methods matching the GetCow() method.  The contract thus looks as follows:


namespace ChannelFactoryWithCows.Contracts
    [ServiceContract(Name = "ICowService")]
    public interface ICowService
        [OperationContract(AsyncPattern = true)]
        IAsyncResult BeginGetCow(AsyncCallback callback, Object state);

        Cow EndGetCow(IAsyncResult result);


BeginGetCow and EndGetCow are the matching async methods for GetCow(), and by providing the ServiceContract attribute with the name ICowService, we effectively match ICowServiceClient with ICowService: we can create a channel of type ICowServiceClient which matches a service implementing ICowService, and call the appropriate methods on it!


As we’re going to use a Channel Factory, there’s no automatic proxy generation, so we need to have a Cow class in the Silverlight application.  The important thing to notice about this class is that it must match the Cow class on the server side – this is necessary, as .NET doesn’t know how to cast a “MyApp.Web.Cow” object to a “MyApp.Cow” object.  There are various ways to solve this: one way would be to write code to allow implicit casting, another way would be to create the class on both client and server and have them reside in the same namespace.  In this example, I took another approach: I created a Silverlight class library containing the Cow class, which is referenced by both the Silverlight app and the Web app – this immediately shows off a SL4/.NET 4 feature: you can reference SL assemblies in projects using the full .NET framework.


What’s left is effectively creating the channel and calling the service method in an async way.  This is not different than regular async programming, as you can see below:


private ICowService GetCowServiceFactoryChannel()
    // create ChannelFactory?
    if ((CowServiceChannelFactory == null)
        || (CowServiceChannelFactory.State == CommunicationState.Faulted))
        BasicHttpBinding basicHttpBinding = new BasicHttpBinding();

        EndpointAddress endpointAddress = 
new EndpointAddress(CowServiceEndpointAddress); CowServiceChannelFactory =
new ChannelFactory<ICowService>(basicHttpBinding, endpointAddress); } // create channel? if (CowServiceFactoryChannel == null) { CowServiceFactoryChannel = CowServiceChannelFactory.CreateChannel(); } return CowServiceFactoryChannel; }
private void GetCowExecution()
    // call CowService WCF service
    ICowService channel = GetCowServiceFactoryChannel();

    var y = channel.BeginGetCow(
       (asyncResult) =>
           // get Cow
           var returnVal = channel.EndGetCow(asyncResult);

           Deployment.Current.Dispatcher.BeginInvoke(() =>
                   // add to collection
       , null);


Just one more thing: as you can see, I’m calling Dispatcher.BeginInvoke in the callback method.  This is necessary because we’re accessing the UI thread; omitting this will result in an invalid cross thread access exception.


And with that’, we’re done! Using this method, you can write highly reusable code: just pass in a matching endpoint, and your code will work.  Next to that, any service implementing your contract can be used, so you could easily create, for example, a mocking service.  Happy coding! :)