Concurrent Web Service Calls from Windows Phone 7 using Rx

Introduction

I’m pretty sure that everybody who works with Silverlight, WPF or WP7 have come across the issue when you just want to call a couple of web services independently from each other but wait for all the results and build a complex object from those results. Well right now I’ve came across this issue once more. I’m building a WP7 application that calls the Facebook API and at the same time I have to call my own services on Windows Azure. I definitely don’t want to communicate with Facebook on the server side since that would be expensive in every possible way. (Performance, usage, price, etc.) Not the mention that I would have to impersonate my user and call the Facebook API from the server side, which would definitely be a security issue. So I have to deal with this on the phone.

I could definitely write the code to synchronize these calls, but after a while it’d get kind of impossible to handle and understand. I could of course do some kind of an abstraction, build an infrastructure around it, but this would just give me a headache and cause additional costs (my time).

Here is some good news. We have a technology that was basically born to solve these kind of issues. The technology is called Reactive Extension (Rx) and it is available for Windows Phone 7. The bad news is that it’s kind of hard to understand, many people tried and to tell you the truth a hell of lot of them just failed. The problem with this technology is that it needs a different thinking, a whole new mind, a switch in your brain to flip. So here is the deal, I’m not going to try to explain Rx. There are a lot of HOLs, sessions, tutorials, blog posts to learn about it. What I’m going to do, is to show you only what you need here to solve this issue, and make you understand only this little part. (Which is IMHO maybe the most useful part clip_image002[4]) If you want to inspect Rx a little bit more you can start with Mike Taulty’s blog and video post: Reactive Extensions “for the rest of us”

The Problem Simplified

So the model of our problem: I have a WP7 client implemented with MVVM. I need to make asynchronous calls to the server side. I need to call two entirely different web service operations. After both calls are completed I need to process the data received from the two service calls. This is it, let’s see what we can do.

Very short intro to Rx – The Mindset

Now imagine we have a couple of objects. These objects have events. Imagine that I create a collection and add these events to this collection. Now I’m waiting for these events to fire. What I need is someone to tell me if all the events in this collection have already fired. Also maybe I want to be notified about every single event that was fired at the time of firing. Still with me, right? Now lets flip that switch in your brain.

What do we have now? We have a collection of events, (or data) and information (one of them is fired, all of them are fired, a certain subset was fired, etc.) that is being pushed towards us! So instead of a collection think of it as a stream. A stream of data, a stream of events. You subscribe to a stream of events/data, and every single time something happens, or data is available, notification (information) is being pushed towards you! All you have to do is to deal with this information.

Very short intro to Rx- Observing Objects

Now this is the part where I’m not going to dive into how Rx works. But what you need to understand is that if you want to observe an object (event, data, collection, whatever) you have to make it observable!

//Two different service to call concurrently
TestService1Client client1 = new TestService1Client();
TestService2Client client2 = new TestService2Client();

//Observe this objects for specific events
var observedServiceCall1 =
    Observable.FromEvent<GetDataCompletedEventArgs>(client1, "GetDataCompleted");
var observedServiceCall2 =
    Observable.FromEvent<GetIntDataCompletedEventArgs>(client2, "GetIntDataCompleted");

Take a look at what we did! We have these two service client proxies. Both proxies have a “Completed” event. (GetDataCompleted and GetIntDataCompleted). Using the Observable.FromEvent<TEventArgs>(source, eventName) method we make observable objects from these events! Now we are ready to subscribe to them!

observedServiceCall1.Subscribe(OnNext);

OnNext deals with the data whenever the GetDataCompleted event fires. But this is not what I want. What I want is to handle these events as a group and I want to be notified only when both events have fired!

Very short intro to Rx – Observing multiple events as a single unit

So I have to tell the Rx framework that I need to observe these events together!

//Observe on background thread
//Observe both objects simultanously
var combinedCall = observedServiceCall1.ObserveOn(Scheduler.ThreadPool)
    .Zip(observedServiceCall2, (left, right) =>
{
    //save results from the two calls to a complex object
    return new CombinedCallResult
    {
        Call1Result = left.EventArgs.Result,
        Call2Result = right.EventArgs.Result
    };
});

This is exactly what I need! The key operator is the Zip operator! This is the one that allows me to combine these two observable object. Now I’ve created this aggregated observable object (combinedCall). Let me explain this code a little:

§  ObserveOn(Scheduler.ThreadPool) – I want to do the observing on the background thread. As a matter of fact I want to do everything on a background thread, so my UI can stay responsive! Scheduler.ThreadPool just gives me a thread from the ThreadPool that I can work with.

§  Zip(rightSource, selector) – Zip will help me create a new observable that will now observe observedServiceCall1 AND observedServiceCall2! Selector is basically a function that will deal with the individual results. So when I get the result I wrap it into this custom class.

§  (left,right) – left stands for the observed event of observedServiceCall1, right stand for the observed event of observedServiceCall2

Very short intro to Rx – Subscription

So now we have the combinedCall observable that helps us observe two events! Now the last thing we need is to subscribe to any info that may be pushed to us!

//Subscription: Both service calls have been completed
combinedCall.ObserveOn(Scheduler.Dispatcher).Subscribe((result) =>
{
        AggregatedData = "WebService Call 1: " + result.Call1Result +
            "\nWebService Call 2: " + result.Call2Result;
});

Now we are subscribing to the results! When data is pushed to the Observer, this code will run! We‘re just updating a property in the ViewModel. But this one is tricky! Because AggregatedData is bound to the UI! It actually raises the PropertyChanged event. And a couple of minutes ago we agreed to do the observing on a background thread. Now this would result in an invalid cross-thread exception. This is something we don’t want, so we tell Rx, that we will need to process the data on the UI Dispatcher! So now the code inside the lambda expression will be running on the UI thread.

All the code together

Now this might be a little confusing so take a moment and read through all the code needed to solve this problem.

//Two different service to call concurrently
TestService1Client client1 = new TestService1Client();
TestService2Client client2 = new TestService2Client();

//Observe this objects for specific events
var observedServiceCall1 =
    Observable.FromEvent<GetDataCompletedEventArgs>(client1, "GetDataCompleted");
var observedServiceCall2 =
    Observable.FromEvent<GetIntDataCompletedEventArgs>(client2, "GetIntDataCompleted");

//Observe on background thread
//Observe both objects simultanously
var combinedCall = observedServiceCall1.ObserveOn(Scheduler.ThreadPool)
    .Zip(observedServiceCall2, (left, right) =>
{
    //save results from the two calls to a complex object
    return new CombinedCallResult
    {
        Call1Result = left.EventArgs.Result,
        Call2Result = right.EventArgs.Result
    };
});

//Subscription: Both service calls have been completed
combinedCall.ObserveOn(Scheduler.Dispatcher).Subscribe((result) =>
{
        AggregatedData = "WebService Call 1: " + result.Call1Result +
            "\nWebService Call 2: " + result.Call2Result;
});

//Issue the calls
client1.GetDataAsync();
client2.GetIntDataAsync();

Threading in pictures

clip_image009[4]

As you can see on the picture above, we are calling the services asynchronously, and observing happens on a worker thread!

Now you just have to free your mind and start using Rx to make your life a whole lot easier! You want 3-4-5 calls running at the same time? You want to run them in a certain order? (chain of call?) You just got a very compact and easy to read and maintainable solution to do all the asynchronous code management you need.

If you want the source code for this sample, you can get it here: RxWebServicesDemo

My Session at MIX11: Effective Validation Techniques with MVVM in Silverlight

MIX11_BB_I'mSpeakingAt_2I’m really happy to announce that I’ll be presenting at the MIX’11 Conference in Las Vegas! I will be talking about how to implement decent validation in Silverlight when using the MVVM pattern.

Here is the link form my presentation: http://channel9.msdn.com/events/MIX/MIX11/OPN05

Now what I want is to provide you with the most accurate and most important details about this topic. So here is your chance to have an impact on this session. Tell me about the scenarios that are really crucial for you in you application and for which you’d love to see a solution. Here are some details (just some bullet points) I plan to include my presentation:

  • Attribute based validation
  • Correct implementation of IDataErrorInfo and INotifyDataErrorInfo in a ViewModeBase
  • Issues when binding directly to the Model
  • Async Scenarios (client and server side validation),
  • Dependency on other properties and complex objects
  • Doing Validation when Binding doesn’t happen (required fields without ever gaining focus)
  • Notifying the ViewModel about wrong input (Input is not in a correct format (+a tip on how to “localize” it))
  • Customizing Validation Feedback with VisualStateManagement + Blend
  • Custom states +a couple of nice behaviors to push the view in invalid state
  • Life without INotifyDataErrorInfo (validation in WP7)

So if there is something you’d wish to hear about just ping me!

.NET RIA Services Introduction

When you’re working with Silveright one of your main challenges is to get the data you want from the database
through multiple tiers and pass it to your Silverlight client using some kind of a WebService. You’d want full CRUD support no matter what architecture pattern you are are using and you’ll need client side change tracking as well. You’d welcome features as code sharing, validation, authentication and authorization support on service operations and of course all these should be enabled automatically by a code generation process.

This is the first one of a series of screencasts in which I’ll try to introduce you to .NET RIA Services which aims to solve the issues mentioned above.

The first video provides a glimpse into the basics how .NET RIA Services works. Hope you’ll enjoy it!

You can download the demo project from here:

What’s new in Silverlight 3.0 – UI to UI binding

Developers coming from the WPF world missed a very important feature in Silverlight. It was the ability to bind directly to UI elements. This was creating simple master-details scenario was impossible unless introducing extra properties between the UI element. (Maybe in the ViewModel for example)
Starting from Silverlight 3.0 Element to Element binding is supported so now WPF developers can be satisfied. 🙂 Here is a very simple demonstrative sample.
image
In the previous example we bind the Slider’s Value property to the rectangle’s Effect.ShadowDepth property. (ElementName determines the UI element, while Path deteremines the specified property). The result should be the following:
image
Changing the values on the slider is immediately reflected by the DropShadowEffect because of the binding defined earlier.
As you can see it this is a very easily applicable but also a very important feature. Just imagine that we bind a DataForm’s CurrentItem property to a DataGrid’s SelectedItem property which would be a very simple and effective support for Master-Detail scenarios.
The sample Demo project can be downloaded here:

Binding update on TextBox.TextChanged event using Behaviors

In Silverlight 3.0 we have the UpdateSourceTrigger property for the Binding object which enables us to define when to save the data back to the underlying (data)property through the binding.

UpdateSourceTrigger has 2 mode:

  1. Default
  2. Explicit

Well, if it comes to TextBox it is really annoying that the update only occurs after the control loses focus. (The default setting for UpdateSourceTrigger is basically LostFocus) Now in WPF you have the UpdateSourceTrigger.PropertyChanged enumeration value which updates the data every time  the TextChanged event fires. Silverlight 3.0 doesn’t support this mode.

Now a workaround could be to implement a Behavior for TextBox. The code should be somehting like this:

image

Little explanation:

When a Behavior gets attached to the object, which in this case is limited to a TextBox, the OnAttached() method runs.

In the implementation of this method we subscribe to the TextChanged event. AssociatedObject is the textbox itself. Now when the TextChanged event fires our AssociatedObject_TextChanged eventhandler method runs. This method will get the binding defined on the TextBox’s Text property and will explicitly update the source property.

The OnDetaching() method runs if we remove the Behavior. In our case this means we have to unsubscribe from the TextChanged event.

Now lets go to Expression Blend 3.0. On the assets panel browse our new UpdateOnTextChangedBehavior and drag and drop in on the textbox. And that’s it. It’s just working.

image

The xaml would look like the following:

image

You can download the code file here in case you need it:

http://cid-6a68a5d249fe7d3a.skydrive.live.com/embedrowdetail.aspx/Public/BehaviorLibary/UpdateOnTextChangedBehavior.cs

Hope this helps!

RIA Services Nuggets – DataPager Issues

Friday I was really brave. (or just crazy) I decided to use Entity Framework as a data source (for the first time) and tried to show the datapaging feature with .NET RIA Services. (Rule No.1: Don’t ever try a demo you’ve never tried before. :)) It has such a cool lazy loading feature. My xaml looked like this:

clip_image001_thumb2

Then it hit me in the face. 20 items were loaded just fine but from 20 to I don’t know how many it just wouldn’t work. The data never arrived. I was quite surprised. Finally I decided to give it up since it’s probably a bug and RIA is just CTP. Then I came home and tried to reproduce the issue and I succeeded! 🙂 I had to face the fact: IT WAS NOT WORKING! Come ooooon! Such a basic thing and it’s bugy…. It made me really upset. 🙂

Then I got into it a little deeper and tried to debug the issue. I found an interesting error message:

“The method ‘Skip’ is only supported for sorted input in LINQ to Entities. The method ‘OrderBy’ must be called before the method ‘Skip’.”

Well yeah… that was it. The paging functionality is implemented with the use of Take and Skip methods. However in Entity Framework you can call these methods only on sorted collections and by deafult ObjectQueries are not sorted unless you call OrderBy() on them. So I had to modify the GetCustomer operation in my DomainService like this:

image_thumb1

Now it’s working just fine. (SortDescriptors defined on the DomainDataSource would have been just fine as well)

But why isn’t this documented anywhere? Or did I missed something?

What’s new in Silverlight 3.0 – Navigation Framework

In the world of web we are used to passing urls to each other, so we always get the proper page without surfing through the whole website. Not to mention the search crawlers which access data (data in html pages) directly through these links. However with Flash and Silverlight this becomes a little more complicated. The navigation inside the Silverlight application is not tied to the browsers url field. You cannot reference a specific page in your silverlight application with a simple url. Or at least it would take a hell of a lot code to support it.

Well, in Silverlight 3.0 we have the Navigation Framework which pretty much solves the problem stated above.

Now let’s see…

The Navigation Framework has two main objects:

  • Page – A simple silverlight page where you can navigate to.
  • Frame – Each page will be presented inside the frame which controls the navigation process.

Let’s create a NavigationDemo sample Silverlight Application.

Demo application can be downloaded here:

http://cid-6a68a5d249fe7d3a.skydrive.live.com/embedrowdetail.aspx/Public/NavigationDemo.rar

Let’s create a Pages Folder and add three new Silverlight Pages (HomePage, ProductsPage, ContactPage)

clip_image001_thumb2

Our layout in the MainPage.xaml should resemble to this:

clip_image0016_thumb1

Now we have 3 links in the upper right corner. The whole space below is occupied by the Frame. This is where our pages will be presented. Now set the HyperlinkButtons’ NavigateUri properties to navigate to the proper pages:

clip_image0018_thumb2

Add a simple TextBlock inside each page with a unique text so you know when navigation actually occurs.

image 

Let’s take a closer look:

  1. You can see that the title of the page has changed: it’s “Contacts”. This is done through setting the Page.Title property in ContactPage.xaml to the “Contacts” string.
  2. The Url shows that we are in the Pages folder, on the ContactPage.xaml. Copy the link, open a new web browser and paste the link. You can see that we are navigated directly to the ContactPage. No need to browse through the HomePage. Yay!
  3. The content of the Frame changed to the specific page’s content. In this case the ContactPage’s TextBlock is visible.
  4. Our navigation bar is unchanged since it’s placed outside the frame. The Contact Us link is selected.
  5. On the picture below you can see that the browser’s back and forward buttons are functioning and they enable navigation through the silverlight application’s pages. We also have history support inside our Silverlight app which is pretty cool.

clip_image001

However our link is not too friendly we could really imagine a somewhat nicer url format. Fortunately the solution is already given by the use of UriMappings. (Later we’ll see there is much more to it than providing more friendly urls.)

So let’s go to the App.xaml and create the mappings. The UriMapper is located in the System.Windows.Navigation namespace in the System.Windows.Controls.Navigation assembly.

image_thumb2

So the mappings are created. Now we have to change the NavigateUri properties to the previously defined aliases:

image_thumb5

One last thing that has to be done.  We have to tell the frame to use our previously defined uri mappings to resolve the urls. This can be done through setting the Frame.UriMapper property. We have to reference the static “mapper” resource:

clip_image00112_thumb1

After running the application we can see that the structure of the url has changed:

clip_image00114_thumb1

Now we have the power to manipulate the url the way we want, so let’s create a master-detail like scenario using a classic querystring. Let’s add a new Page called ProductDetailsPage. On the ProductsPage.xaml add a listbox and fill it up with Products instances:

clip_image00118_thumb1

The code-behind:

image_thumb17

On the Page.Loaded event we load the Products and add them to the listbox.

image_thumb7

When clicking the button we get the selected product’s ID and navigate to the ProductDetails page using the Page.NavigationService property’s Navigate() method and by appending the productID after the url. Right know this doesn’t make to much sense for our SL application but now we know what to do. We have to create a new UriMapping.

clip_image00122_thumb1

You can see that we are mapping a url that contains a querystring like parameter to the much shorter and straightforward form of url that we used above. Between the curly braces there is a placeholder called id which you can reference in the mapping. In our case this means that the querystring parameter can be specified directly after the “Products/” url fragment.

Now we have navigation to an empty page which does nothing at this moment. So let’s add some functionality to it like a stackpanel with 3 databound textblocks to create a view for the Product instance.

image_thumb14

The code-behind:

image_thumb15

The OnNavigatedTo method runs after we arrive to this page. Through the Page.NavigationContext property we can access the QueryString! (the mapping hides it) So we get the parameter that we passed to the current page. The rest of the code is just pure and simple data access and data binding .

So we are done. Let’s take a look at the result:

image

Now we can experiment with links (parameters) like these:

http://localhost:24764/NavigationDemoTestPage.aspx#ProductDetails/1
http://localhost:24764/NavigationDemoTestPage.aspx#ProductDetails/2
http://localhost:24764/NavigationDemoTestPage.aspx#ProductDetails/3

The details page for the various product ids are working smoothly. The Navigation Framework introduced in Silverlight 3.0 solves an important issue. By now you probably have some ideas how this will support SEO but in a next post we will take a closer look on the subject.

If you have any questions do not hesitate to leave a comment! 🙂