Tag Archives: Silverlight

Windows-Phone-7-logo

Throttling Immediate TextBox Binding Behavior for Windows Phone

The learning curve of a Windows Phone developer

While developing Offline Web Browser for Windows Phone i had to build a small MVVM framework in order to keep the logic out of the views.

One of the first thing i found missing was a way to force immediate propagation of text entered in TextBox control to the databound property of my ViewModel.

By default, TextBox binding is triggered only when control loses focus, and this is kind of lame.

Code reuse is not a myth!

This is really old problem. It existed in desktop Silverlight from the beginning. And it made its way to the Windows Phone platform.

Fortunately I remembered that back in the days while experimenting with Silverlight MVVM framework i already solved this problem by creating a custom silverlight TextBox control so i decided to just reuse that code and create a Behavior that will force binding update to fire on each keystroke in TextBox.

That’s the beauty of developing a Windows Phone app – you can reuse most of the Silverlight code you built over the years :)

But then i noticed another problem. Because now each keystroke was propagating changes to my ViewModel, if user would type fast and i do for example some web service call on each property change – then i can have too many requests to the web service (one for each keystroke) but in fact i want to do a call only when user stopped typing for a while.

Fortunately, solution is very simple – we will use Reactive Extensions (Rx) since its perfect fit and its already built-in into Windows Phone.

We just need to reference Microsoft.Phone.Reactive.dll from GAC (no additional download needed) and we are half-way there.

OK, but show us some code!

Yes lets see how the code for the ThrottledImmediateBindingBehavior looks like:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
using Microsoft.Phone.Reactive;

namespace Roboblob.Mvvm.Behaviors
{
    public class ThrottledImmediateBindingBehavior : Behavior
    {
        private BindingExpression _expression;

        public bool Throttle { get; set; }

        private double _throttleDelayInSeconds = 0.5;
        private IDisposable _currentObservable;

        public double ThrottleDelayInSeconds
        {
            get { return _throttleDelayInSeconds; }
            set { _throttleDelayInSeconds = value; }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            if (Throttle)
            {
                this._expression = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
                var keys = Observable.FromEvent(AssociatedObject, "TextChanged").Throttle(TimeSpan.FromSeconds(ThrottleDelayInSeconds));
                _currentObservable = keys.ObserveOn(Deployment.Current.Dispatcher).Subscribe(evt => OnTextChanged(evt.Sender, evt.EventArgs));
            }
            else
            {
                this._expression = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
                this.AssociatedObject.TextChanged += this.OnTextChanged;
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            if (Throttle)
            {
                if (_currentObservable != null)
                {
                    _currentObservable.Dispose();
                    this._expression = null;
                }
            }
            else
            {
                this.AssociatedObject.TextChanged -= this.OnTextChanged;
                this._expression = null;
            }
        }

        private void OnTextChanged(object sender, EventArgs args)
        {
            if (_expression != null)
            {
                this._expression.UpdateSource();
            }
        }
    }
}

Simple Is Beautiful

Our Binding class has bool property Throttle where we can enable/disable throttling and also a ThrottleDelayInSeconds where we specify after how many seconds later after user stops typing our property is updated.

In the OnAttached – we just hook to the TextChanged and each time user types something we update the binding source.

But if Throttle is set to true, we hook to the TextChanged event over Reactive Extensions and we setup throttling so that binding do not trigger if changes are too fast.

In this only after changes stop firing for the time defined in ThrottleDelayInSeconds, only then binding update is triggered.

Off course we do a little cleanup in the OnDetaching as all good coders :)

What about the Xaml???

Yes in Xaml we can use it like this:

            <TextBox Text="{Binding SearchCriteriaText, Mode=TwoWay}">
                <i:Interaction.Behaviors>
                    <RoboblobBehaviors:ThrottledImmediateBindingBehavior Throttle="True" ThrottleDelayInSeconds="1" />
                </i:Interaction.Behaviors>
            </TextBox>

For those who are lazy to type I’m attaching a zipped source code of simple Windows Phone Mango project that is demonstrating the usage of the behavior.

Btw does somebody even remember how it was to type source code from printed computer magazines int your 8bit computer?

Probably not :D

Well at least I hope that someone will find this useful.

Until next time, happy coding!

Using Offline Browser for Windows Phone as Instapaper client

 

 

Lets set some expectations here. We wont be adding new items to Instapaper.com reading list or removing items or anything similar.

We can use our desktop PC for that.

Here we will just explain how to use Offline Browser for Windows Phone to get all those links from Instapaper.com reading list via RSS feed and download them to the phone so we can read them whenever we want – even when we are offline.

So first we need to add the Instapaper unread items Rss feed into Offline Browser as a Links Feed.

Here is how you can do that:

1. Open the Offline Browser for Windows Phone and on the Browser page go to Instapaper.com and login to your account.

Once you are logged in, you will be redirected to this url: http://www.instapaper.com/u which is your unread items list.

2. Now we should find the RSS feed of your unread Instapaper items and use it as links source (Link Feed) of the Offline Browser app.

The RSS feed icon and link are at the bottom right corner of the http://Instapaper.com/u web page, take a look at the screenshot below:

3. Now long tap that link ‘This folder’s RSS’ and context menu of Offline Browser will appear:

4. Click on the “Add Link as Links Feed” item and RSS feed of your unread instapaper items will be added as Links Feed for the Offline Browser.

5. Now lets enable Links Feed synchronization in settings:

There we see the RSS feed from instapaper added to the app as Link Feed and we see that background downloading of the URLs from the feeds is enabled and done every 2 hours.

So even if our application is not running, a background task will retrieve the RSS feed and if there are new links they will all be added to the download queue.

When this happens you will get a toast notification and live tile of the Offline Browser will show number of new links retrieved from all feeds.

Here is how this looks on the Windows Phone start screen:

6. When we click on the Offline Browser icon and there are new items to download we are immediately taken to the download queue screen.

There you can simply click on the Sync button and all new links from download queue will be downloaded.

(app will also check if there are some newer items in the feed and retrieve them together with the items that are already in the download queue).

Once pages are downloaded we can go to the saved pages screen and open them in the browser screen:

Its important to say that once you go through this process and your instapaper RSS feed is added to the app, it becomes automatic and phone will download any links you add to your instapaper reading list.

So now that you know how you can use Offline Browser as your Instapaper client – go ahead, download it from marketplace and give it a try!

lghthouseLogo_cr

Lighthouse – Silverlight Unit Test Runner Project released

Unit Testing in Silverlight? But you need Web Browser to do that!

No you do not! Ok maybe you do. But not in a direct way. I will clarify that later. Lets first go back in time to the root of the story:

Since the initial release of Silverlight i was really annoyed by the fact that Unit Testing had very slim support.

Even later when Silverlight Unit Testing Framework was introduced by Microsoft things became little better but still it was far from good.

You could create Unit Tests, but you had to start your Visual Studio in order to run them – eventually looking at the results of tests in your favorite Web Browser.

That ruled out one of the most important facets of Test Driven Development – running your Unit Test on Continuous Integration server, so that you can easily see when any of your Unit Tests are broken – in other words treating your Unit Tests equally as all your code, like you should.

Not to mention that there was no way to run Unit Tests from Reshaper! (oh boy don’t even let me get started on that one).

Can feeling of anger be a motivation for good deeds?

Very likely. I started by investigating what open source projects were available to fill these Silverlight TDD gaps.

And i did found few of them. But they were either too complex or simply did not work properly and failed to run tests from one reason or the other.

This is how i decided to create project Lighthouse – probably in same way how many other open source projects are born: to scratch an itch of single developer, for the benefit of the community :)

What is it for? What’s the Roadmap?

Lighthouse is envisioned as project that will host multiple tools that will allow Silverlight developers to do Test Driven Development much easier then before.
First tool in this project Silverlight Command Line Unit Test Runner has just been released on Codeplex website.

Lighthouse Command Line Unit Test Runner is console application that runs given Silverlight Unit Testing Framework Unit Tests and collects their results and saves them in known NUnit XML Unit Tests results file format on your hard-drive.

What can i expect?

The rule of the thumb goes like this:

YOUR SILVERLIGHT UNIT TESTS SHOULD BEHAVE EXACTLY THE SAME WHEN YOU RUN THEM WITH LIGHTHOUSE AS IF YOU ARE RUNNING THEM FROM VISUAL STUDIO OR WEB BROWSER.

In other words: If they failed in browser, they will fail when you run them via Lighthouse in completely same way (same timing, same exception etc) – and vice versa.

You can use Lighthouse to run tests in XAP packaged application or you can use it to run tests directly specifying your Silverlight DLL’s – it is very flexible.

Currently Lighthouse saves results in NUnit XML Unit Tests results file format so that means you can use it to run your Unit Tests in ANY Continuous Integration server that supports this format – CCNet, Team City you name it.

In future we will maybe add more output XML formats, but for start this should suffice.

Lighthouse Silverlight Command Line Unit Tests runner supports variety of command line switches so you can tweak it to work how you need it.

You can specify Tag Filter to run only certain test cases.

You can specify timeouts, output log file, output directory etc.

Make sure you visit the Lighthouse Command Line Test Runner Documentation page to get familiar with all the options.

In the future we are planning to develop Resharper plugin to run Silverlight Unit Tests, but you will here more on that when its ready.

And how does all this work?

Its much simpler to explain then it was to make it work:

In its essence, Lighthouse analyzes your XAP/Assemblies and modifies them in a way so that it can control the Unit Test execution. It then fires up a web browser instance in the background and start this modified Silverlight application and collects the results of all Unit Tests. Results are saved in XML file and everyone go home and live happily ever after.

What now?

Until future releases I’m asking all interested Silverlight developers to use Lighthouse and send us feedback or even join the Lighthouse team to make it better.

For the end check out this short video where Lighthouse Command Line Runner executes Silverlight Unit Tests from Sterling project:

Stay tuned…

Microsoft Silverlight 4 Certification, is it worth the ride?


Roboblob's Silverlight 4 Microsoft Certificate
Silverlight 4 Microsoft Certificate

Now some good news folks: I received the confirmation that I successfully passed the Silverlight 4 Microsoft Certification.

I was too busy to immediately brag about it and write a show-off post so I will here just quickly share my thoughts on how all this went before my brain moves these impressions to non-accessible-memory-banks-prepared-for-deletion.

First of all I must admit that I was pretty sceptical about the whole certification thing. I’m not big fan of certifications in general and I find it a bit overrated – who cares about fancy printouts people are framing on their walls. You either know how to do your job or you don’t and some poster with Microsoft stamp on it wont change that in any way.

But at that time (it was 3 months ago) Silverlight 4 Exam was beta test (you could take it for free) and in that period of time I was switching my corporate job to become a full time Silverlight developer so this seemed like perfect opportunity to test my knowledge – and I applied.

Honestly I did not had enough time to prepare for the test – even though I was planning to do so. Simply could not find the time or strength to study and eventually I had to go for a test without any especial preparations – all I had was my hands-on experience in writing Silverlight code and few books I have read on the subject along the way.

Naturally I expected lots of theory mumbo-jumbo in the test so I was sure I will fail-fast :)

But to my surprise the test was mainly pragmatic with questions from real-world Silverlight programming practice so it turned out I did pretty good after all.

It was interesting that some parts of the test required knowledge of MVVM pattern – just as if they asked me what to put there :D

All in all test turned out to be more serious and realistic than I expected so this is +1 for old Microsoft.

In case any one of you want to take the test and don’t know how to prepare I have two things I could recommend:

  1. read THE book: Pete Brown’s Silverlight 4 In Action – Its the best Silverlight book I have read so far and covers most of the knowledge needed for the exam.
  2. Mark Monster also participated in the Beta Silverlight 4 testing and blogged about how he was preparing for it so this is also worth reading.

All in all this was fun ride, and now I’m looking forward to Silverlight 5 Certification announcements :)