Windows 8 Event Viewer’s Immersive-Shell and Metro Style apps

By jay at March 16, 2012 20:41 Tags: , , , , , , , ,

TL;DR: This article talks about an app startup error that can happen with Metro Style apps in Windows 8, how the presence of an app.config file can prevent the app from starting and how the Windows event log viewer’s new Immersive-Shell section can help.

 

The Windows 8 Metro style Xaml/C# application development is an interesting experience.

Since .NET is merely on top of a WinRT and its native structure, you’re left in a bit of a darkness sometimes, when it comes to debugging problems that come from WinRT.

Silverlight and Windows Phone also have their fair share of blind issues of this kind, either by having the application that exits with no apparent reason (when it is in fact a StackOverflow) or because you’ve set two namespaces names with the same content.

You’ve basically left at guessing, particularly on Windows Phone and Silverlight for the desktop, and if you’re lucky enough you’re having a error code that specific enough so that you can narrow your solution to a dozen google can find for you. If you’re not, well you’ve got a E_ERROR. Fail, as they say.

Windows 8 is actually a bit better at that, because of the Event Viewer. There’s a lot of details that appear there, and it’s very informative.

More...

[WPDev] The hidden cost of IL Jitting

By jay at December 02, 2011 22:35 Tags: , , , , , , ,

We’ve gotten used to it. Method jitting is negligible. Or is it really ?

 

IL JITing

The compilation from IL to the native architecture assembly language (or JITting) has been part of the CLR from the very beginning. That’s an operation that was added to make the code execute faster, as interpreting the IL was too slow. By default, it’s happening on the fly, when the code path comes to a method that needs to be jitted, and that impacts the code speed when executing the method the first time.

That compilation step is not exactly free. A lot of code analysis and CPU specific optimizations are performed during this step. This is what arguably makes already JITted code run faster than generic compiled code, where the compiler has no knowledge of the target architecture.

This analysis takes a bit of time, but it is taking less and less time to execute, due to CPUs getting faster, or multi-core JITting features like the one found in .NET 4.5.

We’ve come to a point, on desktop and server machines, where the JIT time is negligible, since it’s gotten fast enough not to be noticed, or be an issue, in the most common scenarios.

Still, if there were times when JITing would be an issue, like it used to be around .NET 1.0, NGEN would come to the rescue. This tool (available in a standard .NET installation) pre-compiles the assemblies for the current platform, and creates native images stored on the disk. When an assembly is NGENed, they appear in the debugger’s “module” window named as “your_assembly.il.dll”, along with some other fancy decorations.

But while there are some caveats, like the restrictions with cross assembly method inline being ignored. It always comes down to a balance between start-up speed and code execution speed.

 

JITing on Windows Phone

On the phone though, CPU is very limited, especially on Generation 1 (Nodo) phones. The platform is too, considering is relative young age. At least on surface.

We’ve got used to create quite a bit of code to ease the development, add levels of abstraction for many common concepts, and lately, for asynchrony.

I’ll take the example of Reactive Extensions (Rx) in this article, just to make a point.

If you execute the following code on a Samsung Focus:

    
    List<timespan> watch = new List<timespan>();

    var objectObservable = Observable.Empty<object>();

    var w = Stopwatch.StartNew();
    Observable.Timeout<object>(objectObservable, TimeSpan.FromSeconds(1));
    watch.Add(w.Elapsed);

    w = Stopwatch.StartNew();
    Observable.Timeout<object>(objectObservable, TimeSpan.FromSeconds(1));
    watch.Add(w.Elapsed);

    output.Text = string.Join(", ", watch.Select(t => t.TotalMilliseconds.ToString()));

You'll consistently get something similar to this :

    20.60, 1.19


Calling an Rx method like this does almost nothing, it’s basicallt just setup. But 20ms is a long time ! Particularly when done on the UI thread, or any other thread for that matter.

These rough measurements tend to show that the Windows Phone platform (as of Mango at least) is not performing any NGEN like pre-jitting, leaving the app the burden of jitting code on the fly.

Still, not everything can be accounted to JITing, there must be type metadata loading, type constructors that are called.

 

Generating code with T4

So to sort that out a bit more, let’s use some T4 templates to generate code and isolate the JIT a bit more :

<#@ template language="C#" #>
using System;
using System.Collections.Generic;

public class Dummy
{
   public static void Test()
   {
      List<int> list = new List<int>();

      <#for (int i = 0; i < 100; i++) { #>
	  list.Add(<#= i.ToString() #>);
      <#} #>
   }
}

 

For different values of iterations, here's what gets out, when timing the call to the method :

Calls First call Subsequent calls
100 1.6ms > 0.03ms
1000 15.7ms > 0.09ms
5000 72.8ms > 2 ms
10000 148ms > 2ms

 

While this type of code is not exactly a good real-life scenario, this shows a bit the cost the IL jitting step. These are very simple method calls, no branching instructions, no virtual calls, … in short, nothing complex.

But with real code, the IL is a bit more intricate, and there’s got to be more logic involved in the JIT when generating the native code.

 

Wrapping up

Unfortunately, there’s not much that can be done here, except by reducing the amount of actual lines of IL that are generated. But that can be a though job, particularly when customers are expecting a lot from applications.

One could suggest to push as much code as  possible on a background thread, even code that seemingly does nothing particularly expensive. But that cannot always be performed on an other thread, particularly if that code depends on UI elements.

Finally, pre-jitting assemblies when installing the applications could be an interesting optimization for the Windows Phone platform, and I’m wondering why this has not made its way to the platform yet…

Asynchronous Programming with the Reactive Extensions (while waiting for async/await)

By jay at November 25, 2011 20:43 Tags: , , , , , ,

This article was originally published on the MVP Award Blog in December 2011.

Nowadays, with applications that use more and more services that are in the cloud, or simply perform actions that take a user noticeable time to execute, it has become vital to program in an asynchronous way.

But we, as developers, feel at home when thinking sequentially. We like to send a request or execute a method, wait for the response, and then process it.

Unfortunately for us, an application just cannot wait synchronously for a call to end anymore. Reasons can be that the user expects the application to continue responding, or because the application joins the results of multiple operations, and it is necessary to perform all these operations simultaneously for good performance.

Frameworks that are heavily UI dependent (like Silverlight or Silverlight for Windows Phone) are trying the force the developer's hand into programming asynchronously by removing all synchronous APIs. This leaves the developer alone with either the Begin/End pattern, or the plain old C# events. Both patterns are not flexible, not easily composable, often lead to memory leaks, and are just plain difficult to use or worse, to read.

C# 5.0 async/await

Taking a quick look at the not so distant future, Microsoft has taken the bold approach to augment its new .NET 4.5 to include asynchronous APIs and in the case of the Windows Runtime (WinRT), restrict some APIs to be asynchronous only. These are based on the Task class, and are backed by languages to ease asynchronous programming.

In the upcoming C# 5.0 implementation, the async/await pattern is trying to handle this asynchrony problem by making asynchronous code look synchronous. It makes asynchronous programming more "familiar" to developers.

If we take this example:

    static void Main(string[] args)
    {
        // Some initialization of the DB...
        Task<int> t = GetContentFromDatabase();

        // Execute some other code when the task is done
        t.ContinueWith(r => Console.WriteLine(r.Result));

        Console.ReadLine();
    }

    public static async Task<int> GetContentFromDatabase()
    {
        int source = 22;

        // Run starts the execution on another thread
        var result = (int) await Task.Run(
            () => { 
                // Simulate DB access
                Thread.Sleep(1000);
                return 10; 
            }
        );

        return source + result * 2;
    }

The code in GetContentFromDatabaselooks synchronous, but under the hood, it's actually split in half (or more) where the await keyword is used.

The compiler is applying a technique used many times in the C# language, known as syntactic sugar. The code is expanded to a form that is less readable, but is more of a plumbing code that is painful to write – and get right – each time. The using statement, iterators and more recently LINQ are very good examples of that syntactic sugar.

Using a plain old thread pool call, the code actually looks a lot more like this, once the compiler is done:

    public static void Main()
    {
        MySyncMethod(result => Console.WriteLine(result));
        Console.ReadLine();
    }

    public static void GetContentFromDatabase (Action<int> continueWith)
    {
        // The first half of the async method (with QueueUserWorkItem)
        int source = 22;

        // The second half of the async method
        Action<int> onResult = result => {
            continueWith(source + result * 2);
        };

        ThreadPool.QueueUserWorkItem(
            _ => {
                // Simulate DB access
                Thread.Sleep(1000);

                onResult(10);
            }
        );
    }

This sample somewhat more complex, and does not properly handle exceptions. But you probably get the idea.

Asynchronous Development now

Nonetheless, you may not want or will be able to use C# 5.0 soon enough. A lot of people are still using .NET 3.5 or even .NET 2.0, and new features like async will take a while to be deployed in the field. Even when the framework has been offering it for a long time, the awesome LINQ (a C# 3.0 feature) is still being adopted and is not that widely used.

The Reactive Extensions (Rx for friends) offer a framework that is available from .NET 3.5 and functionality similar to C# 5.0, but provide a different approach to asynchronous programming, more functional. More functional is meaning fewer variables to maintain states, and a more declarative approach to programming.

But don't be scared. Functional does not mean abstract concepts that are not useful for the mainstream developer. It just means (veryroughly) that you're going to be more inclined to separate your concerns using functions instead of classes.

But let's dive into some code that is similar to the two previous examples:

    static void Main(string[] args)
    {
        IObservable<int> query = GetContentFromDatabase();

        // Subscribe to the result and display it
        query.Subscribe(r => Console.WriteLine(r));

        Console.ReadLine();
    }

    public static IObservable<int> GetContentFromDatabase()
    {
        int source = 22;

        // Start the work on another thread (using the ThreadPool)
        return Observable.Start<int>(
                   () => {
                      Thread.Sleep(1000);
                      return 10;
                   }
               )

               // Project the result when we get it
               .Select(result => source + result * 2);
    }

From the caller's perspective (the main), the GetContentFromDatabase method behaves almost the same way a .NET 4.5 Task would, and the Subscribe pretty much replaces the ContinueWith method.

But this simplistic approach works well for an example. At this point, you could still choose to use the basic ThreadPoolexample shown earlier in this article.

A word on IObservable

An IObservable is generally considered as a stream of data that can push to its subscribers zero or more values, and either an error or completion message. This “Push” based model that allows the observation of a data source without blocking a thread. This is opposed to the Pull model provided by IEnumerable, which performs a blocking observation of a data source. A very good video with Erik Meijer explains these concepts on Channel 9.

To match the .NET 4.5 Task model, an IObservable needs to provide at most one value, or an error, which is what the Observable.Start method is doing.

A more realistic example

Most of the time, scenarios include calls to multiple asynchronous methods. And if they're not called at the same time and joined, they're called one after the other.

Here is an example that does task chaining:

    public static void Main()
    {
        // Use the observable we've defined before
        var query = GetContentFromDatabase();

              // Once we get the token from the database, transform it first
        query.Select(r => "Token_" + r)

             // When we have the token, we can initiate the call to the web service
             .SelectMany(token => GetFromWebService(token))

             // Once we have the result from the web service, print it.
             .Subscribe(_ => Console.WriteLine(_));
    }

    public static IObservable<string> GetFromWebService(string token)
    {
        return Observable.Start(
            () => new WebClient().DownloadString("http://example.com/" + token)
        )
        .Select(s => Decrypt(s));
    }

The SelectMany operator is a bit strange when it comes to the semantics of an IObservable that behaves like a Task. It can then be thought of a ContinueWith operator. The GetContentFromDatabase only pushes one value, meaning that the provided lambda for the SelectMany is only called once.

Taking the Async route

A peek at WinRT and the Build conference showed a very interesting rule used by Microsoft when moving to asynchronous API throughout the framework. If an API call nominally takes more than 50ms to execute, then it's an asynchronous API call.

This rule is easily applicable to existing .NET 3.5 and later frameworks by exposing IObservable instances that provide at most one value, as a way to simulate a .NET 4.5 Task.

Architecturally speaking, this is a way to enforce that the consumers of a service layer API will be less tempted to synchronously call methods and negatively impact the perceived or actual performance of an application.

For instance, a "favorites" service implemented in an application could look like this, using Rx:

    public interface IFavoritesService
    {
        IObservable<Unit> AddFavorite(string name, string value);
        IObservable<bool> RemoveFavorite(string name);
        IObservable<string[]> GetAllFavorites();
    }

All the operations, including ones that alter content, are executed asynchronously. It is always tempting to think a select operation will take time, but we easily forget that an Addoperation could easily take the same amount of time.

A word on unit: The name comes from functional languages, and represents the void keyword, literally. A deep .NET CLR limitation prevents the use of System.Void as a generic type parameter, and to be able to provide a void return value, Unit has been introduced.

Wrap up

Much more can be achieved with Rx but for starters, using it as a way to perform asynchronous single method call seems to be a good way to learn it.

Also, a note to Rx experts, shortcuts have been taken to explain this in the most simple form, and sure there are many tips and tricks to know to use Rx effectively, particularly when it is used all across the board. The omission of the Completed event is one of them.

Finally, explaining the richness of the Reactive Extensions is a tricky task. Even the smart guys of the Rx team have a hard time doing so... I hope this quick start will help you dive into it!

[wpdev] Tips and tricks about updating live tiles in Mango

By jay at September 29, 2011 19:10 Tags: , , , ,

Cet article est aussi disponible en francais.

In the last published applications I've worked on, like Foursquare, Flickr or TuneIn (and more are coming), all of them have live tiles, in both the Pull and locally generated tiles forms. But there are a few things to know to have a great experience with it, and you'll find it out by reading this article.

This is a very powerful feature, letting the user choose how to customize its own very personal experience, with no-one forcing the user into having a tile he does not want. This is the very same reasoning behind the absence of API to add items in Windows 7 task bar.

 

Live Tiles in Pull mode

In the foursquare app there is the main tile, updated via the "pull" model, every hour or so (and the "or so" has a very strong meaning).

That tile that displays the Leaderboard is built in an Azure cloud service using a WPF offscreen rendering, based on the requests of the tile Pull Engine. This tile was built this way because of the limited capabilities of NoDo, where background agents were not available to render it locally on the device.

With Windows Phone Nodo, many users were complaining about the main tile not updating, and quite frankly, this has been a mystery up to the end. It seems like tiles would update on some devices, but not on others, but would only update if the battery power was more 50%.

Also, these tiles seemed to not update if the device is in standby, but only when the user sees the home screen, and when the suggested refresh delay has expired. I say "seem" because it seems like the rules behind this tile update were either not clear, or broken in some way.

This has changed with mango though. The Pull tiles are not updating almost all the time, but the 50% battery rule still seems to apply.

Also there's the rule of the 80KB file size JPEG, that if you go over, your tile won't be displayed.

 

Programmatic Live Tiles

In Foursquare, the user may choose to pin a secondary "Tile" a specific place to its main screen for easy access.

Updating these tiles can be acheived with the ShellTile API, and with that you can set four thing:

  • A title for the front and back
  • An image URL on the front and back
  • A four lines text on the back
  • A number on the front
  • (and you forget about the animated tiles like the people hub)

 

While all these features are interesting, only one of them is actually very useful: Images URL.

All the other properties are not stylable, they only follow the system's colors, and do not fit very well with user generated content. In the case of Foursquare, Flickr and TuneIn, the displayed images is user provided content, and having a white on white text is not very useful.

On the subject of image URLs, setting an external URL sets the image of the tile, but as long as the device does not reboot. If the device is rebooted, the tile looses its content. A pretty strange behavior, if you ask me.

 

Using the new isostore uri schema

Fortunately, it is now possible to store the image locally in a special folder in the isolated storage named  /Shared/ShellContent, and use the new URI prefix "isostore", like this "isostore:/Shared/ShellContent/MyTile.jpg".

This means that you can download the image to display to the isolated storage, and use it from there.

But there's a big problem with using this technique : You do not control the size of the downloaded image. So if it is bigger than 80KB, you're stuck with the accent color background.

On a side note, I'd be curious to know the story behind this isostore prefix, because there are only two places that can use it, SQL CE Databases and Live Tiles. This prefix cannot be used as a Source property for Image controls, even though it would be very useful. But I digress.

 

Generating Live Tiles

Hopefully, it's very much possible to generate a complete tile's content, using the WriteableBitmap.Render method. This method allows the offscreen rendering of any UIElement, then save it using the SaveJpeg extension method to persist it.

The tiles for Foursquare, Flickr and TuneIn are generated this way, using a user control that a real designer person created. This gives great looking tiles, and the layout and style can be updated depending on the dynamic content.

Here are a few things to generate tiles :

  • The "new" (kinda) Silverlight 4 ViewBox control is very handy to resize text to fit the 173x173 layout,
  • You can use an Image control in your render source, but you need to wait for the BitmapImage (not the Image) to raise the ImageLoaded event, (The Reactive Extensions can be very handy for that)
  • You'll also need to set the CreateOptions to None on your BitmapImage to make sure the image is downloaded immediately,
  • If you download images, make sure you have a local fallback image underneath, just in case the remote image cannot be downloaded,
  • Before rendering the content, make sure to call Measure and Arrange methods to force the layout to the 173x173 size required by the tiles.
  • You may need to call Measure and Arrange multiple times, because for some obscure reason, the control to be  rendered may not honor these commands. Check for the ActualHeight and ActualWidth properties values to see if they are correct.
  • Make sure to render your tile before pinning it to the home screen ! The app is basically halted when you call the pin command, and the user may not come back to your app for you to finish the image rendering.
  • Don't take too long to render your tile though, if you wait too much, the user experience if pretty bad. That can definitely be a challenge when downloading content to be displayed on the tile.

But then, you may only refresh your tiles when the application is running, unless you use the new Background Agents mango feature.

 

Updating the tiles with Background Agents

Background agents are Microsoft's way of letting third party apps run code in the background, but with some big restrictions, like memory (4MB), schedule (30 minutes) or duration limits (15 Seconds) for Periodic Tasks.

Here are a few tricks about background agents :

  • Periodic Agents run at a 30 minutes interval, and that is not configurable. So be gentle, you may want to add logic to avoid doing work too often, like not refreshing tiles during the night, and actually update the tile every 3 to 6 hours.
  • Don't wait too much to generate the tile, 15 seconds is very short. And your task may get killed by the OS before that.
  • Don't rely solely on the agent to run to update your tiles, the user may disable your agent using the Settings / Applications / Background Agent page. And the OS may prevent it from running, if it needs to.
  • Abuse of the ScheduledActionService.LaunchForTest, to test your background agent,
  • A background agent runs your code in a different process than your application, meaning that both your app and the agent can run at the same time. Watch out for shared resources, like a SQL CE database or an isolated storage file.
  • If your are updating your tiles in both your application and your background agent, you may need to add some IPC using an old fashion named-Mutex (ahh, the good old days) and synchronize access to your resources.
  • Avoid referencing too many assemblies in your background agent, there are a lot of Unsupported API that may make your app fail certification. You can validate your app using the Marketplace Test Kit automated tests.

About the first point, while I understand the power consumption concerns on running below 30 minutes, I still don't get why that interval cannot be set higher, to avoid that very same power consumption issue. There also must be a story behind this...

Then about the last point, during the Beta Phase of the Mango SDK, the StandardTileData class was considered an unsupported API, making the automatic background update of tiles impossible. Hopefully, this changed since the RC of the SDK and it is now possible to update tiles from background agents.

 

That's it for now. Have fun with the tiles ! 

[wp7dev] Images and cache control in Windows Phone 7.1 (Mango)

By jay at August 20, 2011 16:39 Tags: , , ,

TLDR: Windows Phone 7.1 Mango's Image control now respects HTTP/1.1 server cache directives, and particularly the max-age, meaning better performing apps. And it is doing it better than you could ever do :)

Image loading is one of the weakest parts of third party apps on Windows Phone 7.0 (NoDo).

The Flickr app in WP7 is a good demonstration of this. The app is basically stalling during the loading of images, and there are (obviously) a lot of images loaded by this app. (The Mango release will make this app really awesome and responsive, I can tell you :))

There are two main reasons for this, being the image loading happening on the UI Thread and partial cache persistence.

 

Hacking around image loading in NoDo

So if you look around to mitigate those two issues, you'll find a few things like the LowProfileImageLoader from a Microsoftee. This removes a lot of burden from the UI thread by not using the WebClient, and queueing requests to avoid having too many dowloads at the same time.

But like I've discussed before, this is still not the perfect solution because HttpWebRequest still goes on to the UI thread, and when there are many images loaded the UI becomes easily sluggish.

For the image cache part, Silverlight will cache BitmapImage instances based on the Url, will persist them across application runs but will ignore the HTTP/1.1 max-age directive. This means that each time you run the application, the app will try to refresh the image again. It may not be downloaded again, but it still is checked. This may delay a lot the display of the image, because of the wait for the server to check if the image has changed.

If you still want to do some sort of caching without asking the server every time, then you need to handle the storage of downloaded streams and use BitmapSource.SetSource, and perform some in-memory caching of BitmapSource instances to still use the Silverlight cache even if you can't provide an Url. And all this has to be performed on the UI thread. It really does not help.

These are many roadblocks that hurt badly the perceived performance of the application.

 

Images in Mango

If you try to the same in Mango, doing the background download and caching by yourself, you end up making the matters worse.

Mango has changed everything on that front, and the Product Team has addressed these issues in a very nice way. Loading images is now seamless, you can download as many as you want and UI will not lag a bit.

If you observe the loading of images in mango, you'll quickly see that cached images are displayed almost instantly, primarily because of the cache engine respecting server cache directives. This means that an image will not be checked for a refresh nor downloaded again if the cache duration has not expired.

All this means that you pretty much don't need to do anything to display images in Mango, unless you need to bypass server caching directives.

This is good news :)

Also, Silverlight seems to be doing some work off the UI thread the "user code" (us, mere mortals) cannot do because it needs to be on the UI thread, meaning that you have to let Silverlight do its magic to load images the fastest and seamless way possible.

 

Image caching in Mango

By looking closer to the way Mango does caching, I've noticed a few things :

  • Images seem to be downloaded once per application run, meaning that server cache directives are ignored until a restart of the application (Fast-resume does not seem to count as a restart),
  • Images that need to be refreshed are checked for modifications on the server, and if an HTTP 302 is sent back, the cached image stays.
  • ETag is supported, the If-None-Match header is sent when the max-age has been reached.
  • If-Modified-Since is also sent when the max-age time span has been reached,
  • When using BitmapCreateOptions.IgnoreImageCache
    • Server cache directives do not seem to be bypassed, the cache is not refreshed until max-age has been reached
    • If Cache-Control max-age and Expires headers are not specified the cache does not seem to be ever refreshed
    • If Expires is specified but not max-age, then the server is called to check for a newer version with If-Modified-Since

These are very good news, since most web server implementation support and respect the HTTP/1.1 Cache-Control directives, meaning that images will be displayed and refreshed properly by default.

[wp7dev] Error code 0xc00cee65 and duplicate XML namespaces

By jay at July 29, 2011 07:32 Tags: ,
There are times when you feel almost alone, particularly when you type an error code in google, and nothing comes up.
I got that interesting and particularly verbose exception when doing some XAML refactoring for a Windows Phone 7 application :

An unhandled exception of type 'System.Exception' occurred in System.Windows.dll
Additional information: 0xc00cee65

Turns out it was due to this :

 

xmlns:ucontrols2="clr-namespace:Company.Views.Controls;assembly=Company.Views.Phone"  
xmlns:ucontrols="clr-namespace:Company.Views.Controls;assembly=Company.Views.Phone"

 

Where two xml namespaces were referencing the same CLR namespaces and assembly. Merging the two namespaces fixed this issue.

 

Tough one...

When declarativeness goes away for performance

By jay at July 25, 2011 20:35 Tags: , , ,

TLDR: The creation a C# expression tree is not cached, and using it to simulate a methodof keyword is terribly slow. This article is about reconsidering the use of this technique when performance is a concern.

 

During the development of my last projects, and it's been like that for a while, I've been used to look for ways to express programs in a more declarative or functional way.

LINQ is a pretty good tool to acheive that, as well as fluent interfaces, lamdbas and all those neat language features and tricks.

 

When the language is against you

But there are some times when the language is not there to support patterns, like with the use of the IPropertyChanged interface. The language (and the CLR for that matter) does not publicly support intercepting calls to properties or methods. That can actually be done through Transparent Proxies or dynamic proxy generation, but these are not supported on Windows Phone 7. The latter somehow will on WP7.1.

Anyway, using that interface requires raising an event with a string containing the name of the property that has changed.

The use of metadata in the form of strings is unfortunately not refactoring friendly, and if you change your property name, you've got a bug on your hands.

Since there is no methodof keyword in C#, you could say that the language is against you since there is no direct way to get the name of a property or method at compile time.

This can still be done through reflection with plumbing code that uses Expression Trees to work around it, and it works pretty fine.

That way you can easily write nice wrappers like this one :

public int MyProperty 
{
    get { return GetValue(() => MyProperty); }
    set { SetValue(() => MyProperty, value); }
}

That way, you get both the type safety and the refactoring friendly use of INotifyPropertyChanged.

 

Where declarativeness does not shine

If you crack open the assembly for a property like this one with a disassembler, you get this :

public int MyProperty
{
    get
    {
        return this.GetValue<int>(
            Expression.Lambda<Func<int>>(
               Expression.Property(
                  Expression.Constant(this, typeof(MainPage)
               ),
               (MethodInfo) methodof(MainPage.get_MyProperty)
            ),
        new ParameterExpression[0]));
    }
    set
    {
        this.SetValue<int>(
           Expression.Lambda<Func<int>>(
              Expression.Property(
                 Expression.Constant(this, typeof(MainPage)),
                 (MethodInfo) methodof(MainPage.get_MyProperty)
              ),
           new ParameterExpression[0]),
        value);
    }
}

That's a lot of code !

And worse, that's not the end of it, because you'll have to traverse the expression just to get the "methodof", and then call the "Name" property to get the string. All this for a string that will never change after you've compiled your assembly.

 

When declarativeness goes away for performance

But that would not be that bad if you executed that code once, or ran it on a desktop computer (or you don't care about performance). For desktop and server applications, where the cost of executing that kind of code is (almost) neglectible, you do not care much about that.

But if you execute that code a few million times, or run it on a Windows Phone 7 on the UI thread, you've got a problem. The expression is not cached, neither in a static variable or an instance variable, depending on the context. Sure, you could store it in an expression typed variable, and cache it manually that way, but you'd lose a bit declarativeness.

To make a small comparison, it takes 13 seconds on my Samsung Focus to execute 10,000 gets of the property using expressions, and takes 0.2 milliseconds to do the same using a simple string.

Pretty easy to choose, isn't it ?

That's where you lose the declarativeness away for performance, and cringe a little bit about it when you know that you'll have to chase a bug in the future because of a lazy rename. Still, you can have debug-time only code that walks up the stack and checks that the property actually exists, but you have to execute that code to find the bug.

 

Mitigating

Hopefully, there are tools like Postsharp that help in that regard, where a post processing step does the reflection once and for all, and injects that missing string. That's direction I'd rather not take, but since there's still no out of the box solution, that can be a good fit.

 

We're so used to techniques that avoid us to write boring code, but when performance is a concern, it is necessary to reconsider all coding reflexes and think twice before using them.

[Rx] Using the ObserveOn and SubscribeOn operators

By jay at July 24, 2011 20:04 Tags: , , , , ,

TLDR: This post talks about how the Reactive Extensions ObserveOn operator changes the execution context (the thread) of the IObservable OnNext/OnComplete/OnError methods, whereas the SubscribeOn operator changes the execution context of the implementation of the Subscribe method in the chain of observers. Both methods can be useful to improve the performance of an application's UI by putting work on background threads.

 

When developing asynchronous code, or consuming asynchronous APIs, you find yourself forced to use specific methods on a specific thread.

The most prominent examples being WPF/Silverlight and Winforms, where you cannot use UI bound types outside of the UI Thread. In the context of WPF, you'll find yourself forced to use the Dispatcher.Invoke method to manipulate the UI in the proper context.

However, you don't want to execute everything on the UI Thread, because the UI performance relies on it. Doing too much on the UI thread can lead to a very bad percieved performance, and angry users...

 

Rx framework's ObserveOn operator

I've discussed a few times the use of ObserveOn in the context of WP7, where it is critical to leave the UI thread alone and avoid choppy animations, for instance.

The ObserveOn operator changes the context of execution (scheduler) of a chain of operators until an other operator changes it.

To be able to demonstrate this, let's write our own scheduler :

public class MyScheduler : IScheduler
{
    // Warning: ThreadStatic is not supported on Windows Phone 7.0 and 7.1
    // This code will not work properly on this platform.
    [ThreadStatic]
    public static int? SchedulerId;

    private int _schedulerId;
    private IScheduler _source;
        
    public MyScheduler(IScheduler source, int schedulerId)
    {
        _source = source;
        _schedulerId = schedulerId;
    }

    public DateTimeOffset Now { get { return _source.Now; } }

    public IDisposable Schedule<TState>(
              TState state, 
              Func<IScheduler, TState, IDisposable> action
           )
    {
        return _source.Schedule(state, WrapAction(action));
    }

    private Func<IScheduler, TState, IDisposable> WrapAction<TState>(
              Func<IScheduler, TState, IDisposable> action)
    {
        return (scheduler, state) => {

            // Set the TLS with the proper ID
            SchedulerId = _schedulerId;

            return action(_source, state);
        };
    }
}

This scheduler's purpose is to intercept calls to the ISchedule methods (You'll fill the missing Schedule methods by yourself) and flag them with a custom thread ID. That way, we'll know which scheduler is executing our code.

Note that this code will not work properly on Windows Phone 7, since ThreadStaticAttribute is not supported. And it's still not supported on 7.1... Seems like not enough people are using ThreadStatic to make its way to the WP7 CLR...

Anyway, now if we write the following Rx expression :

Observable.Timer(TimeSpan.FromSeconds(1), new MyScheduler(Scheduler.ThreadPool, 42))
          .Do(_ => Console.WriteLine(MyScheduler.SchedulerId))
          .First();

We force the timer to raise OnNext on the ThreadPool through our scheduler, and we'll get the following :

42

Which means that the lambda passed as a parameter to the Do operator got executed in the context of the Scheduler used when declaring the Timer operator.

If we go a bit farther :

Observable.Timer(TimeSpan.FromSeconds(1), new MyScheduler(Scheduler.ThreadPool, 42))
          .Do(_ => Console.WriteLine("Do(1): " + MyScheduler.SchedulerId))
          .ObserveOn(new MyScheduler(Scheduler.ThreadPool, 43))
          .Do(_ => Console.WriteLine("Do(2): " + MyScheduler.SchedulerId))
          .ObserveOn(new MyScheduler(Scheduler.ThreadPool, 44))
          .Do(_ => Console.WriteLine("Do(3): " + MyScheduler.SchedulerId))
          .Do(_ => Console.WriteLine("Do(4): " + MyScheduler.SchedulerId))
          .First();

We'll get the following :

Do(1): 42
Do(2): 43
Do(3): 44
Do(4): 44

Each time a scheduler was specified, the following operators OnNext delegates were executed on that scheduler.

In this case, we're using the Do operator which does not take a scheduler as a parameter. There some operators though, like Delay, that implicitly use a scheduler that changes the context.

Using this operator is particularly useful when the OnNext delegate is performing a context sensitive operation, like manipulating the UI, or when the source scheduler is the UI and the OnNext delegate is not related to the UI and can be executed on an other thread.

You'll find that operator handy with the WebClient or GeoCoordinateWatcher classes, which both execute their handlers on the UI thread. Watchout for Windows Phone 7.1 (mango) though, this may have changed a bit.

 

An Rx Expression's life cycle

Using an Rx expression is performed in a least 5 stages :

  • The construction of the expression,
  • The subscription to the expression,
  • The optional execution of the OnNext delegates passed as parameters (whether it be observers or explicit OnNext delegates),
  • The observer chain gets disposed either explicitly or implicitly,
  • The observers can optionally get collected by the GC.

The third part's execution context is covered by ObserveOn. But for the first two, this is different.

The expression is constructed like this : 

var o = Observable.Timer(TimeSpan.FromSeconds(1));

Almost nothing's been executed here, just the creation of the observers for the entire expression, in a similar way IEnumerable expressions work. Until you call the IEnumerator.MoveNext, nothing is performed. In Rx expressions, until the Subscribe method is called, nothing is happening.

Then you can subscribe to the expression :

var d = o.Subscribe(_ => Console.WriteLine(_));

At this point, the whole chain of operators get their Subscribe method called, meaning they can start sending OnNext/OnError/OnComplete messages.

 

The case of Observable.Return and SubscribeOn

Then you meet that kind of expressions :

Observable
   .Return(42L)
   // Merge both enumerables into one, whichever the order of appearance
   .Merge(
      Observable.Timer(
         TimeSpan.FromSeconds(1), 
         new MyScheduler(Scheduler.ThreadPool, 42)
      )
   )
   .Subscribe(_ => Console.WriteLine("Do(1): " + MyScheduler.SchedulerId));

Console.WriteLine("Subscribed !");

This expression will merge the two observables into one that will provide two values, one from Return and one from the timer.

And this is the output :

Do(1):
Subscribed !
Do(1): 42

The Observable.Return OnNext was executed during the call to Subscribe, and has that thread has no SchedulerId, meaning that a whole lot of code has been executed in the context of the caller of Subscribe. You can imagine that if that expression is complex, and that the caller is the UI Thread, that can become a performance issue.

This is where the SubscribeOn operator becomes handy :

Observable
   .Return(42L)
   // Merge both enumerables into one, whichever the order of appearance
   .Merge(
      Observable.Timer(
         TimeSpan.FromSeconds(1), 
         new MyScheduler(Scheduler.ThreadPool, 42)
      )
   )
   .SubscribeOn(new MyScheduler(Scheduler.ThreadPool, 43))
   .Subscribe(_ => Console.WriteLine("Do(1): " + MyScheduler.SchedulerId));

Console.WriteLine("Subscribed !");

You then get this :

Subscribed !
Do(1): 43
Do(1): 42

The first OnNext is now executed under of a different scheduler, making subscribe a whole lot faster from the caller's point of view.

 

Why not always Subscribe on an other thread ?

That might come in handy, but you may not want that as an opt-out because of this scenario :

Observable.FromEventPattern(textBox, "TextChanged")
          .SubscribeOn(new MyScheduler(Scheduler.ThreadPool, 43))
          .Subscribe(_ => { });

Console.WriteLine("Subscribed !");

You'd get an "Invalid cross-thread access." System.UnauthorizedAccessException, because yo would try to add an event handler to a UI element from a different thread. 

Interestingly though, this code does not work on WP7 but does on WPF 4.

An other scenario may be one where delaying the subscription may loose messages, so you need to make sure you're completely subscribed before raising events.

 

So there you have it :) I hope this helps you understand a bit better those two operators.

Team Build and Windows Phone 7

By jay at May 01, 2011 00:00 Tags: , , ,

Building Windows Phone 7 applications in an agile way encourages the use of Continuous Integration, and that can be done using Team System 2010.

There are a few pitfalls to avoid to get there, but this can be acheived quite easily with great results.

I won't cover the goodness of automated builds, this has already been covered a lot.

 

Adding Unit Tests

Along with the continous integration to create hopefully successful builds out of every check-in of source code, you'll also find the automated execution of unit tests. Team System has the ability to provide nice code coverage and unit tests success rates in Reporting Services reports, where statistics can be viewed, which gives good health indicators of the project.

Unfortunately for us, at this point there are no ways to automatically execute tests using the WP7 .NET runtime. But if you successfuly use an MVVM approach, your view models and non UI code can be compiled for multiple platforms, because they do not rely on the UI components that may be specific to the WP7 platform. That way, we are still able to test our code using the .NET 4.0 runtime with MSTest and Visual Studio 2010 test projects.

To avoid repeating code, multi-targeted files can be integrated into single target projects either by :

  • Using the Project Linker tool and link multiple projects,
  • Creating project files in the same folder and use the "include file" command when showing all files in the solution explorer. Make sure to change the output assembly name to something like "MyAssembly.Phone.dll" to avoid conflicts.

Multi-targeted files are using the #if directive and the WINDOWS_PHONE define, or the lack thereof, to compile code for the current runtime target.

There is also the option of creating projects with the Portable Library add-in, but there are some caveats on that side, and there are a few constraints when using this method. You may need to externalize code that is not supported, like UrlDecode.

Testing with MSTest ensures that your code runs successfully on .NET 4.0 runtime, but this does not test on the WP7 runtime. So to be sure that your code is successfully running on it, and since Windows Phone 7 is build on Silverlight 3, tools like the SL3 Unit Test framework can be used to manually run tests in the emulator. This cannot be integrated into the build for now, unfortunately; you'll have to place that in your QA tests.

 

TeamBuild with the WP7 toolkit

To be able to buid WP7 applications on your build machine, you need to install the SDK on your build machine, and a Team Build agent and/or controller.

Creating a build definition is done the same way as for any other build definition, except for one detail. You need to set the MSBuild platform to x86 instead of Auto if your build machine is running on a 64 Bits Windows. This forces the MSBuild runtime to use the 32 bits runtime, and not 64 bits, where the SDK does not work properly.

If you don't, when building your WP7 application, you'll find that intriguing message :

Could not load file or assembly 'System.Windows, Version=2.0.5.0'

Which is particularly odd considering that you've already installed the SDK, and that dll is definitely available.

You may also find that if you install that DLL from the SDK in the GAC, you'll get that other nice message :

Common Language Runtime detected an invalid program.

Which is most commonly found when mixing 32 bits and 64 bits assemblies, for which the architecture has been explicitly specified instead of "Any CPU". So don't install that DLL in the GAC and set the MSBuild architecture to x86.

 

That's it  for now, and Happy WP7 building !

[WP7] HttpWebRequest and the Flickr app "Black Screen" issue

By jay at April 22, 2011 14:54 Tags: , , , , ,

TL;DR: While trying to fix the "Black Screen" issue of the Windows Phone 7 flickr app 1.3, I found out that HttpWebRequest is internally making a synchronous call to the UI Thread, making a network call negatively impact the UI. The entire building of an asynchronous web query is performed on the UI thread, and you can't do anything about it.

Edit: This post was formerly named "About the UI Thread performance and HttpWebRequest", but was in fact about Yahoo's Flickr application and was enhanced accordingly.

When programming on Windows Phone 7, you'll hear often that to improve the perceived performance, you'll need to get off of the UI Thread (i.e. the dispatcher) to perform non UI related operations. By good perceived performance, I mean having the UI respond immediately, not stall when some background processing is done.

To acheive this, you'll need to use the common asynchrony techniques like queueing in the ThreadPool, create a new thread, or use the Begin/End pattern.

All of this is very true, and one very good example of bad UI Thread use is the processing of the body of a web request, particularly when using the WebClient where the raised events are in the context of the dispatcher. From a beginner's perspective, not having to care about changing contexts when developing a simple app that updates the UI, provides a particularly good and simple experience.

But that has the annoying effect of degrading the perceived performance of the application, because many parts of the application tend to run on the UI thread.

 

HttpWebRequest to the rescue ?

You'll find that the HttpWebRequest is a better choice in that regard. It uses the Begin/End pattern and the execution of the AsyncCallback is performed in the context of ThreadPool. This performs the execution of the code in that callback in a way that does not impact the perceived performance of the application.

Using the Reactive Extensions, this can be written like this :

var request = WebRequest.Create("http://www.google.com");

var queryBuilder = Observable.FromAsyncPattern(
                                (h, o) => request.BeginGetResponse(h, o),
                                ar => request.EndGetResponse(ar));

queryBuilder()
                /* Perform the expensive work in the context of the AsyncCall back */
                /* from the WebRequest. This will be the ThreadPool. */
                .Select(response => DoSomeExpensiveWork(response))

                /* Go back to the UI Thread to execute the OnNext method on the subscriber */
                .ObserveOnDispatcher()
                .Subscribe(result => DisplayResult(result));

That way, you'll get most of your code to execute out of the UI thread, where that does not impact the perceived performance of the application.

 

Why would it not be to the rescue then ?

Actually, it will always be (as of Windows Phone NoDo), but there's a catch. And that's a big deal, from a performance perspective.

Consider this code :

 public App()
 {
  /* some application initialization code */


  ManualResetEvent ev = new ManualResetEvent(false);

     ThreadPool.QueueUserWorkItem(
  d =>
  {
      var r = WebRequest.Create("http://www.google.com");
      r.BeginGetResponse((r2) => { }, null);

      ev.Set();
  }
     );

     ev.WaitOne();
 }

This code is basically beginning a request on the thread pool, while blocking the UI thread in the App.xaml.cs file. This makes the construction (but not the actual call on the network) of the WebRequest synchronous, and makes the application wait for the request to begin before showing any page to the user.

While this code is definitely not a best practice, there was a code path in the Flickr 1.3 application that was doing something remotely similar, in a more convoluted way. And if you try it for yourself, you'll find that the application hangs in a deadlock during the startup of the application, meaning that our event is never set.

 

What's happening ?

If you dig a bit, you'll find that the stack trace for a thread in the thread pool is the following :

  mscorlib.dll!System.PInvoke.PAL.Threading_Event_Wait() 
  mscorlib.dll!System.Threading.EventWaitHandle.WaitOne() 
  System.Windows.dll!System.Windows.Threading.Dispatcher.FastInvoke(...) 
  System.Windows.dll!System.Net.Browser.AsyncHelper.BeginOnUI(...)
  System.Windows.dll!System.Net.Browser.ClientHttpWebRequest.BeginGetResponse(...) 
  WindowsPhoneApplication2.dll!WindowsPhoneApplication2.App..ctor.AnonymousMethod__0(...)

The BeginGetResponse method is trying to execute something on the UI thread. And in our example, since the UI thread is blocked by the manual reset event, the application hangs in a deadlock between a resource in the dispatcher and our manual reset event.

This is also the case for the EndGetResponse method.

But if you dig even deeper, you'll find in the version of the System.Windows.dll assembly in the WP7 emulator (the one in the SDK is a stub for all public types), that the BeginGetResponse method is doing all the work of actually building the web query on the UI thread !

That is particularly disturbing. I'm still wondering why that network-only code would need to be executed to UI Thread.

 

What's the impact then ?

The impact is fairly simple : The more web requests you make, the less your UI will be responsive, both for processing the beginning and the end of a web request. Each call to the methods BeginGetResponse and EndGetResponse implicitly goes to the UI thread.

In the case of Remote Control applications like mine that are trying to have remote mouse control, all are affected by the same lagging behavior of the mouse. That's partially because the UI thread is particularly busy processing Manipulation events, this explains a lot about the performance issues of the web requests performed at the same time, even by using HttpWebRequest instead of WebClient. This also explains why until the user stops touching the screen, the web requests will be strongly slowed down.

 

The Flickr 1.3 "Black Screen" issue

In the Flickr application for which I've been able to work on, a lot of people were reporting a "black screen" issue, where the application stopped working after a few days.

The application was actually trying to update a resource from the application startup in an asynchronous fashion using the HttpWebRequest. Because of a race condition with an other lock in the application and UI Thread that was waiting in the app's initialization, this resulted in an infinite "Black Screen" that could only be bypassed by reinstalling the application.

Interestingly enough, at this point in the application's initialization, in the App's class constructor, the application is not killed after 10 seconds if it is not showing a page to the user. However, if the application stalls in the constructor of the first page, the application is automatically killed by the OS after something like 10 seconds.

Regarding the use of the UI Thread inside the HttpWebRequest code, applications that are network intensive to get a lot of small web resources like images, this is has a negative impact on the performance. The UI thread is constantly interrupted to process network resources query and responses.

 

Can I do something about it ?

During the analysis of the emulator version of the System.Windows.dll assembly, I noticed that the BeginGetResponse is checking whether the current context is the UI Thread, and does not push the execution on the dispacther.

This means that if you can group the calls to BeginGetResponse calls in the UI thread, you'll spend less time switching between contexts. That's not the panacea, but at the very least you can gain on this side.

 

What about future versions of Windows Phone ?

On the good news side, Scott Gu annouced at the Mix 11 that the manipulation events will be moved out the the UI thread, making the UI "buttery smooth" to take his words. This will a lot of applications benefit from this change.

Anyway, let's wait for Mango, I'm guessing that will this will change is a very positive way, and allow us to have high performance apps on the Windows Phone platform.

About me

My name is Jerome Laban, I am a Software Architect, C# MVP and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Remote Control for Windows Phone.