Category: Silverlight

EvenTiles from Start to Finish–Part 2

In the first part of this series about how to develop a Windows Phone application from scratch we looked at the initial project and how to initialize the Application Tile by setting elements in the manifest file. Today we will add an ApplicationBar to our application and we will add page navigation as well. We simply take off where we finished in Part 1. Adding an application bar is actually easier from within Expression Blend. This tool can be used to design and prototype Windows Phone applications. The advantages of using Expression Blend to add the application bar are:

  • immediate visual feedback;
  • simple selection / insertion of application bar icons
  • simple reordering possibilities for application bar icons en menu items.

imageVisual Studio can work closely together with Expression Blend. Changes in one environment will be visible in the other environment (usually changed files must only be saved or a project must be rebuilt in order to achieve this). If a solution is already open in Visual Studio, you can start Expression Blend from within the Project Menu as shown. Even though you can use Expression Blend to add code to your Windows Phone pages, you probably want to limit doing so, since you don’t have Intellisense available, which is one of the great features of Visual Studio that really makes entering code easy. You can immediately see that you are in a different environment when looking at Expression Blend. Its default theme color is dark. Something else that is immediately noticeable is the large amount of windows, options and choices available inside Expression Blend. It surely will take you some time to feel comfortable in this powerful design tool.

image

What you can see here is Expression Blend showing the MainPage of our EvenTiles application. You can also see how to select an ApplicationBarIcon in the collection of ApplicationBarIcon buttons. Besides concentrating on creating a (static) UI for a Windows Phone application, Expression Blend is also a fantastic tool to create different visual states and animations. We are still in the early stages of application development in this series, but more in depth usage of Expression Blend will definitely follow later on. For now we will just add a little bit of functionality to our application. Using Expression Blend, two new pages have been added to the project, a Settings Page and an About Page. Both these pages only contain a filled title section. Right now, the only functionality that will be added to the application is code to navigate to each of the two empty pages when the corresponding ApplicationBar buttons are clicked. The following code snippet shows the ApplicationBar that was created with Expression Blend in XAML, and already includes Click event handlers:

ApplicationBar on MainPage
  1. <phone:PhoneApplicationPage.ApplicationBar>
  2.     <shell:ApplicationBar Opacity="0">
  3.         <shell:ApplicationBarIconButton IconUri="/icons/appbar.feature.settings.rest.png"
  4.                                         IsEnabled="True"
  5.                                         Text="settings"
  6.                                         Click="Settings_Click" />
  7.         <shell:ApplicationBarIconButton IconUri="/icons/appbar.questionmark.rest.png"
  8.                                         IsEnabled="True"
  9.                                         Text="about"
  10.                                         Click="About_Click" />
  11.     </shell:ApplicationBar>
  12. </phone:PhoneApplicationPage.ApplicationBar>

To add code to the Click event handers, we are using the C# code behind file, belonging to the MainPage.

image

To create entries in the code behind file for both Click event handlers (and in that way connecting XAML to code), you can right click on the event handler in XAML and selecting Navigate to Event Handler entry from the shown popup menu. The code in the event handlers is very simple, using the NavigationService to navigate to another page by providing a Uri that contains the page name.

Navigating to other pages
  1. private void Settings_Click(object sender, EventArgs e)
  2. {
  3.     NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
  4. }
  5.  
  6. private void About_Click(object sender, EventArgs e)
  7. {
  8.     NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
  9. }

After deploying the application to the emulator, the Main Page shows an ApplicationBar. Clicking on either of the two ApplicationBar buttons results in navigating to another page inside the application. The following video shows all steps to create the ApplicationBar, the additional pages and the code to navigate from page to page:

Adding an ApplicationBar and showing page navigation

LiveTiles will be extended soon. In the next episode we will take a look at the Silverlight toolkit, Page Transitions and additional controls that are available in the Silverlight toolkit. Make sure to lookout for part three in this series about Windows Phone application development.

Windows Phone Application Development & Debugging – Deactivation versus Tombstoning

While creating an update of an existing application I ran into a problem that sometimes occurred when the application was moved to the background. It turned out that the application behaved consistent with no exceptions raised when it was tombstoned after being moved to the background. However, the application sometimes crashed when it was deactivated and immediately became the executing application again without being tombstoned. In a later post I will explain the specific problem that caused the application to crash, for now I want to focus on ways to easily test deactivation scenarios.

Visual Studio 2010 has great support to test tombstoning scenarios for Windows Phone applications. Simply start debugging an application on a device or on device emulator and click the start button on the device (emulator). You will notice that the application moves to the background but that Visual Studio does not terminate its debugging session. Putting a breakpoint inside Activated / Deactivated event handlers shows us that the application is indeed being tombstoned / resurrected.

Visual Studio and Tombstoning

The debugger shows that the application is still running even though the application is no longer visible on the device. By using the back key on the device, it is possible to return to the application and to continue debugging it. However, if you start the application again on the device (so not using the back key), the debugger terminates. This means that a brand new instance of the application was started. Inside an application, it is possible to distinguish between a new instance being started and resurrection from being tombstoned by acting on the Launching or Activated events respectively. In both cases, the constructor of the page that becomes visible will be executed. More information about the application life cycle of a Windows Phone application can be found in this excellent series of blog entries by Yochay Kiriaty.

There are situations where an application is moved to the background without being tombstoned. In those situations, the application simply remains resident in memory, with its process being kept alive. When the application is activated again, it simply continues running without the need to create a new physical instance of the application. For end users the behavior is identical to tombstoning, after all, the application becomes invisible when another application starts executing. For developers there is a difference though, because no Launching or Activated event is raised and no constructor code (for instance for the currently visible page) is executed. To be able to consistently test application deactivation requires some additional work. One of the ways to ‘force’ deactivation over tombstoning is by starting a PhotoChooserTask. In my own application I simply use the application bar to add a new ApplicationBarIconButton to display a PhotoChooserTask.

To assure that this ApplicationBarIconButton is only visible in Debug mode, a bit of conditional compilation is needed. The following code snippet shows how to create a new ApplicationBarIconButton programmatically, add it to the ApplicationBar and add an event handler to its click event.

Adding an ApplicationBar Item
  1. #if DEBUG
  2. PhotoChooserTask _pt;
  3. #endif
  4.  
  5. public MainPage()
  6. {
  7.     InitializeComponent();
  8.  
  9. #if DEBUG
  10.     _pt = new PhotoChooserTask();
  11.  
  12.     this.ApplicationBar.IsVisible = true;
  13.  
  14.     ApplicationBarIconButton pauseButton = new ApplicationBarIconButton
  15.     {
  16.         Text = "Pause App",
  17.         IconUri = new Uri("/Images/appbar.transport.pause.rest.png", UriKind.Relative),
  18.         IsEnabled = true
  19.     };
  20.  
  21.     pauseButton.Click += new EventHandler(pauseButton_Click);
  22.     this.ApplicationBar.Buttons.Add(pauseButton);
  23. #endif
  24. }

Of course, adding a button to an existing ApplicationBar only works if the application has 3 or less ApplicationBarButtonIcons in use. An alternative could for instance be adding a MouseLeftButtonDown event handler to the application’s title. When clicking the ApplicationBarButtonIcon you created specifically for debug purposes, what you now can do is display the PictureChooserTask. This results in your application being pushed to the background, without being tombstoned.

Forcing us to the background
  1. void pauseButton_Click(object sender, EventArgs e)
  2. {
  3.     _pt.Show();
  4. }

This approach makes it relatively easy to test the different scenarios for your application going to the background and returning to the foreground again. Here are the results in a little test application.

TombstoningOrNot

In the left screen you can see the application immediately after the main page became visible. In the center screen you see the result of clicking the pause button, after which a PhotoChooserTask was activated and closed again. What you can see is that there is no Application_Deactivated / Application_Activated combination. You can also see that no constructor is called after returning from the PhotoChooserTask. In other words, the application is not tombstoned while the PhotoChooserTask is active. Finally, the right screen shows how the application returns from being tombstoned. In this case constructors are called and Application_Activated is raised.

The issue I had in one of my applications had to do with counting on constructors to be called to dynamically add a few controls to my visual tree.

Note: This blog entry is applicable for Windows Phone 7. For the next version of Windows Phone (codenamed Mango), developers can choose between tombstoning and fast application switching by setting the corresponding property in the project settings. Fast application switching could be considered as another state in the application’s life cycle, being very similar to the situation that was described in this post using the PhotoChooserTask.

A new Windows Phone 7 Device (Emulator)?

Just a few hours ago, the Windows Phone Developer Tools Update was released by Microsoft. This update is specifically for Windows Phone application developers to allow them to build apps that are ready for the upcoming Windows Phone OS update. After installation of the tools update, you can test copy and paste functionality on the (also updated) emulator.

In order to start working with the updated tools, you will need to download the Windows Phone Developer Tool update and a separate Visual Studio 2010 update. Also make sure to read the Release Notes for the update. The order of installation for the separate tools is not important but you have to install them both. A little more background information about the latest WPDT update can be found on the Windows Phone Developer Blog.

It is expected that all existing apps that are already published in Marketplace will continue to work, both on phones that will be updated to the new version of the OS that will be available later, but also on phones that are not updated. To show the new copy and paste feature of Windows Phone 7 in action I have created a small application that takes a URL and allows that URL to be copied in Internet Explorer on the Windows Phone Emulator. To see this little application in action, just take a look at this video.

Windows Phone 7 Copy and Paste with the WPDT January Update.

Using a BackgroundWorker to load SoundEffects into memory

In a previous post I showed you how to use specific XNA Framework functionality inside a Silverlight application for Windows Phone 7 to be able to use sound effects. Typically, when you want to play a sound effect you want to have it available immediately. As long as you don’t have too many sound effects to be played inside your application you can keep them all available in memory. However, you still need to load the sounds into memory at some time, typically when the application is started. Even if you don’t have too many different sounds that you want to use inside your application, loading sounds from a file into memory is still a time consuming operation, something that especially hurts your application during startup. After all, the end user that starts your application wants to work with it immediately, and it is a frustrating experience if you have to wait a while, even if it is only for a few additional seconds. The obvious choice in this situation is to load the sounds in the background, allowing the user to already working with the application. Of course I am using the sounds I am loading in the background as an example to show a BackgroundWorker in action. More long lasting operations (and not only during application initialization) are candidates to run on a BackgroundWorker. In a later blog post we will talk more about performance of Silverlight based Windows Phone 7 applications and things you have to think about. This post simply shows you how to use the BackgroundWorker. To talk about the BackgroundWorker we will take a look at the same application we used before when discussion the use of sounds inside an application. To separate sounds and sound handling from the rest of my application, I created a SoundPlayer class with a place holder for a number of sounds and a static method that loads those sounds from a number of wav files into SoundEffect objects:

  1. public static void LoadSoundEffects()
  2. {
  3.     soundLoader = new BackgroundWorker();
  4.     soundLoader.DoWork += new DoWorkEventHandler(soundLoader_DoWork);
  5.     soundLoader.RunWorkerCompleted +=
  6.         new RunWorkerCompletedEventHandler(soundLoader_RunWorkerCompleted);
  7.  
  8.     soundLoader.RunWorkerAsync();
  9. }

In the above code snippet, a new instance of a BackgroundWorker is created and two event handlers are assigned to respectively the DoWork event and the RunWorkerCompleted event. Finally, the RunWorkerAsync method is called, which in turn fires the DoWork event on the BackgroundWorker, allowing the event handler to execute on a separate thread. You have to be careful not to update UI Elements inside the DoWork event hander. It is only allowed to update UI Elements on the thread that created them (typically the UI Thread). In this sample this is no problem since the BackgroundWorker is only used to load sounds into memory. If you need to update UI Elements on a separate thread you must make use of the BeginInvoke method of the Dispatcher class.

In this sample, the DoWork even handler is simple and straight forward. It looks like this:

  1. static void soundLoader_DoWork(object sender, DoWorkEventArgs e)
  2. {
  3.     int i;
  4.  
  5.     soundEffects = new SoundEffect[nrSoundEffects];
  6.  
  7.     for (i = 0; i < nrSoundEffects; i++)
  8.     {
  9.         Stream audioStream = TitleContainer.OpenStream(sounds[i]);
  10.         soundEffects[i] = SoundEffect.FromStream(audioStream);
  11.         audioStream.Close();
  12.     }
  13. }

We are simply reading audio information through a number of streams and store them locally. In order to read the audio files, they are defined as content in the Visual Studio project. When all sounds are stored (or in other words when we are leaving the DoWork method), the BackgroundWorker raises the RunWorkerCompleted event. In its event handler, for this example, we are simply unsubscribing from all events, because the BackgroundWorker to load sounds is only called one time:

  1. static void soundLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  2. {
  3.     if (soundLoader != null)
  4.     {
  5.         soundLoader.DoWork -= soundLoader_DoWork;
  6.         soundLoader.RunWorkerCompleted -= soundLoader_RunWorkerCompleted;
  7.         soundLoader = null;
  8.     }
  9. }

The BackgroundWorker has more functionality, for instance to report progress for long lasting operations. Progress information can be easily displayed to the user. In the above shown example, progress information is not used. The end result of using a BackgroundWorker is that the user interface remains responsive. In this particular example, the application starts pretty fast so that end-users can start playing while sounds are still being loaded.

If you are curious about this game, you can find it Clicker here on the Windows Phone 7 Marketplace. Note: This link will work from a Windows Phone 7, or from a PC with Zune software installed. The game has a trial mode so you can try it for free.

Another year, another MIX

Last year in April, the place to be was Las Vegas, NV for MIX 10. During this conference  Windows Phone 7 was officially introduced. Immediately after MIX 10 the development tools were available for download. Also, the great content that was presented during MIX 10 is still available for you to watch. It seems hard to believe that we have been developing Windows Phone 7 applications for less than a year. We really have come a long way. Windows Phone 7 is released in a number of countries, devices are available in many more countries and the list of applications being released on Marketplace is growing rapidly.

Update: It is no longer possible to vote for MIX11 sessions. Thank you very much if you voted for one (or more) of my sessions that are listed below.

This year, before attending MIX, there is a call to action for everybody (especially for you since you are reading this blog post). You are in control of voting for a number of sessions of which the most favorite sessions will be presented at MIX. Amongst the Windows Phone 7 sessions that are up for voting, three were submitted by me. I am counting on you to help me become part of MIX 11. If you like the things I am writing on this blog or if you have seen me speaking in the past, or just because you are visiting this website, make sure to vote for my MIX 11 sessions. You can vote for all these sessions by clicking on the links. You can only vote for each session once on a physical machine, but of course I can’t prevent you against voting multiple times on different machines. Here are the sessions I submitted for voting (clicking on the individual links will bring you to the voting page for the particular sessions):

  • Windows Phone 7: Application Architecture

    When you start developing Silverlight applications for Windows Phone 7 using Visual Studio 2010, you might be tempted to use code behind to connect your user interface (written in XAML) to your functionality (written in C#). In this sample filled presentation, Maarten Struys explains why this relatively easy approach is not necessarily the best approach to create testable, maintainable and great Windows Phone 7 applications. During the presentation, the power of DataBinding in Silverlight will be revealed and a traditional application, using code behind will be converted into an application that makes use of the MVVM design pattern.

  • Windows Phone 7 and the Cloud: The Sky is The Limit

    Windows Phone 7 is a powerful platform for which you can create great stand-alone Silverlight based applications. To create Windows Phone 7 applications with limitless processing resources and virtually unlimited storage capacity, Windows Azure and Windows Phone 7 are great companions. In this sample filled presentation, Maarten Struys shows you how to create a Windows Phone 7 application together with a Windows Azure based back-end. He explains how the application can efficiently communicate with the back-end using a REST based Web Client interface. He also shows you how to efficiently cache information locally on the phone to make Windows Phone 7 applications operate independent of network connectivity. After attending this session you know how to create Windows Phone 7 applications that are as powerful as server applications.

  • Fast starting and State Saving Windows Phone 7 Applications

    In this sample filled presentation, Maarten Struys shows you the impact of Tombstoning on Windows Phone 7 applications. He shows you how to store the application’s state and individual page state information efficiently. He also explains how your application can start fast and efficiently by making use of multithreading and asynchronous programming techniques. After attending this presentation, your Windows Phone 7 Tombstone headaches will be history and your end users will be happy with your fast starting applications.

Thank you very much for voting! I really hope to see you in Las Vegas between April 12 – April 14 for MIX 11. If you are planning to visit MIX 11, make sure to register before February 11 to benefit from a nice discount.

Adding Sound Effects to a Windows Phone 7 Silverlight Application

Certain Windows Phone 7 applications benefit from using sound effects, even if the application itself is written in Silverlight. You most likely have noticed that you can play media inside a Silverlight application by making use of the MediaPlayerLauncher inside your application to pass control to the integrated media player on the phone or by making use of the MediaElement class. Both these options are great if you want to play audio content under control of some form of media player (with MediaElement allowing to integrate player functionality inside your own application).

However, if you want short sound effects that play under control of your application, you can make use of functionality that is available in the XNA Framework, even if you are developing a Silverlight based Windows Phone 7 application. The XNA Framework contains a SoundEffect class. This class holds a sound resource in memory that can be played from inside your application by calling its Play method. You can even alter properties like the pitch and volume of a SoundEffect. Since there is interoperability possible between Silverlight and the XNA Framework (at least to a certain extend), it is possible to make use of SoundEffect inside a Silverlight application. However, given the different application models for Silverlight and XNA Framework applications, you have to be aware of what you are doing when added SoundEffect to your Silverlight application. A first attempt to add sound might look like this:

  1. using System.ComponentModel;
  2. using System.IO;
  3. using Microsoft.Xna.Framework;
  4. using Microsoft.Xna.Framework.Audio;
  5.  
  6. namespace Clicker.Model
  7. {
  8.     public class SoundPlayer
  9.     {
  10.         public enum Sounds
  11.         {
  12.             Switch = 0,
  13.             Penalty,
  14.             StartGame,
  15.             HighScore,
  16.             EndGame
  17.         };
  18.  
  19.         static SoundEffect[] soundEffects;
  20.  
  21.         public static void Play(Sounds soundEffect)
  22.         {
  23.             if (soundEffects != null)
  24.             {
  25.                 soundEffects[(int)soundEffect].Play();
  26.             }
  27.         }
  28.     }
  29. }

This code snippet, taken from a real application, shows how to play a sound that was previously loaded into memory. To focus on playing sounds, loading the sounds into an array of type SoundEffect is omitted. When the static Play method of the SoundPlayer class is called, an exception is thrown.

Exception

The exception being displayed clearly indicates the cause of the problem. You can read more about solving this particular exception on MSDN, which contains information about enabling XNA Framework Events inside Windows Phone Applications. The information is very relevant, however, it explains how you should regularly call FrameworkDispatcher.Update(). Calling this method dispatches messages that are in the XNA Framework message queue for processing. The documentation gives the advice to call FrameworkDispatcher.Update() regularly, for instance on a timer. For playing single sound effects, this seems to be an overkill. After all, using a timer means that some code will executed repeatedly (in our case even if no sound is currently played). On a battery powered device like a Windows Phone 7 this means that we are draining more battery power then necessary. Instead, I simply modified my code by adding a call to FrameworkDispatcher.Update() immediately before calling the Play method on the SoundEffect object. This works fine in the following scenario:

  • The only XNA Framework functionality used inside a Silverlight application is one or more instances of type SoundEffect.
  • Only one single SoundEffect is played at any given time.

The following code snippet shows the modified Play method of my own SoundPlayer class (which is playing sounds as expected):

  1. public static void Play(Sounds soundEffect)
  2. {
  3.     if (soundEffects != null)
  4.     {
  5.         FrameworkDispatcher.Update();
  6.         soundEffects[(int)soundEffect].Play();
  7.     }
  8. }

In an upcoming blog entry I will show you how to load a number of SoundEffects into memory using a BackgroundWorker.

Splash Screens

If you start developing a new Windows Phone 7 application, you usually start by creating a new Visual Studio 2010 project. As part of the initial project, Visual Studio creates a default splash screen for you, consisting of a waiting clock.

DefaultSplashScreen

A Windows Phone splash screen is simply a jpg file with a resolution of 800 * 480 pixels. This means that it is very simple to replace the default splash screen (which is conveniently stored in your Visual Studio project under the name SplashScreenImage.jpg). Just make sure you have a jpg file with the right resolution and also make sure that it is placed in the root of your Visual Studio project. The name must be SplashScreenImage.jpg and its Build Action must be set to Content in the Properties window. Leaving the original splash screen unchanged in your own application gives end users a somewhat boring experience. After all, a splash screen is used to give users the impression that your application starts fast, and it also occupies users while your application is loading. If all applications use the same default splash screen, it will not help giving users a fast starting impression about those applications. So it is important to provide your own splash screen. If an application does not spent much time initializing, the actual amount of time that a splash screen is displayed is very short. For one of my applications, I did create a reasonably nice splash screen, to find out that the splash screen often is displayed for less then a second. My initial thought was to delay application start to allow end users to admire my splash screen. Of course this is a very bad idea, something you should not even consider doing.

SplashScreen1

This splash screen is used in a little game that is available on Marketplace. Typically the game starts up in under a second, meaning the user hardly has time to see the splash screen. The good news is that it is at least not the default splash screen. I have to admit that I considered adding a delay in my application for users to see the splash screen. Of course, and end user might like it once to take a look at this splash screen, but after starting an application several times, the splash screen will become boring since it is just a static image.

On a side note, if you are curious about this game, you can find it here on the Windows Phone 7 Marketplace. Note: This link will work from a Windows Phone 7, or from a PC with Zune software installed.

Back to the story about splash screens though. If you are developing a Silverlight application for Windows Phone 7, take the following idea into consideration.  By far the best experience you can give end users for fast starting applications, is to take a screen shot from your application’s main page. If your application starts with some animation, make sure to take the screen shot from the initial situation (before the animation starts running).

SplashScreen2

Capture

Also, leave the application title / page title out of the splash screen. What I did for my latest application was taking the following shot from the main screen. Once the application is initialized, the application and page title animate in from the top, nice and gently. This gives a very nice experience for end users, and you don’t have to worry that your splash screen is only visible for a very short time, after all, your splash screen partly is your main page.

 

To have some nice page transitions on your main page, you can make use of functionality that is available in the November release of the Silverlight for Windows Phone Toolkit. An in-depth explanation of how to use these page transitions can be found in this MSDN  blog entry by Will Faught.

This is the code that I am using to bring in the application title and page title in an override version of the OnNavigatedTo method:

  1. protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
  2. {
  3.     base.OnNavigatedTo(e);
  4.  
  5.     if (Settings.Instance.ApplicationLaunching)
  6.     {
  7.         SlideTransition slideTransitionFadeIn = new SlideTransition { Mode = SlideTransitionMode.SlideDownFadeIn };
  8.         ITransition transitionTitle = slideTransitionFadeIn.GetTransition(this.TitlePanel);
  9.         transitionTitle.Completed += delegate { transitionTitle.Stop(); };
  10.         transitionTitle.Begin();
  11.         Settings.Instance.ApplicationLaunching = false;
  12.     }
  13. }

Only when my application is launching (a new instance of the application is started, or the application returns from being tombstoned), the animation will run. In all other situations ‘normal’ page transitions will be executed. I keep track of the application being launched in the app.xaml.cs source file like this:

  1. // Code to execute when the application is launching (eg, from Start)
  2. // This code will not execute when the application is reactivated
  3. private void Application_Launching(object sender, LaunchingEventArgs e)
  4. {
  5.     Settings.Instance.IsTrialMode = RunningMode.CheckIsTrial();
  6.     Settings.Instance.ApplicationLaunching = true;
  7. }
  8.  
  9. // Code to execute when the application is activated (brought to foreground)
  10. // This code will not execute when the application is first launched
  11. private void Application_Activated(object sender, ActivatedEventArgs e)
  12. {
  13.     Settings.Instance.IsTrialMode = RunningMode.CheckIsTrial();
  14.     Settings.Instance.ApplicationLaunching = true;
  15. }

As you can see, a little bit of code and an additional screen capture from of your application gives you a simple splash screen that is effective for fast loading applications, yet giving the end users a very nice starting experience of your application.