HTTP and images in Windows Phone

I continue to explore different techniques of displaying images in Windows Phone and this time I will show some possible implementations of fetching them from the web using the HTTP protocol.

Classic implementation:

urlImage is a string representation of the url of the image : example :

This method uses the WebRequest class and reads the response as a Stream using request.EndGetResponse.


call is very important as it allows us to use the BitmapImage on the main UI thread even when the callback is invoked on a background thread.

The method will invoke the action and pass the retrieved image to this action as parameter.

It can be invoked like this in order to set a property of type BitmapImage:

Implementation with async/await:

The “Microsoft Async” allows to use the async/await pattern in the standard Windows Phone methods.


This package adds some extension methods to the standard WebRequest class returning Task<BitmapImage>


Replaces the following elements:

The function returns directly a Task<BitmapImage> instead of passing an action as parameter

Remark :


Here we still need to marshal the call on the main Thread to allow using the returned BitmapImage and bind it on the UI.

The async/await pattern illustrated here allows better management of the threads as it relies on the TPL. Vous pouvez la remplacer sans soucis par l’ancien code.

Here’s how you could call the function: (Image is a property of type BitmapImage)


The “Microsoft HTTP Client Libraries” NuGet needs to be installed in order to be able to use the HttpClient class. The advantage of this class is that it allows to use the same syntax as we would in a Windows 8 application.


Important remark: it’s necessary to use a buffer instead of a Stream because

  • BitmapImage needs to be used on the main Thread
  • The Main thread cannot be used in AsyncStream


This function can be called the same way as before:

Performance tests

The 3 methods can be used but which one performs better when loading multiple images?

I have adapted the previous program from Performance tests of static images to

  • Display the 3 methods in the lists
  • Benchmark by loading 10 times the big png image (400K 1000×1000) from the previous article

I have also added the MemoryCounter from Coding4Fun to follow the memory usage.

Here are the results from a WiFi network (average from 20 passes).

  • Method 1 : HttpRequest/Response with Action callback : 6 sec
  • Method 2 : Async HttpRequest/Response : 9 sec
  • Method 3 : HttpClient : 8,5 sec


During the tests I have also inverted the order of passes to avoid influencing the results.

La consultation des listes donne un réel aperçu des 3 différentes méthodes.

C’est encore une fois la méthode “classique” avec HttpRequest qui donne le meilleur résultat.

Le système d’Action permet d’éviter l’attente de la fin du traitement du thread pour interroger le réseau et permet ainsi une meilleure parallélisassions des tâches.

Sharing of source code in Windows and Windows Phone projects

The Portable Class Library (PCL)

The portable Class library (PCL) will allow us to share a large part of the code across projects.

It is possible for a few years to share the PCL code between projects (Sliverlight and WPF, Windows Phone, Windows 8,…).
More projects are different, the more shared classes decreases.

It is important to see that this Library can be used for projects compatible with the selected options.

Note also the visual studio Express editions do not create a PCL, but instead accepts their use in a project.

This Library may use a library which would not have at least the same options selected.



Slow HTTP requests in .NET

When profiling a web application I have noticed constant delays of about 200ms on some HTTP calls it was making to an external API. Both the web application and the API were on the same network segment and thus network latency was out of the question. Besides the target API has previously been subject to jMeter load tests and proven to handle 1500req/s. What was even more peculiar in this situation was that only the POST requests were exhibiting this delay. GET requests were pretty fast as expected.


Visual Studio versions for your Windows Phone Apps?

Windows Phone 7.x, 8.0 and 8.1

3 major versions of Windows Phone exist since April: 7.x, 8 and 8.1.

The 8.1 version allows among others to create ‘classic’ Windows Phone 8.1 applications called 8.1 – Silverlight (SL) and also Universal applications that can be shared between Windows 8.1 and Windows Phone 8.1.

Having common codebase was already partially possible with the PCL (Portable Class Libraries). The compiled assembly can be used in Windows Phone 7.x, WP8 and Windows 8 project for example.

With Universals Apps the UI code can also be shared.

Visual Studio 2013 allows for creating PCL compatible with WP8, W8, WP8.1, W8.1 which can be used in classic Windows Phone applications and Windows 8.x with Universal Apps projects.

But Visual Studio 2013 is no longer compatible with WP7.x.

Windows Phone 7.x still represents 19% of Windows Phone users in April 2014 (click on the image for the full survey of adduplex).


So you need to make a choice.

If you want to create an application for Windows Phone 7.x you need to use Visual Studio 2012. The PCL will be compatible WP7 and WP8, as well as the Windows Phone 7.x application.


The diagram below shows the possibilities of each Visual Studio version.

Depending on how the PCLwas built, your code may or may not be shared between a Windows Phone 7 project and a Windows Phone 8.1 project.


Creating multilingual websites in WordPress

The purpose of this post is to show a tutorial about creating a multilingual website in WordPress using the multisite feature.

Advantages of the proposed solution :

  • Lots of flexibility for content translation and presentation of the articles in different languages
  • Different themes based on country
  • Search Engine Optimization

Step 1 : Creating multisite WordPress

Add the following line in wp-config.php.

This will activate a new option in the Dashboard: Tools -> Network Setup.

All that’s left is to follow the instructions.

Choose the default folder options in order to have urls of the following pattern

2 actions are necessary :

  • Copy/Paste some code inside wp-config.php
  • Copy/Paste some code inside .htaccess


Sample ASP.Net MVC project (updated)

I’ve updated the sample MVC project I wrote for using ASP.NET MVC 3 and the Razor view engine.

A minor change is that I no longer use the FluentValidationModelValidatorProvider but the standard one. So I decorate the view model with the necessary data annotations :


How to convert XHTML to PDF in C#


In this blog post I will illustrate how you could convert an XHTML page into PDF using the flying-saucer library. This is a Java library so we need to first step would be to convert it to a .NET assembly.

I will use the IKVM.NET Bytecode Compiler (ikvmc.exe) for this purpose. So go ahead and download both the flying-saucer library and the IKVM project. Then run the following command:


What features would you like to see in ASP.NET MVC 4?

If there was a single feature I would like to see in ASP.NET MVC 4 that would be to remove/deprecate ViewBag/ViewData. Those two constructs lead to very ugly code in the views and should be avoided. Here are few of the things I hate about them:

  • They are not strongly typed and you need to cast in your views in order to obtain the actual type
  • They are not refactor friendly because they rely on magic strings
  • They lead to brittle unit tests because of the magic strings
  • They lead to spaghetti code in the views

Here’s the diff patch I would love to see applied for the ViewDataDictionary.cs class in ASP.NET MVC 4:

Uploading multiple files with C# 13

Have you ever been in a situation where you needed to upload multiple files to a remote host and pass additional parameters in the request? Unfortunately there’s nothing in the BCL that allows us to achieve this out of the box.

We have the UploadFile method but it is restricted to a single file and doesn’t allow us to pass any additional parameters. So let’s go ahead and write such method. The important part is that this method must comply with RFC 1867 so that the remote web server can successfully parse the information.

First we define a model representing a single file to be uploaded:


LINQ to XML and reading large XML files

LINQ to XML makes it relatively easy to read and query XML files. For example consider the following XML file:

Suppose you would like to find all records with groupid > 2. You could be tempted to issue the following query:

There’s a flaw in this method. XElement.Load method will load the whole XML file in memory and if this file is quite big, (more…)

Dynamic methods in .NET

Using reflection to invoke methods which are not known at compile time might be problematic in performance critical applications. It is roughly 2.5-3.0 times slower than direct method calls. Here’s a sample test I’ve conducted:

Here are the results:

Method CPU units
Direct method invocation 796
Reflection method invocation 1986

So using reflection to perform a single property read is 2.5 slower than direct property access.

Dynamic methods can be used to generate and execute a method at run time, without having to declare a dynamic assembly and a dynamic type to contain the method. They are the most efficient way to generate and execute small amounts of code. (more…)

Transactional NTFS (part 1/2)

Transactional NTFS and DotNet

Starting from Windows Vista and Windows Server 2008, Microsoft introduced a great new feature called Transactional NTFS (TxF).

It allows developers to write file I/O functions that are guaranteed to either succeed completely or fail completely.
Unfortunately there are no classes in the .NET framework that would allows us to perform, such operations.
We need to resort to P/Invoke to use the newly introduced functions CreateTransaction, CommitTransaction, RollbackTransaction and DeleteFileTransacted. (more…)

How we do ASP.NET MVC

Sample MVC Solution

In this post I will show a sample ASP.NET MVC 2.0 project structure illustrating different concepts such as data access, user input validation and mapping between the domain and the view model. The project is still under construction but the source code is available at github.

I will illustrate the usage of the following frameworks:

  • MvcContrib bringing useful extension methods and strongly typed helpers to ASP.NET MVC
  • AutoMapper enabling easy mapping between the domain and the view models
  • FluentValidation – a small validation library for .NET that uses a fluent interface and lambda expressions for building validation rules for your business objects
  • NHibernate – a popular ORM in the .NET world
  • FluentNHibernate – a statically compiled alternative to NHibernate’s standard hbm xml mapping
  • Spring.NET – object container and dependency Injection framework for .NET
  • Rhino.Mocks – A dynamic mock object framework for the .Net platform. It’s purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing


Armed with this arsenal of frameworks let’s start exploring the solution structure. I’ve opted for 2 projects solution but in many real world applications more levels of abstraction could be brought to the business layer. Personally I favor to have less big assemblies rather than many small assemblies into the solution. Fewer the assemblies, faster the load time and faster the IDE. In this case particular attention should be brought to bring proper separation of concerns inside the same assembly




Playing with FindFirstFile and FindNextFile

Enumerating files in .NET is easy. Everybody knows the GetFiles method and you may be tempted to write code like this :

But if you look closer you will notice that this method returns an array of strings. This could be problematic if the directory you search contains lots of files. The method will block until it performs the search and once it finishes it will load all the results into memory. It would be much better if it just returned an IEnumerable. That’s exactly what the EnumerateFiles method does in .NET 4.0. Unfortunately in .NET 3.5 there’s nothing for the job.

In this post I will show how to implement this functionality using the FindFirstFile and FindNextFile functions. (more…)

Fun with matrix multiplication and unsafe code 1

In this post I will compare two methods that perform matrix multiplication. We start by defining the Matrix class:

Next we add the first algorithm to the Matrix class which performs a naive multiplication:

The second method uses unsafe code: (more…)