.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, 
UriKind.Absolute);
  
    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
               Cows.Add(returnVal);
           });
       }
       ,  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:

 

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

 

and:

 

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

 

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:

 

slchannelfactorywithcows

 

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
    {
        [OperationContract]
        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
                   Cows.Add(returnVal);
               });
       }
       , 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! :)

Featured, General, Silverlight »

[4 Feb 2011 | 0 Comments]

In October last year, I participated in the beta exams for Silverlight MCTS certification.  Last week, I was notified that I had passed the exam, so – quite excitedly – I tweeted about this.  Not soon thereafter I got a few questions from people asking me what to expect of the exam, and how to prepare for it.  Therefore, I decided to dedicate a blog post to it.

 

So, what can you expect of this exam, 70-506, Silverlight 4 Development?  If you’ve taken any other MS Certification exam, you already know what you’re going to get: a bunch of multiple choice questions, spanning about every aspect of Silverlight development.  Questions can be more theoretic, but often consist of a proposed problem, and 4 code examples you have to choose the right one from.  I got the feeling the questions were much more aimed at real-life problems compared to other certification exams I took in the past.  I vividly remember a .NET Fundamentals exam (.NET 2.0) containing questions like “What is the correct syntax for xxx”, with possible answers consisting of useless (due to IntelliSense) wrongly spelled class names. 

 

No such silliness here: for almost all code-related questions, I could easily imagine a real-life situation where I would pose myself that exact question. 

 

You should, however, have a vast knowledge of all the core concepts: DataBinding, INotifyPropertyChanged, Converters, DataContext, Validation, … as there were questions about all of these.  That said: this is something every serious Silverlight developer should know about.

 

Next: how should you prepare for this exam?  At the moment, there isn’t a book you can buy/download (might want to read mine though ;-)) specifically aimed at the exams.  But: if you’re working with Silverlight day to day, you should be able to pass the exam without any problems.  I’ve been working with it for more than 2 years now, and I didn’t prepare for the exam at all, yet there were very few questions I wasn’t able to answer with certainty – so I guess my main advice would be: don’t worry, you can do it! ;-)

 

However: if you haven’t been developing SL projects for a while, you should prepare – and even if you have, brushing up on your knowledge is always a good idea.  Luckily, there are resources to be found around the web:

 

 

Look at these links, and you should be more than prepared for the exam.  Good luck!

.NET, Featured, MVVM, Silverlight »

[28 Jan 2011 | 4 Comments]

Image this: you’re working on a Silverlight application, using the MVVM pattern, and you want to do something with the result of an async request (for example, you’re fetching persons, and you want to add them to a list in your VM when the operation completes).  Something like this:

 

PersonServiceReference.PersonServiceClient client = 
new PersonServiceReference.PersonServiceClient();
          
client.LoadPersonsCompleted += (s, a) =>
{
    if (a.Error == null)
    {
        AllPersons = new ObservableCollection<Person>(a.Result);
     }
};
client.LoadPersonsAsync();

 

However, when you do this, you get an “invalid cross-thread exception” (if AllPersons is bound to a list in your UI).  What does this mean?  Simply put, you’re trying to access the UI thread (as the list you’re manipulating is bound to something in your UI), but you’re doing this from another thread: the thread on which your async operation runs.

 

Luckily, this is pretty easy to solve: invoke the Dispatcher as such and you’ll get rid of above exception:

 

Dispatcher.BeginInvoke(() =>
{
// your code
});

 

Now, if you’re trying this at the moment, and you’re using the MVVV pattern, you’re probably trying this in your VM and you’ve probably noticed something: it doesn’t work.  Why?  It doesn’t work because you don’t have access to the dispatcher: you can only get to it from inside of classes inheriting UI controls (such as UserControl, Page, …).  Quite logical, actually: since it’s used for trying to get back to the UI thread, it’s useless in non-UI-related code.  Operations like that aren’t allowed: for example, try to access the Applications’ RootVisual from inside a VM, and you’ll get an unauthorized access exception.

 

However, in MVVM, we actually DO need access to the Dispatcher.  Luckily, it’s not that hard to do.  The solution I prefer is keeping the dispatcher in a static variable, so it’s accessible from anywhere in your application.  To achieve this, create a class (eg: LocalStateContainer) with a static variable in your application.  In your App Start, fill this variable with the dispatcher:

 

LocalStateContainer.Dispatcher = RootVisual.Dispatcher;

 

Now, you can access it from anywhere in your application to get back to the UI thread when needed. 

 

To get back to our original problem, following code will solve it:

 

PersonServiceReference.PersonServiceClient client = 
new PersonServiceReference.PersonServiceClient();
          
client.LoadPersonsCompleted += (s, a) =>
{
    LocalStateContainer.Dispatcher.BeginInvoke(() => 
    {
        if (a.Error == null)
        {
            AllPersons = new ObservableCollection<Person>(a.Result);
         }
    });
};
client.LoadPersonsAsync();

 

Hope this helps some of you out! :)

.NET, General, Silverlight, Headline »

[25 Jan 2011 | 0 Comments]

imageAs last year, MIX2011 had an open call for sessions.  Apparently, the response was overwhelming, and looking at the shear number of sessions available for voting there were a whole lot of quality session submissions. 

 

I’m glad to announce that one of my session proposals was withheld as well – all I need now is your vote! :-)

 

 

 

 

This is the session excerpt:

 

Silverlight, MVVM & WCF RIA Services: an architectural story

At the start of each project, you’ll have to lay out your solution architecture - and it’s very important to "get this right". Silverlight, MVVM & WCF RIA Services work nicely together, but as with each architecture, the best solution depends on your application requirements. What are your options in this case? What are the pitfalls? How can you tie these technologies together to provide you with a solid foundation for your projects? This is an in-depth session, based on real-life experience.

 

So if you want to do me a favour, please vote for my session @ MIX11.  And while you’re at it (after all, you’ve got up to ten votes to spend ;-)), have a look at the sessions of two of my colleagues as well, Maarten Balliauw and Sandrino Di Mattia

 

Tnx!

General »

[13 Jan 2011 | 0 Comments]

The publisher of our book just let me know they will be releasing five new Microsoft books on Monday, 24th of January.  To celebrate this, they’re offering a 25% discount on all Microsoft books (starting from 2 orders or more) during the whole month of January.  This of course includes my book, Silverlight 4 Data and Services Cookbook (so yes, this post is actually a small commercial intervention ;-)).

 

Next to that, they’re also giving away a free 1-year subscription every Monday, worth $220.  So if you want access to all Packts’ books for free, this is your chance.

 

Good luck!

General »

[11 Jan 2011 | 0 Comments]

The year has just started, and it's already developing into an exciting one.  Coming up in the next few months are some really cool projects, both at work and private - including one with Windows Phone 7 & Azure if all works out. 

 

I'll also try to write some more content for this blog.  Next to the book, I've been writing various articles for Silverlight Show and .NET Magazine (Dutch edition) in 2010, but I'll try and add a bit more blog-exclusive content as well.  Oh, and on the book-front some exciting news is coming up as well ;-)

 

What about sessions?  The "presentation season" is coming up again: in the next few months, we've got TechDays & MIX to look forward to - I'm pretty sure we'll get some new info on Silverlight 5.  And who knows, maybe a new version of WCF RIA Services?  I'd really like that - it's by far my favourite framework for building data driven Silverlight apps.  As far as personal sessions are concerned: I've submitted quite a few session proposals for various events, we'll see what gives ;-)

 

All in all it's safe to say 2011 will be an exciting year, technology-wise.  I'm looking forward to it - I hope you are as well :-)