March 2011 - Posts

Next Thursday, 07.04.2011, I’ll be giving two sessions about “Using Windows 7 Features in .NET Applications”, in Microsoft offices, Ra’anana, Israel.
On the first session “The 7 Show: From XP to Win 7” we will talk about new features in Windows 7 that will modernize your application.
We will learn how to work with the new Taskbar, how to work with Sensors, how to use the Ribbon interface and more.
The session will be rich with examples in .NET, WPF and WinForms.
On the second session “Touch Everywhere” we will see how to use the Multi-touch feature which comes out of the box in Windows 7.
We will learn about the possible level of support (Good, Better & Best) and learn about helper libraries that provide a convenient API when working with multi-touch devices.
The session will include many examples in all the common UI technologies: C++, WinForms, WPF and Silverlight.
The entrance is free, but requires registration.
Hope to see you there!
That’s it for now,
Arik Poznanski
Note: the following article was first published as part of the Windows Phone Recipe “Ways to Load Applications Faster” found here, which I wrote for Microsoft, together with Yochay Kiriaty.
Purpose of This Document
This document introduces the loading procedure for Windows Phone Silverlight applications. It explains common mistakes that application developers make during application launch, and how those errors can increase the total application load time and harm the user experience. Next, this document describes some possible solutions for overcoming long load times and explains their implementation.
Application startup is also discussed in Performance Considerations in Applications for Windows Phone. That paper provides excellent background information and can help make your Windows Phone applications shine.
Windows Phone Application Flow: Launching, Running, and Closing
We can't talk about proper loading techniques and optimizing application startup time without explaining Windows Phone application lifetime events. The following section providers a short overview; for more detailed information, see Execution Model for Windows Phone.
Windows Phone provides developers with a series of events and APIs for handling tombstoning and other application state changes, which include launching and closing. The PhoneApplicationService class, found in the Microsoft.Phone.Shell namespace, provides access to various aspects of the application’s lifetime, including management of the application’s state when it becomes active or inactive.
The PhoneApplicationService class exposes four main lifetime events. For any auto- generated Windows Phone application (generated by Visual Studio 2010 Express for Windows Phone or Visual Studio 2010), the App.xaml.cs file includes four methods directly related to the execution model. These methods are your application handlers for the lifetime events exposed by the PhoneApplicationService class:
- Application_Launching
- Application_Activated
- Application_Deactivated
- Application_Closing
The names of these methods are self-explanatory. However, there are some subtleties that we need to cover:
- Application Launching – A Windows Phone application is considered to be launched when it’s started by a means other than by the user pressing the Back button to return to a previous application. An application is launched when the user taps the entry for the application in the phone’s applications list or the tile for the application on Start. An application can also be launched when the user taps a toast notification.
- Application Deactivated occurs when a different application takes control of the foreground; for example, when the user launches a chooser or presses the Start button. In both cases, your application will be deactivated; the Deactivated event is raised, as opposed to the Closing event when your application exits. However, unlike an application that’s closed, a deactivated application will most likely get tombstoned. Don’t become confused: A tombstoned application’s underlying process still gets terminated, so your application does “close.” But unlike a closed application (which has exited), where the Windows Phone operating system removes any trace of the application from memory, in the deactivated scenario the Windows Phone operating system stores a record (a tombstone) of the application's state. Basically, the Windows Phone operating system keeps a tombstone of the application that becomes part of the phone’s application back-stack, which is a journal that enables the use of the Back button to enhance navigation functionality.
- Application Activated – After an application has been deactivated, it’s possible that it will never be reactivated. However, it’s also possible that the user will return to the application by pressing the Back button enough times to reach the application. When the user returns to a deactivated application, it’s reactivated and the Activated event is raised. Windows Phone then navigates to the last page viewed by the user in order to give the user the feeling that the application is simply continuing. Note that unlike Launching, some data objects in an Activated application might still be initialized.
- Application Closing is simply the outcome of the user pressing the Back button enough times to navigate backwards through the pages of your application, and past the application’s first page. Currently, this is the only way for a user to exit your application. Once your application is closed, its process is terminated, the operating system removes any trace of that application from its memory, and there’s no way to return to the application other than by launching a new instance.
Note that Launching and Activated events are mutually exclusive, as are the Deactivated and Closing events.
These events play a critical role in your application’s loading and closing times. Loading time also applies during application tombstoning and, more importantly, for applications resuming from tombstone.
One last note before we continue. There’s a certain sequence of methods that gets called during launching and tombstoning. This method sequence is critical for optimizing load time operations.
For the most part, when your application is launching or returning from tombstone, the following methods are being executed in the following order:
- Application constructor –App() found in App.xaml.cs
- Application launching – Application_Launching found in App.xaml.cs
- Your application’s “first page” constructor
- Your application’s “first page” OnNavigatedTo method
Note: When returning from tombstone, the “first page” is the last page the application was showing, and not necessarily the actual first page of the application.
Note: When your application returns from a tombstone state, this entire sequence is executed. However, in cases where tombstoning is relaxed, and your application is deactivated but not tombstoned, the Application constructor and the Page constructor aren’t executed. For additional information about Application Lifetime events and tombstoning, see Execution Model for Windows Phone.
Application launch time is defined from the time Windows Phone loads your application into memory and starts executing the application constructor (the first method in the sequence) until the end of the execution of the OnNavigatedTo method first page.
Startup and Shutdown Times
Windows Phone enforces a series of time limits on application startup and shutdown in order to preserve a consistent and responsive user experience across the phone’s built-in applications and 3rd-party applications. If your application exceeds the allowed time for startup or shutdown, it will be forcibly terminated and removed from the back-stack. This means your application doesn’t get tombstoned, it’s simply terminated, and the user can’t use the back button to reactivate it. The following table outlines launch shutdown, deactivated, and reactivated times:
Table 1-1. Application Startup / Shutdown times
| Application Event | Limit |
| Starting the application (application Launching event) | 10 sec |
| Forward navigating away from the application (application Deactivated event) | 10 sec |
| Returning to the application using the Back key (application Activated event) | 10 sec |
| Exiting from the application (application Closing event) | 10 sec |
You can see that you have up to 10 seconds of real-world time (this doesn’t mean that you have 100% of the CPU for 10 seconds) to handle each application lifetime event. If for some reason your code takes longer than 10 seconds to execute, the Windows Phone system will terminate your application.
Note: Besides the operating system safeguards, part of the Marketplace ingestion process is to check the time it takes to launch and to return from tombstoning. The user experience guidelines are even stricter, and require less than 10 seconds to properly launch your application. According to Windows Phone 7 Application Certification Requirements, the application must render the first screen within five seconds after launch, even when there’s a splash image. Therefore, optimizing and understanding the load sequence are critical to your application’s success.
- Startup time – Includes launching or returning to a tombstoned application. It’s the time from when your application process starts executing until your application becomes active or visible. Your application becomes visible only after the execution of the OnNavigatedTo method ends of the page the application navigates to upon launch or returning from tombstoning. Until then, the application’s splash screen is displayed and the application isn’t considered active.
- Shutdown time – Includes deactivating and exiting from the application, and mostly consists of the time from when the forward navigation was invoked until the Deactivated or Closing methods execution ends.
Demonstrating the Problem
As explained in the previous section, the application must complete its loading and display its first page (or any page when returning from tombstoning) within 10 seconds or the OS will kill the process. Moreover, even if your application launches in five or eight seconds, you still need to optimize the user experience by loading the application and displaying something as soon as possible; otherwise, the impatient user might tap the Back or Windows button to navigate away from your application.
So let's see how easy it is to create a well-behaved application. In the following demo we’ll create a Windows Phone Silverlight application that needs to execute some long operations while loading.
Note: Our example application describes a very simple scenario for a Silverlight application that displays some information on the first page. This information should be obtained from some web service or local storage. To illustrate the problem, we create a fake workload that intentionally takes about 10 seconds to complete.
To simulate a long operation, we’ll simply trigger a function that sleeps for a second and reiterate that 10 times. (See the MyService.Init methods below.)
To experience this firsthand, simply follow these steps:
Step 1: Create a Windows Phone Application
Step 2: Create long workloads
public class MyService
{
private const int NumberOfIterations = 10;
public static void Init()
{
for (int i = 0; i < NumberOfIterations; ++i)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
public static void Init(Dispatcher dispatcher)
{
for (int i = 0; i < NumberOfIterations; ++i)
{
if (dispatcher != null)
{
dispatcher.BeginInvoke(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
});
}
}
}
}
Essentially, both methods perform the same operation: they sleep for about 10 seconds to mimic a long workload. The second Init method accepts a Dispatcher as an input parameter that we use each in sleep period. This forces a sync with the main user interface (UI) page (since that’s the dispatcher we’re passing in), as it isn’t reasonable to write code that completely blocks the UI thread for 10 seconds. Eventually, calling the dispatcher allows Windows Phone to terminate faster, as you’ll see later.
Step 3: Call the long workloads from various locations in your application
Call the function MyService.Init from either one or all five methods:
1. App constructor
public partial class App : Application
{
public App()
{
...
MyService.Init();
}
...
}
2. Application Launching event
This event is raised when the user launches the application by tapping on the application’s icon.
public partial class App : Application
{
...
private void Application_Launching(object sender, LaunchingEventArgs e)
{
MyService.Init();
}
}
3. Application Activated event
This event is raised when the user taps the Back key to return to the application, or after returning from a chooser or a launcher.
public partial class App : Application
{
...
private void Application_Activated(object sender, ActivatedEventArgs e)
{
MyService.Init();
}
}
4. Page constructor
This function is called when the Page class is created.
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
MyService.Init(this.Dispatcher); //Or you can run MyService.Init();
}
...
}
5. Page OnNavigatedTo method
This function is called when the page is navigated to, either from another page or when the application gets launched/activated.
Note: The problem shown in this demo also can occur when your application comes back from a tombstone state, so you need to make sure you don't have lots of work in the constructor and OnNavigatedTo functions of any of your pages in the application.
public partial class MainPage : PhoneApplicationPage
{
...
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MyService.Init(this.Dispatcher); //Or you can run MyService.Init();
}
}
Step 4: Run your application
Simply run your application from your phone and observe that the operating system terminates your application. When it terminates your application depends on specific implementation criteria, as explained below.
Note: To test whether the Windows Phone terminates your application when your application’s load time exceeds the 10-second limit, you must run your application on a real device without attaching the debugger. You need to deploy the application to the phone and then run it. Don’t run the application from Visual Studio, as when the debugger is attached (either to your Windows Phone device or to Windows Phone emulator); the relevant watchdog timers are disabled and the application will simply load after all the fake workload methods complete their task.
If you use the Init without the dispatcher, then the sleep (on the main UI thread) prevents any operations from executing on the main thread (which is the main application thread). This is rather extreme and doesn’t represent a real-life scenario. So we’ve added a call to the dispatcher during each sleep period in order to sync back to the UI thread, and give the Silverlight runtime a chance to do what it’s supposed to do (terminate your application). Therefore, you’ll notice that when calling the MyService.Init method without the parameter, the application will eventually get terminated, but only after all the sleep periods occur (depending on how many times you called the MyService.Init method). When you pass the dispatcher as an input param (this is only possible in the MainPage), you’ll notice that your application terminates faster.
Try removing the MyService.Init method from the Application constructor and Launching method, but leave them in the MainPage constructor and OnNavigatedTo methods. You’ll see that it still takes about 11 or 12 seconds for the operating system to terminate your application. This again proves that it takes only one misbehaving method to significantly impair your application’s load time.
The Solution – Optimizing Your Application Load Time
Now that you understand the Windows Phone Silverlight application launch sequence and the problem of long launch times, it’s time to present some ways to optimize your application load times.
The solution is composed of four action items:
- Use a splash image
- Defer work
- Do work on a background Thread
- Use a loading page
Action Item 1: Use a Splash Image
The first thing you can do is to help to solve the user experience issue. If the user sees an image of the application that says "Loading…", he’ll wait a few more seconds before pressing the Back key out of frustration. Therefore, be smart and use a splash screen.
In fact, all Windows Phone project templates include a splash screen image. By default, this image is named SplashScreenImage.jpg, and it automatically appears when your application is starting. The default image looks like this:

Make sure to change the default image to something that suits the theme of your application. That way, when users see the splash screen (which happens instantly), they’ll recognize it as part of your application. Changing the default splash screen is also a Marketplace requirement.
Note: The image must have:
- A size of 480 by 800 pixels
- The filename set to SplashScreenImage.jpg
- The Build Action set to Content
Action Item 2: Defer Work
This against everything your parents taught you, but when it comes to loading an application on Windows Phone, never do now what you can do later.
Postponing non-mission-critical work until after the application loads is always a good technique. At that point you aren’t constrained by time issues, and you might have time to run workload between user actions.
For example, suppose you write a Sudoku game for Windows Phone. You might be tempted to generate the Sudoku game map when the application loads. However, it would be best to delay this action until the application is loaded and the user selects "New game." At this point you can show some nice animation during the game setup process.
You should defer any workload that isn’t critical to the application launch and doesn’t have a severe impact on the user experience when the application loads. Always prefer lazy initialization of objects, which promotes deferring non-essential workloads.
Unfortunately, not every workload in your application launch sequence can be postponed. There are certain scenarios in which you can’t defer the workload to a later time in the application or until the user performs some operation. Some scenarios require you to run a workload as close as possible to the application start time. For example, consider an application that shows the top 10 trends currently on Twitter. Without the trends information, there’s nothing real to show on the application’s main page. However, we can't afford for the application to be terminated just because it’s getting the latest trends over the network.
To address scenarios in which your application has to complete some work close to startup time, you need to run some or all of the workloads in the background. This is exactly what we explain in the next section.
Action Item 3: Do Work on a Background Thread
This is probably the most important step in optimizing your application load time. To keep your application from hanging or terminating, the launch methods sequence must complete as soon as possible. If you can't defer a certain workload, you have to run that work in the background, that is, on a background thread.
You can use the following options:
1. Manually create a thread
using System.Threading;
Thread thread = new Thread(() => { MyService.Init(); });
thread.Start();
For additional information about manually creating threads, see the Thread Class documentation.
2. Queue work item into the thread pool
using System.Threading;
ThreadPool.QueueUserWorkItem((o) => { MyService.Init(); });
For additional information about using the thread pool, see the ThreadPool Class documentation.
3. Use BackgroundWorker class
By using the BackgroundWorker class, you can assign a delegate that will perform the workload, as well as a callback method that will be executed once the delegate completes its operation.
To use the BackgroundWorker class, you’ll need to add a using statement for System.ComponentModel.
using System.ComponentModel;
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork +=
(s,e) =>
{
// runs on background thread
MyService.Init();
};
backgroundWorker.RunWorkerCompleted +=
(s, e) =>
{
// runs on UI thread
};
backgroundWorker.RunWorkerAsync();
For additional information about using the BackgroundWorker class, see the BackGroundWorker Class documentation
When working with a background thread, you can’t directly update any UI control without marshaling to the UI thread from your back-thread. Silverlight offers a simple mechanism to do that by using the Dispatcher.BegineInvoke method.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//This happens on UI thread, if you want to marshal info back to UI thread from any other background thread.
});
Note: When working with background threads, you should always remember that UI components in Silverlight have thread affinity; that is, you can access a control only from the thread that created the control. So if you need to update the UI with progress/completed reports from the background thread, you should dispatch your code to run on the correct thread. This can be done by using the method myControl.Dispatcher.BeginInvoke(), where myControl is the control you want to update.
Action Item 4: Use a Loading Page
Now that you’ve moved some of the workload to the background, your application will load much faster and you should see your application’s first page rather quickly. However, most likely you’ve got nothing meaningful (such as the new data you’re fetching) to show, since the background thread is still executing. Therefore, If you started some work on a background thread , you should consider showing a busy/loading indicator, like a progress bar, during the wait time.
You should avoid having a separate page for the loading indicator UI, since it would become part of the application’s page back stack. This would create a strange scenario in which pressing the Back button from the main page would return the user to the loading page rather than exiting the app.
Instead, in your main page, add a grid that contains two controls: the “loading control” that will show loading information (indicator), and the actual main page content. Toggle the Visibility property of the two controls according to the current loading state. Also, if you set the ProgressBar’s IsIndeterminate property to true , turn it off once you no longer need the loading screen, or you’ll have performance issues. You can read more about this at A ProgressBar With Text For Windows Phone 7.
For example, the following XAML shows how a main page could be structured:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid x:Name="loadingContent">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="0,-30,0,0"
Text="Loading..."
/>
<ProgressBar
x:Name="progressBar"
Minimum="0"
Maximum="100"
/>
</Grid>
<Grid x:Name="mainPageContent" Visibility="Collapsed">
<TextBlock
VerticalAlignment="Center"
HorizontalAlignment="Center"
FontSize="56"
Text="Main page data"
/>
</Grid>
</Grid>
The following code shows how to use the BackgroundWorker class to do the work in the background, update the progress bar, and toggle Visibility when the work’s done:
MyService.BackgroundWorker = new BackgroundWorker()
{
WorkerReportsProgress = true
};
MyService.BackgroundWorker.DoWork +=
(s, e) =>
{
MyService.Init();
};
MyService.BackgroundWorker.ProgressChanged +=
(s, e) =>
{
progressBar.Value = e.ProgressPercentage;
};
MyService.BackgroundWorker.RunWorkerCompleted +=
(s, e) =>
{
loadingContent.Visibility = Visibility.Collapsed;
mainPageContent.Visibility = Visibility.Visible;
};
MyService.BackgroundWorker.RunWorkerAsync();
In order to receive progress updates from the background thread, we passed the BackgroundWorker to MyService class, and use the ReportProgress method:
public class MyService
{
private const int NumberOfIterations = 10;
public static BackgroundWorker BackgroundWorker { get; set; }
public static void Init()
{
for (int i = 0; i < NumberOfIterations; ++i)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
if (BackgroundWorker != null)
{
BackgroundWorker.ReportProgress((i+1) * 100 / NumberOfIterations);
}
}
}
...
}
Another way to toggle between the controls is to bind the Visibility property of both the mainContent and loadingContent to a Boolean flag that signifies the loading state (for example, bool isLoading). To do that, you’ll need a class that implements IValueConverter to convert from bool to Visibility.
Summary
Windows Phone applications must load fast and provide a good user experience. This is enforced by the application certification process and by the operating system. While the sample provided in this article is rather simple, the concepts remain true for all Windows Phone applications, and the techniques explained here will work for any Windows Phone application.
Another important consideration is the actual versus the perceived user experience. There’s more than one way to show loading progress, other than a progress bar, but it’s important to show something that’s meaningful and tells the user,“Hey, soon you’ll see your favorite app.”
That’s it for now,
Arik Poznanski.
Yesterday I’ve delivered my lecture titled “3-Screens Development using WPF, SL and WP7” in the SDP 2011 conference.

In this lecture I’ve presented the application FlashCards.Show which has 3 clients in WPF, Silverlight and Windows Phone 7.
I showed how to share the code base between the different clients using:
- MVVM
- Adding files as links
- Preprocessor symbols
- OOP
- Portable Library tools
Then I showed a few features that exist in WPF and don’t exist in Silverlight, and how one can overcome this gap.
Specifically I showed how to:
- Implement Commands in Silverlight 3
- Implement ClipToBounds property
- Implement a DataTemplateSelector replacement
I want to thank all the people who came to my lecture today.
I really enjoyed it and I hope you too.
You can download the PowerPoint presentation and the demos here.
In addition you can find more references on porting from WPF to Silverlight in the following posts:
Porting from WPF to Silverlight- The Missing Pieces, Part 1
Porting from WPF to Silverlight- The Missing Pieces, Part 2
I will post again when my lecture will be available to view on Sela College Channel.
That’s it for now,
Arik Poznanski.
Following is another post by Yochay Kiriaty on a project I’ve done for Microsoft involving WPF, Silverlight, Windows Phone 7 and Windows Azure.
If you’re interested in more details, make sure you come to my presentation at the coming SDP 2011 conference (in two days!).
[Cross-posted from http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/03/03/flashcards-show-planning-a-cross-platform-solution.aspx]
I recently blogged about Flashcards.Show Version 2 for WPF, Silverlight, and Windows Phone, which features the Flashcards.Show application. I’m not going to (again) review the app, but I do want to talk about how we developed the application and the design the code base to support multiple clients.
The first version of Flashcards.Show was a Windows (WPF) application. This app was originally designed by IdentityMine, and used a few Windows 7 features such as multi-touch and taskbar integration. While the first version was great, we wanted to increase its value by enabling users to share the decks that they are creating. Therefore, when we set to work on version 2, we sought both functional and technological solutions to enable ease of use for the deck-sharing scenarios, as well as ease of development and maintenance of the code.
Ease of use for a deck-sharing scenario is achieved by enabling users to simply click one button to start the sharing process, and another to send the deck. Behind the scenes, the application communicates with Windows Azure Flashcards services and uploads the deck. To keep it simple, we chose to use the default email client application as the means for sending the email. The pre-populated email that is generated includes a link to a Silverlight player that lets the email recipients view and interact with the attached deck. If you want to experience it first hand, you can try by clicking this link. The email also includes information on how to download the deck to your Windows Phone application and how to install (using ClickOnce) the WPF application.

Sharing Code between WPF, Silverlight and Windows Phone
After we designed deck sharing, our next step was to build the Silverlight viewer. We knew that we were going to target Windows Phone as the next platform, and therefore our first decision was to make sure the runtimes are compatible. This drove the decision to build the viewer as a Silverlight 3 rather than Silverlight 4 application. While this decision costs us a few days of hard work to implement SL4 features in SL3 code, it paid off during the Windows Phone development phase.
The second decision was to share as much code base as possible, which we did. The Flashcards.Show source code includes a solution file that includes all the “client” (WPF, Silverlight, and Windows Phone) projects. If you’re interested, you can find another solution file that includes all Flashcards.Show projects, including Windows Azure in the WindowsAzureService folder (once you extract the zip file). . For now, we’ll focus on the client projects:
- FlashCards.ViewModel.WPF – Contains the View-Model piece of the MVVM architecture that is used in the Windows application
- FlashCards.ViewModel.SL – Contains the View-Model piece of the MVVM architecture that is used in the Silverlight application
- FlashCards.ViewModel.Phone – Contains the View-Model piece of the MVVM architecture that is used in the Windows Phone application
- FlashCards.UI.WPF – Contains the main Windows application, including both modes, Admin and Game
- FlashCards.UI.SL – Contains the Silverlight application, including the different pages and resources
- FlashCards.UI.Phone – Contains the Windows Phone application, including the different pages and resources
Looking at the above list, you might be asking yourself if there are duplications between the different ViewModel projects and the UI projects. To start with, we have to compile for the target framework. The assembly that is used for WPF ViewModel .NET 3.5 is not supported by Silverlight or Windows Phone. In addition to the Silverlight assembly, Silverlight 3 also is not fully supported by Windows Phone. Therefore you have no other option but to compile to the required target CLR.
But there is more to it than this, especially in regard to the ViewModel project. Since all clients basically share the same data model, they all have the same application logic, display the same games, and follow the same game rules. Therefore both the Silverlight and Windows Phone view-model projects include links to most of the FlashCards.ViewModel.WPF view-model project. The WPF view-model contains the data model for the deck of cards (cardDeck.cs), which is comprised of individual cards (cardPair.cs), which again are comprised of two sides of a card (card.cs). The model includes metadata (MetaData) information about the types of items (text, image, sound, video, URL) placed on each card. The games logic is also part of the view-model as you can see in the LearningGameViewModel.cs and the MatchingGameViewModel.cs. Feel free to further explore the code.
If you review the Flashcards.ViewModel.SL and Flashcards.ViewModel.Phone projects, you’ll see that they are virtually identical, and the code files in each of these projects simply contain links to the original WPF view-model files.
However, a more careful review of the Flashcards.ViewModel.SL reveals some differences. For example, the Silverlight view-model doesn’t have the Taskbar.cs file, since it doesn’t integrate with the Windows 7 taskbar as the WPF application does. The Silverlight version also doesn’t include the DeckPackaging.cs file, since we don’t allow the Silverlight viewer to edit and upload decks to the Windows Azure service.
We omit files and classes of features that are not functional in the Silverlight and Windows Phone solutions. You might want to note that the Flashcards.ViewModel.Phone is identical to the Silverlight view-model.
But there are additional changes that reflect the differences between the different platforms. In the view-model projects, you can find them in the MainViewModel.cs file. The WPF and Silverlight versions of this file are quite different from each other. The Windows Phone code is embedded into the Silverlight project and we use WINDOWS_PHONE and SILVERLIGHT conditional compile time symbols to distinguish between the two. Reviewing the MainViewModel.cs file, you’ll notice compile time conditional statements such as: #if WINDOWS_PHONE
The reason we decided to use compile time symbols instead of creating a complete new copy of the MainViewModel.cs file in the phone project is due to the simple fact that while there are differences between the two, they are small and relatively easily encapsulated.
For example, the Windows Phone application can save decks in local store, a feature we are not using in Silverlight (although possible). This introduces a completely new set of features, like getting a deck from isolated storage over the network, which can be encapsulated for the Windows Phone implementation, and abstracted from the main view-model logic. We simply make sure the main view-model receives the required information for its internal data model, and when the code compiles and runs on Windows Phone, we make sure we wrap the additional functionality in such a way that it is transparent to the main view-model logic.
For example, the StartLoading function is implemented for Silverlight and Windows Phone. While the code is similar in nature, In the Windows Phone implementation you’ll notice that we need to jump through extra hoops. For example, in the webClient_OpenReadCompleted method (called…), we don’t just return a stream back to the view-model, we also write the deck to the isolated storage. During the write time, we show a progress report, because such operations on a Windows Phone can take some time.
Another example is the private _instance_PropertyChanged method that is used in Windows Phone to control the navigation between the application pages, where in the Silverlight version we simply swap in and out user controls instead of complete pages.
Lesson Learned
- Make your data model technology-agnostic as possible
- In your view-model, separate the way you handle data (the model) and the flow (screen, pages, etc.) of the application (the view) within your application logic. This will make it easier to introduce different behaviors and code for different platforms, just as we did for Windows Phone and SL
Sharing UI (XAML) Is Difficult
This brings us to the next topic of sharing UI and XAML. While sharing the View-Model is relatively straightforward, sharing the UI, is a completely different story.
To start with, there is no #if def support for XAML. Therefore, you can’t use compile time symbols to control which XAML code end up in which project. Next, the namespaces are different. WPF uses a System.Windows.Window, whereas Silverlight uses System.Windows.Controls.UserControl. But even if you successfully overcome the namespace problem, there is a bunch of functionality in WPF4 that is not in Silverlight 3 (remember we chose SL3 for ease of migration to Windows Phone). Therefore, we end up rewriting most of the Silverlight application. With that said, you can still leverage all of your .NET and WPF skills as you write the Silverlight XAML, using data binding, date templates, and such. However, I really hope Shawn’s work on 3-Screen Coding Is Here: Portable Library Tools allow you to target multiple .NET platforms with one binary will help reduce such friction in the near future.
While converting the WPF solutions to support Silverlight 3 was a pain, we deliberately targeted Silverlight 3 and not Silverlight 4 because Windows Phone Silverlight runtime is version 3. The reason is simple; we wanted the easiest possible port from Silverlight to Windows Phone. And the outcome was just that, a super easy port from Silverlight to Windows Phone. It took about 3 days to make the Silverlight application run on Windows Phone.
If you look at the FlashCards.UI.Phone project, you’ll find that most of the files are links to the Silverlight UI project. The differences are visible when we check the displaying screens. In Windows Phone Silverlight application there is only one way to display data – inside a Windows Phone Page. Therefore the Windows Phone and Silverlight solutions differ in that way. But even here, the Silverlight and Windows Phone versions are very similar.
For example, the Windows Phone LearningPage.xaml includes a LearningGame user control (LearningGame.xaml). If you look at the Silverlight LearningGame.XAML, you’ll find the same user control. While we had to copy the XAML file and make some changes to fit the smaller screen, the core of the control, its behavior, and the code behind are very (very) similar. Therefore, even if we did end up copying XAML files, the core functionality remains the same.
Lessons Learned
- Unfortunately, we can’t really share XAML code
- Some controls can be reused
Bottom Line
Obviously, there is no single silver bullet solution to sharing code across multiple platforms. With that said, while working on this project, we learned that there is a lot of room to navigate the platform’s limitations.
- Using MVVM in your WPF/SL solution makes it easier to share the model. Your application data models, logic and any request to the server side backend can and should be shared.
- As for your UI, well, that really depends on the complexity of your design, and how closely you want your implementation to be dependent upon the platform form factor, like the phone’s small screen. However, even here there is some flexibility.
You are more than welcome to download the project source code, which includes some documentation. And please watch a short video on C9 demoing the 3 client applications. As usual, your feedback is most welcome.
I want to thank Arik Poznanski, from Sela group, who helped drive the second phase of Flashcards.show.
Follow Windows Phone announcements on Twitter at WP7DEV
Follow Yochay on Twitter
Get started with free tools, free training, and free Jump Start video course
(Post edited by Barbara Alban)
[end of cross-post]
That’s it for now,
Arik Poznanski

Since I will arrive on Monday and I’m not participating in the boot camps, I’ve decided to follow Gil Fink’s footsteps and also offer four 15 minutes consulting sessions FOR FREE! We can discuss about anything, from UI technologies like WPF, Silverlight and WinForms to C# with Interop, COM and Windows 7.
All you have to do is contact me through my Blog’s Contact Form or my mail (which can be found on the left column of my blog) with your details and what do you want to talk about. I’ll contact the first four who will send a request and will give them the details when and where we will meet.
Also, you can catch me for a beer and chat when on MIX. Contact me if you're interested.
And thank Gil for the great idea!
That’s it for now,
Arik Poznanski.
Following is a great post by Yochay Kiriaty on a project I’ve done involving WPF, Silverlight, Windows Phone 7 and Windows Azure.
If you’re interested in more details, make sure you come to my presentation at the coming SDP 2011 conference.
[Cross-posted from http://windowsteamblog.com/windows/b/developers/archive/2011/02/17/flashcards-show-version-2-for-the-desktop-browser-and-windows-phone.aspx]

The Flashcards.show application has been around for few months now. It is mostly used as a developer’s reference and demo for showing specific and cool Windows 7 features. While the first version of the Flashcards let you create all kinds of decks and then consume these cards in the form of games, you could not share any of the great cards you created with anyone else except by sending the deck file itself via email..

Figure 1: Flashcards.Show in “Game” mode
With that in mind, we started working on Flashcards.Show version 2. Our goal was to enable seamless and easy sharing of decks among users across different computers. The idea was simple, upload the deck to the cloud, and let the user send a message to whomever the user wants to share the deck with. That message will include a link for the receiving party to click on to launch a web browser and run a Silverlight application that can “play” the shared deck. The Silverlight application dynamically downloads the shared deck and displays that single deck just as it would be displayed on the WPF application. At this point the user can launch any of the 3 games: Learning, Matching, or Memory, with the same user experience as the WPF application.

Figure 2: Flashcards.Show memory game running in IE as Silverlight application
Note: The shared decks have a few limitations. The deck size can’t exceed 5MB and we don’t allow video or audio. All restrictions are functional and not technical. We didn’t want to get into too deep of a development cycle.
So far so good, we have a WPF application that can share decks through the cloud and a Silverlight application that can play these decks. The next logical step was to try and run the Silverlight application on Windows Phone. Since one of Windows Phone development models is Silverlight, there is a good chance the app will run. So we tried. As you can see it works!

Figure 3: Flashcards.Show running on the Windows Phone emulator
The Flashcards.Show application runs on Windows Phone as a Silverlight application and can display the same deck that the WPF application shared with the web Silverlight. The same content and the same games can be played on Windows, on the web running Silverlight, and on Windows Phone.
If you want to download the application, feel free to use the Flashcards.Show ClickOnce install. If you want access to the code, please visit Flashcards on MSDN Code Gallery.
So there you have it – a single application that run on three different platforms backed by Windows Azure as the supporting cloud service. The nice thing about the entire Flashcards.Show implementation is our ability (by design) to share a lot of code and resources between WPF, Silverlight, and Windows Phone.

Figure 4: Flashcards.Show high level architecture
How does it work?
The Flashcards.Show application is built from two main components:
- The suite of client applications – WPF for Windows, Silverlight for web, and Windows Phone
- The cloud piece, a series of web services running on Windows Azure backed by Azure storage.
In this series of posts, we will NOT explain the cloud part, but will focus on the Silverlight and Windows Phone implementations.
When you download the Flashcard.Show version 2 source code, you will find a single Visual Studio solution file (FlashCardsSolution) that contains 10 different projects:
- FlashCards.UI.Phone – Contains the Windows Phone application, including the different pages and resources
- FlashCards.UI.SL – Contains the Silverlight application, including the different pages and resources
- FlashCards.UI.WPF – Contains the main Windows application, including both modes, Admin and Game
- FlashCards.ViewModel.Phone – Contains the View-Model piece of the MVVM architecture that is used in the Windows Phone application
- FlashCards.ViewModel.SL – Contains the View-Model piece of the MVVM architecture that is used in the Silverlight application
- FlashCards.ViewModel.WPF – Contains the View-Model piece of the MVVM architecture that is used in the Windows application
- FlashCardsServices – Contains the Windows Azure project that references the services that are deployed with it
- FlashCardsServices.Contracts – Contains the definition of the services use by the various Flashcards.Show applications
- FlashCardsServices.Entities – Contains the model of the supporting web services
- FlashWCFWebRole – Contains the web services that the different Flashcards.Show applications use
Looking at the above list, you might be asking yourself, what are the duplications between the different ViewModel projects and the UI projects?
To start with, we have to compile for the target platform (Windows, Silverlight, and Windows Phone), you have no other option but to compile to the required target CLR. For a little bit of background, please watch Shawn Burke’s “3-Screen Coding: Sharing code between Windows Phone, Silverlight, and .NET”. This sample, doesnt use the library Shawn is referring to in his talk, but it would sure make our life easier.
However, that doesn’t mean we just have to duplicate code. This is especially true in regards to the ViewModel (part of MVVM) piece of the application. Since all clients basically share the same model, they all have the same logic and display the same games and screen flow. Therefore, as you can see from the figure on the left, the WPF view-model (FlashSards.ViewModel.WPF) is the main view model we are using, and the phone’s view-model (FlashSards.ViewModel.Phone) and Silverlight view-model (FlashSards.ViewModel.SL) simply link to the relevant view model files. As you can see from the image, little arrows indicate that the relevant files are linked (click on the image to the left to see a larger version of it). This shows that we are maintaining a single view-model for all clients.

The UI is a little bit trickier. The difference between Silverlight 3 and WPF 4 runtimes are such that in our case, it is easier to simply rewrite the Silverlight application (remember, we choose to target SL3 to make the porting to Windows Phone easier). The FlashCards.UI.SL is a Silverlight project that mimics a lot of the WPF functionality, but with Silverlight capabilities.
You can still leverage all of your .NET and WPF skills as you write the Silverlight XAML and use data binding. We deliberately targeted Silverlight 3 and not Silverlight 4 because Windows Phone Silverlight runtime is version 3. The reason is simple; we wanted the easiest possible port from Silverlight to Windows Phone. And the outcome was just that, a super easy port from Silverlight to Windows Phone. It took about 3 days to make the Silverlight application run on Windows Phone.
As you can see from the figure to the left, most of the Windows Phone UI project- FlashCards.UI.Phone files are links (including the folders that are collapsed in image #6.). The links point to the Silverlight web application implementation FlashCards.UI.SL.
The files that could not be linked are those under Views. These files include XAML that is directly related to the way we display the specific pages on the phone. The phone’s form-factor is much smaller, and therefore we can fit fewer objects into it. With that in mind the implementation of the XAML was similar but not identical.

Unlike regular C# code, XAML doesn’t support of #ifdef, therefore we had to write new XAML for all the views in the game. But even then we could copy large parts of the already existing XAML.
At this stage I am not going to jump into the details of the implementation, mainly because there are a lot of them. You are more than welcome to download the source code, which includes documentation. You can also watch a short video on C9.
I want to thank Arik Poznanski who helped drive the second phase of Flashcards.show.
Follow Windows Phone announcements on Twitter at WP7DEV
Follow Yochay on Twitter
Get started with free tools, free training, and free Jump Start video course
(Post edited by Barbara Alban)
[end of cross-post]
That’s it for now,
Arik Poznanski