Category Archives: Silverlight

EvenTiles and TrialMode

In part 17 of EvenTiles we will take a look at Trial Mode. When an application supports trial mode, users can first try the application before buying it. It is up to you as the application developer to determine which functionality is available in the application when running in trial mode. Even though trial mode makes your application slightly more complex, the advantage of implementing trial mode is that you will only have to submit one single version of your application that customers can either try or buy. The application is started with either a trial license or a full license (when the user purchased the application). Inside the application, you can make use of an API to determine if a user is running your application in trial mode or not. From a technical point of view, there are no restrictions to trial mode, so you can even provide full application functionality in trial mode. Of course that does not make sense, because you typically want to use trial mode to invite end users to try your application after which they hopefully get so excited about your application that they determine to buy it.

NOTE: Be careful with providing a limited time to execute a fully functional application in trial mode, because end users can simply reinstall your application to again run the application for a certain amount of time in trial mode.

Let’s assume that EvenTile has two different modes of operation, implemented through Trial Mode. In Trial Mode, EvenTiles is fully functional without restrictions, however, the application will display ads on the main page (adding the actual advertisements to EvenTiles will be covered later in this series). As soon as users purchase EvenTiles, advertisements will be disabled. In trial mode, the application also contains functionality to retrieve location information in order to receive localized advertisements, although the user can disable location retrieval through the Settings Page of the application. However, if a user purchases the application, location information will not be retrieved and it does not make sense to have a toggle switch in the Settings Page to enable / disable location retrieval. Finally, if the user runs EvenTiles in trial mode, they have the option to purchase the application from within the application’s About Page. Of course, this option is only available in trial mode, if the application is already purchases, the About Page allows a user to display more applications that were published by DotNETForDevices.

Let’s begin by finding out how we can determine if the application is currently running in Trial Mode. In order to do so, as long as the user is running the application in Trial Mode, we will check the current application’s license each time the application starts or becomes the foreground application, and set a Boolean property accordingly. We also store the current value of that Boolean property in our application settings. When a user has purchased the application, we only have to check the application settings which results in faster starting / resuming of the application. The following code snippet shows how to determine if we are running in Trial mode:

Running in Trial Mode?
  1. public const string keyTrialMode = "K_TRIAL";
  2. public static bool IsTrialMode { get; private set; }
  3.  
  4. private void Application_Launching(object sender, LaunchingEventArgs e)
  5. {
  6.     if (!appSettings.Contains(keyTrialMode))
  7.     {
  8.         appSettings[keyTrialMode] = true;
  9.     }
  10.  
  11.     IsTrialMode = (bool)appSettings[keyTrialMode];
  12.  
  13.     if (IsTrialMode)
  14.     {
  15.         CheckTrialMode();
  16.     }
  17. }
  18.  
  19. private void CheckTrialMode()
  20. {
  21.     IsTrialMode = new LicenseInformation().IsTrial();
  22. }

This snippet only shows checking for Trial Mode when the application is launched. We first determine if we already stored the current license type in our application settings. If we assume we are running in Trial Mode we need to check if the license type has chanced since the last time the user ran the application. Since correct license information will only be added when the application is downloaded from the Windows Phone Marketplace, it might be a little tricky to test this functionality. When you installed the application locally on an unlocked device during testing of your application, or when you execute the application from within Visual Studio, the LicenseInformation.IsTrial method always returns false. With a little bit of conditional compilation, we can easily change this for test purposes. In the following code snippet you can see that we can test Trial mode when we are running the application in Debug mode and when the TRIAL symbol is defined. By simply setting this symbol to NO_TRIAL we can test the application for both different license types.

Testing Trial Mode
  1. #if DEBUG
  2. #define TRIAL
  3. #endif
  4.  
  5. using System.Windows;
  6. using Microsoft.Phone.Marketplace;
  7.  
  8. namespace EvenTiles
  9. {
  10.     public partial class App : Application
  11.     {
  12.         private void CheckTrialMode()
  13.         {
  14. #if ! TRIAL
  15.             IsTrialMode = new LicenseInformation().IsTrial();
  16. #endif
  17.         }

In the OnLaunching method of the application, the IsTrialMode property is initialized to true and optionally modified by executing the CheckTrialMode method. If you want to test the application as if it was purchased by a user, you can simply change TRIAL to NO_TRIAL, recompile and execute the application again.

NOTE: If you take this approach, make sure that you install a clean copy of the application to a device or the emulator when switching back to trial mode. The way the code is organized, once the IsTrialMode property is set to false, the call to the LicenseInformation.IsTrial method is never executed again. To install a clean copy, make sure to rebuild your application in Visual Studio before deploying it, instead of simply building the application. After a rebuild, not only the application is replaced on the target device, but the entire IsolatedStorage area of the application is cleaned.

Testing a purchased app
  1. #if DEBUG
  2. #define NO_TRIAL
  3. #endif
  4.  
  5. using System.Windows;
  6. using Microsoft.Phone.Marketplace;
  7.  
  8. namespace EvenTiles
  9. {
  10.     public partial class App : Application
  11.     {
  12.         private void CheckTrialMode()
  13.         {
  14. #if ! TRIAL
  15.             IsTrialMode = new LicenseInformation().IsTrial();
  16. #endif
  17.         }

Since Debug is not set in release mode, you will always call the LicenseInformation.IsTrial method when the application is deployed to a device.

Since we now have determined if the application is running in Trial Mode or not, we can simply use this information to display / hide the location retrieval toggle button on the Settings Page. Also, when can alter the functionality of one of the buttons on the About Page. If the application runs in Trial Mode, the user can purchase the application from within the About Page. If the user already has purchased the application, they can use the same button to check more applications from the same publisher, as shown in the following code snippet:

Changing button behavior
  1. public partial class AboutPage : PhoneApplicationPage
  2. {
  3.     public AboutPage()
  4.     {
  5.         InitializeComponent();
  6.  
  7.         btnMore.Content = App.IsTrialMode ? "Purchase EvenTiles now" : "More from DotNETForDevices";
  8.     }
  9.  
  10.     private void btnMore_Click(object sender, RoutedEventArgs e)
  11.     {
  12.         if (App.IsTrialMode)
  13.         {
  14.             MarketplaceDetailTask detailTask = new MarketplaceDetailTask();
  15.             detailTask.Show();
  16.         }
  17.         else
  18.         {
  19.             var searchTask = new MarketplaceSearchTask
  20.             {
  21.                 ContentType = MarketplaceContentType.Applications,
  22.                 SearchTerms = "DotNETForDevices"
  23.             };
  24.             searchTask.Show();
  25.         }
  26.     }
  27. }

When the application is running, it either shows the location toggle switch and it provides different functionality in the About Page.

image

The following video shows how to add Trial Mode to the EvenTiles application. It also shows how you can test this functionality by making use of some conditional compilation.

Adding TrialMode to the application and testing TrialMode.

To be able to experiment with the functionality of EvenTiles as it is right now, the sample code is available for dowload here. In the next episode of EvenTiles we will talk about adding support to run EvenTiles on 256-MB Windows Phone devices.

EvenTilesYou can already install the latest version of EvenTile on your own Windows Phone. from Marketplace. Remember that the application is not meant to be extremely useful, although it contains similar functionality that “serious” applications have. Just go ahead and get here: http://www.windowsphone.com/en-US/search?q=EvenTiles (or search on your phone for EvenTiles in the Marketplace application).

Advertisements

EvenTiles from Start to Finish–Part 16

In the previous episode of this series about how to develop a Windows Phone application from scratch you learned how to create the UI of a more or less typical About Page using Expression Blend. The About Page contains nothing fancy, just a number of TextBlocks and a few Buttons. Right now we are ready to add some functionality to the About Page to

  • Display the application’s version in a TextBlock
  • Submit an email containing remarks and/or suggestions to the application’s publisher
  • Submit a review for the application
  • Check Marketplace for more applications, available from the same publisher

screen1

In itself, these are all small, relatively easy and partly unrelated actions. However, the latter 3 items, even though different, all have something in common. In order to achieve the desired result, we will make use of functionality that is available in a Windows Phone, but outside of our application. To use that specific functionality, we will make use of different Windows Phone Launchers. You can think of a Launcher as a separate application that can be shared by our applications to allow users to perform some common tasks in a uniform and consistent way. The fact that a Launcher starts a separate, built-in application, has some consequences for our application that makes use of the Launcher. When the application we launched becomes active, our application will be moved to the background. This means that our application will temporarily be paused and even be tombstoned in low memory / resource situations. Since we already took care of properly dealing with our application being moved to the background (see episode 7 about Tombstoning), this is not a big deal but it is good to realize what is happening under the covers of the Windows Phone platform.

Note: Usually Launchers are mentioned together with Choosers because they provide similar functionality and operate more or less the same. The big difference between them is that a Chooser (as the word implies) is capable of selecting some data (for instance a picture) and return the selected item to our application. Choosers will be covered in a later episode of EvenTiles.

As always, it makes a lot of sense to see things in action and to take a look at actual code. That is the reason why, besides these series of blog entries, there are also accompanying videos and sample code available for download.

Retrieving the application’s version number

The first goal we want to achieve is to retrieve the version number of our application and display it in the About page. Since our application stores its own version number in its manifest file, we want to retrieve it from there.

NOTE: The version number must also be specified when submitting an application to the Windows Phone Marketplace. According to the documentation, this version number must match your application’s version number but maintaining it in your manifest file is a separate activity. There is yet another version number, stored in the application’s AssemblyInfo.cs file and modifiable through the project properties. In EvenTiles we ignore the latter and retrieve the version number immediately from the application’s manifest file.

Application version numbers consist of major, minor, build, and revision components. To match the version number as it is showed in the Windows Phone Marketplace, we only want to display the major and minor parts of the application. Since the application manifest file is just another XML file, we can easily retrieve the version number from it.

Version info in manifest file
  1. <App xmlns=""
  2.      ProductID="{883385e6-52e5-4835-83db-8a17499b5767}"
  3.      Title="EvenTiles"
  4.      RuntimeType="Silverlight"
  5.      Version="1.0.0.0"
  6.      Genre="apps.normal"
  7.      Author="Maarten Struys"
  8.      Description="Sample description"
  9.      Publisher="DotNETForDevices">

To retrieve the version number and to display it in a Textblock inside the About Page, we can just load the XML from the manifest file and find the value of the version attribute of the App element. The reason why this works is because the application manifest file (WMAppManifest.xml) is deployed to the phone as part of the XAP file.

Get version from manifest file
  1. private string GetVersionNumber()
  2. {
  3.     string[] version = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value.Split('.');
  4.  
  5.     StringBuilder sb = new StringBuilder(version[0]);
  6.     sb.Append(".");
  7.     sb.Append(version[1]);
  8.     versionNumber = sb.ToString();
  9.  
  10.     return versionNumber;
  11. }
  12.  
  13. private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
  14. {
  15.     tbVersion.Text = GetVersionNumber();
  16. }

Sending an email

A nice feature inside a Windows Phone application is the possibility for end users to get in touch with you through email. Making this as easy as possible for end users might result in you getting some useful feedback about your application and might also increase the user’s satisfaction with your application, which in turn might lead to better and more reviews. To send an email programmatically to a fixed email address is very simple. You simply can make use of the EmailComposeTask and even pre-populate information in the email to make it easier for the end user to send out an email. The following code shows how to send an email programmatically:

Using the EmailComposeTask
  1. private void btnEmail_Click(object sender, RoutedEventArgs e)
  2. {
  3.     StringBuilder sb = new StringBuilder("Feedback / Support for EvenTiles ");
  4.     sb.Append(versionNumber);
  5.  
  6.     var emailComposeTask = new EmailComposeTask
  7.     {
  8.         To = "mstruys@hotmail.com",
  9.         Subject = sb.ToString()
  10.     };
  11.     emailComposeTask.Show();
  12. }

NOTE: In order to test this functionality, you have to use a physical device. The Windows Phone Emulator will throw an exception when using the email compose task.

Submitting a review

If you know how to use one Windows Phone Launcher you basically know how to use them all. Since we already saw that sending an email is a very simple operation (creating a new object, setting some properties and calling the Show method on the object), submitting a review should not be difficult. The following code shows how to allow your users to submit a review by using the MarketplaceReviewTask Launcher:

Submitting a review
  1. private void btnReview_Click(object sender, RoutedEventArgs e)
  2. {
  3.     MarketplaceReviewTask reviewTask = new MarketplaceReviewTask();
  4.     reviewTask.Show();
  5. }

screen2

Of course, this code can be extended, for instance by storing in the application settings if a review has already been submitted. If so, we can for instance remove the button to submit a review from the application. We can also verify if we currently have a data connection in order to submit a review. All this functionality is omitted in this sample code.

Checking for more applications

Using the same approach as described before, we can also allow the user to look for more applications that we already published on the Windows Phone Marketplace. This can be achieved by using the MarketplaceSearchTask, again in a similar way:

Finding apps on Marketplace
  1. private void btnMore_Click(object sender, RoutedEventArgs e)
  2. {
  3.     var searchTask = new MarketplaceSearchTask
  4.     {
  5.         ContentType = MarketplaceContentType.Applications,
  6.         SearchTerms = "DotNETForDevices"
  7.     };
  8.     searchTask.Show();
  9. }

The MarketplaceSearchTask is a very nice marketing instrument because you can guide users of your application to other Windows Phone applications you have published.

The following video shows how to create the functionality we described in this episode of EvenTiles. It also shows two of the described Launchers in action, one running in the emulator, one on a physical device.

Using Launchers inside a Windows Phone Application

To be able to experiment with this working implementation of EvenTiles, especially to understand how the application interacts with the PeriodicTask through a file in IsolatedStorage, the sample code is available for dowload here. In the next episode of EvenTiles we will talk about implementing Trial Mode in your application to allow users to try the application before optionally buying it.

EvenTilesIf you want to see EvenTiles already in action on your Windows Phone, you can also install the latest free version from Marketplace. Remember that this application is not meant to be extremely useful, although it contains similar functionality that “serious” applications have. Just go ahead and get your free copy of EvenTiles from Marketplace at this location: http://www.windowsphone.com/en-US/search?q=EvenTiles (or search on your phone for EvenTiles in the Marketplace application).

EvenTiles Until Now (A Windows Phone Development Series)

Looking at all the different topics that the EvenTiles series covers, I think it makes sense to at least have a table of contents for the series so far. For instance, if you are interested in reading something about tombstoning, it is not necessary to read through the entire series (although of course I invite you to do so anyway). At this moment, EvenTiles explains how to use Windows Phone Tiles, including Secondary Tiles. It also show how you can update content on your Tiles locally by using a Background Agent. Also don’t forget that all source code is available and each individual episode of EvenTiles contains a demo on video as well. The latest sample source code can be downloaded.

Here is the table of contents for the first 14 parts of EvenTiles:

Introducing the EvenTiles application

  • Creating a new project in Visual Studio 2010 Express for Windows Phone
  • Defining an Application Tile from within the WMAppManifest.xml file
  • Using the emulator to run the application

PageNavigation and ApplicationBar

  • Using Expression Blend to create an Application Bar
  • Navigating to different pages by using the NavigationService

Using the Silverlight for Windows Phone Toolkit in your application

  • Defining page transitions in XAML and using them in your application
  • Using styles in XAML
  • Declaring and using a ToggleSwitch control

Creating the Settings Page

  • Designing a Windows Phone page using Expression Blend
  • Executing code as a result of page navigation (using OnNavigatingTo and OnNavigatingFrom)
  • Using event handlers to execute code on user interaction with UI elements

Using IsolatedStorage

  • Storing data in between different times an application executes
  • Introducing the application life cycle
  • Using IsolatedStorageSettings to persist information

Using the Isolated Storage Explorer Tool

  • Examining the contents of our application’s IsolatedStorage

Fast Application Switching and Tombstoning

  • A Windows Phone Application’s life cycle
  • Saving application state when moved to the background
  • Restoring application state when returning to the foreground

More on Tombstoning

  • Maintaining Page State
  • Restoring a page to exactly the same situation it was when the application moved to the background
  • Restoring focus of input UI elements

Creating a Secondary Tile

  • Creating a Secondary Tile inside your application
  • Navigating from the Secondary Tile to the application
  • Determine if a Secondary Tile is currently visible on the Start screen of a Windows Phone through a lambda expression
  • Setting the front and back contents of a Secondary Tile

Background Agents

  • Different types of Background Agents
  • Properly creating a PeriodicTask
  • Starting and stopping a PeriodicTask
  • Relation between an Application and a Background Agent

Debugging Background Agents

  • Using conditional compilation to test Background Agents
  • Properly using the LaunchForTest method
  • Using the debugger to debug a PeriodicTask

The lifetime of PeriodicTask

  • Rescheduling a PeriodicTask
  • Exceptions that might be thrown when scheduling a PeriodicTask

Communication between an Application and its PeriodicTask

  • Passing data between an application and a PeriodicTask
  • Protecting variables against simultaneous access by different threads
  • Using a Mutex to synchronize threads

Exchanging data between an Application and its PeriodicTask

  • Using a file in IsolatedStorage to exchange data between an application and a PeriodicTask

Even though there are many more episodes of EvenTiles planned, attention will now move beyond tiles as we focus on using built-in applications and accessing device hardware.

EvenTiles from Start to Finish–Part 3

In the second part of this series about how to develop a Windows Phone application from scratch we looked at the ApplicationBar and Page Navigation. Today we will introduce the Silverlight Toolkit for Windows Phone, show how to use it inside an application and add page transitions to the application. We will take off where we finished in Part 2.

The Silverlight Toolkit for Windows Phone is a separate assembly that you can install after downloading it. It installs in the same location where the Windows Phone SDK’s are installed, making it very easy to add a reference to it in order to use functionality that can be found in the toolkit.

imageAfter you have installed the toolkit, you can add a reference to it inside your application by right-clicking the references field your project and selecting the toolkit in the dialog box that appears. After adding the toolkit to the references, you will see it under references inside solution explorer. The first thing we are going to do is adding page transitions. If you look at the video, you will see that the pages of our application are currently simply appearing without any animations. However, page transitions inside many applications are similar to turning pages in a book. This is for instance the case with applications that are already installed on your Windows Phone. The Silverlight Toolkit contains functionality to make it very easy to incorporate similar page transitions inside your own applications. There are many different transitions to choose from, but we will use the same page turning transitions that you probably already know when you activate an application from the start screen.

To add page transitions inside your own application, it is important to change the PhoneApplicationFrame for your application into a TransitionFrame. The latter is defined in the Silverlight toolkit and allows for page transitions. The RootFrame is a container to hold all pages that you will create inside your application. You will have to search for the method InitializePhoneApplication inside the source file App.xaml.cs that Visual Studio created for you when you created the EvenTiles project. Inside this method, you can see that a new RootFrame is created of type PhoneApplicationFrame. You will have to change this into a TransitionFrame in order to get your page transitions working.

Using a TransitionFrame
  1. // Do not add any additional code to this method
  2. private void InitializePhoneApplication()
  3. {
  4.     if (phoneApplicationInitialized)
  5.         return;
  6.  
  7.     // Create the frame but don't set it as RootVisual yet; this allows the splash
  8.     // screen to remain active until the application is ready to render.
  9.     // RootFrame = new PhoneApplicationFrame();
  10.     RootFrame = new TransitionFrame();
  11.     RootFrame.Navigated += CompleteInitializePhoneApplication;
  12.  
  13.     // Handle navigation failures
  14.     RootFrame.NavigationFailed += RootFrame_NavigationFailed;
  15.  
  16.     // Ensure we don't initialize again
  17.     phoneApplicationInitialized = true;
  18. }

In order to get page transitions working, the next thing you have to do is add some XAML that defines the different page transitions to each page on which you want to make use of page transitions. Instead of adding individual pieces of XAML for each page, you can also create a new style that you use inside all pages that you want to make use of page transitions. That is the approach we are taking in this sample. First thing to do is add the following XAML to the App.xaml file:

PageTransition Style
  1. <!–Application Resources–>
  2. <Application.Resources>
  3.     <Style x:Key="DefaultPageWithTransitions"
  4.             TargetType="phone:PhoneApplicationPage">
  5.         <Setter Property="sltk:TransitionService.NavigationInTransition">
  6.             <Setter.Value>
  7.                 <sltk:NavigationInTransition>
  8.                     <sltk:NavigationInTransition.Backward>
  9.                         <sltk:TurnstileTransition Mode="BackwardIn" />
  10.                     </sltk:NavigationInTransition.Backward>
  11.                     <sltk:NavigationInTransition.Forward>
  12.                         <sltk:TurnstileTransition Mode="ForwardIn" />
  13.                     </sltk:NavigationInTransition.Forward>
  14.                 </sltk:NavigationInTransition>
  15.             </Setter.Value>
  16.         </Setter>
  17.         <Setter Property="sltk:TransitionService.NavigationOutTransition">
  18.             <Setter.Value>
  19.                 <sltk:NavigationOutTransition>
  20.                     <sltk:NavigationOutTransition.Backward>
  21.                         <sltk:TurnstileTransition Mode="BackwardOut" />
  22.                     </sltk:NavigationOutTransition.Backward>
  23.                     <sltk:NavigationOutTransition.Forward>
  24.                         <sltk:TurnstileTransition Mode="ForwardOut" />
  25.                     </sltk:NavigationOutTransition.Forward>
  26.                 </sltk:NavigationOutTransition>
  27.             </Setter.Value>
  28.         </Setter>
  29.     </Style>
  30. </Application.Resources>

Here we define different transitions that will run when you are navigating to and from pages inside the application. The transitions that you can see in the code snippet are all TurnStileTransitions which are commonly used for page transitions inside a Windows Phone application. The Silverlight Toolkit contains other transition types as well.

imageAfter having defined the transitions and after having changed the RootFrame to be able to host transitions, the only thing that is left to do is assigning newly created transition style to each individual page. This can for instance be done using Expression Blend. When you now would run the application, it will blend in perfectly with applications that came with your Windows Phone. Navigating from page to page inside our application is now identical to navigating inside for instance the different settings on the Windows Phone. Of course it is not necessary to make use of page transitions, but it does make your application look better and even more professional.

 

The Silverlight Toolkit for Windows Phone contains much more useful items, like a number of cool user interface elements. To see already one of them in action, we are adding it to the Settings Page. On the SettingsPage we later need a switch that can enable / disable reading of location data. Right now we are just going to enter a dummy switch and we are choosing a nice control from the Silverlight Toolkit, the ToggleSwitch. This control looks like a light switch and has (like a CheckBox) two different states, checked and unchecked. This control looks extremely good inside a Windows Phone application, as you can see in the following screenshot:

image

Inside Visual Studio 2010 Express Edition you can see the SettingsPage in designer mode. In it, you can also see a ToggleSwitch (in checked mode). The ToggleSwitch is added to the content grid, filling up as much space as it needs in the last row of the grid. How to layout UI controls inside a grid and in other container controls is something we will cover later in this series about Windows Phone Application Development.

In the following video you can see all the steps that are needed to add transitions to your Windows Phone Application and how to be able to use functionality from the Silverlight Toolkit inside your own application.

Using the Silverlight Toolkit to add Page Transitions to EvenTiles

LiveTiles will be extended soon. In the next episode we will create the SettingsPage UI and make sure that we can store data entered on the SettingsPage. Make sure to lookout for part four in this series about Windows Phone application development which will be published soon.

EvenTiles from Start to Finish–Part 1

As I promised a few days ago, in between other blog entries I will show you how to create a complete Windows Phone application from scratch. This project starts with running Visual Studio to create an initial solution and it stops after having updated the application a few times and successfully submitted each different version to MarketPlace. Initially I will focus on creating the application without thinking too much about testability and reusability. I just show you the possibilities of Visual Studio, the Emulator and later on Expression Blend, Marketplace and additional tools. Later in this project we shift focus towards creating a more maintainable application, also using modern design patterns like MVVM. This series of articles is not meant to be a complete programming course for Windows Phone. If you want to know more about developing applications in C#, you should take a look at the Rob MilesYellow Book. Not only an excellent resource to learn the C# programming language but also fun to read. If you want to learn more about Windows Phone application development, I can highly recommend Rob Miles’ Blue Book, and Charles Petzold’s book titled Programming Windows Phone 7. The good news is that all these books can be downloaded for free and they are all very valuable resources.

Ok, back to application development. In this first part, you will learn how to create the initial solution for your project, how to modify the default Application Tile, how to write something on the back of the Application Tile through the manifest file and how to modify the default Icon. You will also see the application in action for the first time. All steps that are necessary are not only documented, but also accompanied by a short video that can be viewed in this blog entry as well. If you already want to have a sneak preview of the application we are going to develop, it will be published on Marketplace soon. I will update this line with the link to the application once it has been certified.

To begin with, we create a new Windows Phone Silverlight Application, call it EvenTiles and modify both the ApplicationIcon.png and the Background.png files to have a transparent icon for the application and a transparent Application Tile. The cool part about adding transparency is that the area’s of the art work that are transparent show up in the theme accent color that is selected by the user of the phone. Of course we are also setting the application name and a page name on the application’s main page.

image

For this first version of EvenTiles we are not going to add additional functionality, although we will change the behavior of the Application Tile. Instead of showing a static Application Tile, we want it to alternate between displaying the front and the back. We can achieve this by providing back side content for the Application Tile. This can actually be done in code, but also by adding definitions for background content to the application’s manifest file. Each Windows Phone application has a manifest file with the name WMAppManifest.xml that contains information about the application, including an optional definition of content that needs to be displayed on the back side of the Application Tile. We will modify the WMAppManifest file to specify what we want to see on the back side of the Application Tile (as shown in the following code snippet):

Defining the Application Tile
  1. <Tokens>
  2.   <PrimaryToken TokenID="EvenTilesToken" TaskName="_default">
  3.     <TemplateType5>
  4.       <BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
  5.       <Count>0</Count>
  6.       <Title>EvenTiles</Title>
  7.       <BackBackgroundImageUri IsRelative="true" IsResource="false">Backbackground.png</BackBackgroundImageUri>
  8.       <BackTitle>EvenTiles</BackTitle>
  9.       <BackContent>Click me to start EvenTiles</BackContent>
  10.     </TemplateType5>
  11.   </PrimaryToken>
  12. </Tokens>

In order to clearly see the content on the back side of the Application Tile, it’s image is simply an entirely transparent image, meaning it will show a solid theme color as background of the back side content.

If you deploy this application to the emulator or to a real device, you will see a rotating Application Tile after you have pinned the application to the start screen. You can watch the application being created in this video:

EvenTIles:Part 1 – Add a back side to the Application Tile

So far, the following additional EvenTiles episodes have been published:

  1. Introducing the EvenTiles application
  2. ApplicationBar and Page Navigation
  3. Using the Silverlight Toolkit for Windows Phone
  4. Creating a Settings Page
  5. Storing Application Settings in IsolatedStorage
  6. Using the Isolated Storarage Explorer Tool
  7. Fast Application Switching and Tombstoning
  8. More on Tombstoning
  9. Creating a Secondary Tile
  10. Background Agents
  11. Debugging Background Agents
  12. The lifetime of a PeriodicTask
  13. Communication with a PeriodicTask
  14. Exchanging data with a PeriodicTask
  15. Adding an About Page
  16. Accessing Marketplace from within a Windows Phone Application
  17. Implementing Trial Mode 

Every Live Tile deserves a Windows Phone Application

Over the last week I have been writing about Live Tiles in Windows Phone Mango, how you can create Secondary Live Tiles and how you can display information on the back of Live Tiles and periodically change that information. There is more to write about Live Tiles, but I think it is time to change the topic slightly.

In part 4 of the Live Tile mini series, I introduced an application that adds a Secondary Tile to the Start Screen of your phone. That application is now almost finished in its first version. This free application has a Secondary Tile, it contains an AdControl, deals with location awareness and periodically updates the Secondary Tile. It also can access Marketplace, both to submit a review for the application and to display other applications that are published by me. All in all it is a complete application, yet its functionality is very simple. It is simple enough to explain it almost entirely. That is exactly what I am planning to do over the upcoming weeks.

Initially, the application makes use of code behind. In a later version it will be changed, making use of MVVM and Unit Testing. The application will also act as a sample to show profiling, debugging background agents and many more topics. I will combine blog entries and videos to show how to create this application, how to test it and hopefully how to publish it to Marketplace. As soon as the application is available for download, I will let you know in this blog entry. Here is a sneak preview of EvenTiles.

dump1This application is very simple, yet it contains lots of functionality that you can use inside a Windows Phone application. When the application is started, it checks if a Secondary Tile exists. Actually, it can even be started by clicking on its Secondary Tile when available. If no Secondary Tile is pinned to the start screen, the user has the option to create a Secondary Tile and automatically pin it to the Start Screen. When the Secondary Tile is already pinned on the Start Screen, the user has the possibility to remove it from the Start Screen. You can also see that the application has advertisements. In order to allow for localized advertisements, the application reads the current location of the device once (if the user allows doing that). The application has a Settings Page that can be reached through the ApplicationBar as well as an About Page. To preserve data, the application makes of of Isolated Storage. To transfer data between the application and its background agent, a file in IsolatedStorage is used that is protected by a Mutex. So even though the application itself is very simple, it contains many pieces of functionality that you can use in very complex applications as well. As such, this application is hopefully a starting point that allows you to develop fantastic Windows Phone Applications. Stay tuned for the first part of EvenTiles from Start to Finish – Part 1, which shows you how to create the initial solution and how to create a Secondary Live tile.

Where is that Mutex?

In the continuous story of Live Tiles I wanted to write about updating the Application Tile by using a PeriodicTask. This is a very nice way to update the tile without having to make use of a remote service. However, the PeriodicTask needs to get some data that is available in my application. The way to go is to store that data in a file in IsolatedStorage in the application and have the PeriodicTask retrieve the data from that same file, since it has access to IsolatedStorage.

Since the application might update data that the PeriodicTask needs and since both of them are executing independently from each other, it is a good idea to protect the data by means of a synchronization object. The documentation for Background Agents even suggests using a Mutex for this purpose.

And this is where the fun started for me. I tried to create a Mutex inside my application, and time and again I ran into an issue. The Mutex object was clearly unknown in my application, even though I did add a using directive for System.Threading.

image

It took me quite some time to figure out what was going on here, especially since the PeriodicTask that I was perfectly capable of using a Mutex. Both are Windows Phone projects, both have access to more or less the same namespaces. And yet, there was this difference in recognizing a Mutex object.

image

Taking another look at the documentation for the Mutex did not really help me, although it should have helped me, because there is a hint in the documentation that I completely missed.

image

Even though I was reading the above documentation several times, I didn’t get it. I know I had access to the System.Threading namespace and I still could not use the Mutex. So I started searching for a solution on the Internet and I was not really successful in that, although I got the indication that folks are using Mutex objects in Windows Phone Mango applications. All in all I guess I wasted at least one hour when I decided to compare references to assemblies in both the application and the PeriodicTask projects. Here I found one subtle difference.

image

The difference between the two projects is a reference to mscorlib.extensions. After adding a reference to that assembly in my application’s project, I could use the Mutex. Of course it simply comes back to reading the documentation, because it does indicate that the necessary assembly is mscorelib.extensions (in mscorlib.Extensions.dll). Ignoring that one little sentence delayed me for at least one hour. Hopefully you don’t fall in the same trap.

Where did my ads go?

Since a few weeks, Windows Phone developers can retrieve data on crash counts and stack traces for each published application through the App Hub. Because two of my applications indeed showed a few crash counts, it was of course time to fix the issues and to update the applications. One of those applications, ClickerLite, uses the AdControl to display advertisements inside the application. Besides fixing bugs, I also built the application against the latest version of the Windows Phone SDK. Instead of having to download and use a separate assembly to enable (Microsoft Advertising pubCenter) ads, the Microsoft Advertising SDK for Windows Phone is now part of the Windows Phone SDK. Of course this makes it easier to use the AdControl with full designer support in both Visual Studio 2010 and in Expression Blend 4.0. However, when I started to test my application, the AdControl was not visible, even though I did set the control up to receive test ads.

ClickerLiteDesignerView

As often, the solution to the problem was easy, although it took me some time to find it. I simply needed to add the ID_CAP_MEDIALIB capability to my application’s manifest file. In the previous version of the Advertising SDK, this capability was not required and therefore not included in the manifest file. The end result was test advertisements showing up in the Visual Studio 2010 designer. However, when running the application (both in the emulator and on a real device), the test advertisements did not show up. This of course was also a clear indication that real advertisements would not show up in a released version of the application.

Adding ID_CAP_MEDIALIB solved the problem, the test ad showed up during testing, and the application was ready to be updated.

On a side note, if you are curious about ClickerLite, 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.

Modifying existing Silverlight Controls

During development of a brand new Windows Phone 7 application, I ran into a dilemma. The application is a game in which the user needs to memorize a number of fields. After the playing board has been displayed for a limited amount of time, the user needs to find particular fields by clicking on them. The playing board looks like this:

Screen1 

The different squares that are part of the playing board follow the theme color that the user currently has selected on the phone. Since the user needs to be able to click on the different squares, it is necessary to deal with some form of hit testing. In my initial approach I decided to build the different squares as Silverlight Rectangles, all hosted in an individual row / column inside a Grid control. Each time the user hits one of those squares, something has to happen to its appearance. In my first attempt (when creating a quick and dirty prototype), I decided to subscribe to the MouseLeftButtonDown and MouseLeftButtonUp events since Rectangles do not implement Click events. By handling both button down and button up events and capturing the mouse in between a button down and a button up event sequence, I made sure to have both events acting on the same Rectangle. Even though this approach is feasible, it takes a lot of code, just to make sure that a proper click is recognized on a Rectangle. Since this game needs to react very fast on user input, I want to execute as little code as possible to recognize which Rectangle is currently selected by the user. Also, I want to write as little code as possible, and the whole mouse capturing in combination with some different actions that need to be done on the user ‘clicking’ a Rectangle got me into writing more and more code. Until of course I realized that it was time to do some thinking and to make use of the power of Silverlight, extending existing controls and ‘good old object oriented programming’. What if I could make use of a Button control? Silverlight Buttons do expose Click events, the Button takes care of low level MouseLeftButton handling and contain lots of other functionality. In fact, Buttons contain too much functionality for the different items of my playing board. If you take a look at the Button documentation, you can see the different button styles and all different visual states, including animations that are used to move from one visual state to another. For my particular need, this is way too much functionality. So what if I can limit the functionality of a button (to only display a colored square and to expose a Click event)?

PlayButton – A very simple derived and restyled Silverlight Button

I started by creating a new Windows Phone Class Library to an existing solution in Visual Studio 2010. This Class Library contains my PlayButton class, that simply derives from Button. Replacing the original Rectangle controls on my playing board by PlayButton controls gave the following result:

Screen2

 

Surely, the Rectangles are replaced by PlayButtons. Because PlayButton derives from Button without modifying anything, a PlayButton is simply a Button. This is the reason why a border is shown and why the theme color of the original Rectangles is lost. It also means that there are placeholders for Content and it is possible to act on Click events. However, each time a button is clicked it is going through a number of state transitions, potentially slowing down users that want to play this particular game. To overcome these issues, I created a brand new control template, including a default style to define and render my PlayButton. In order to work properly, the default style needs to be defined in a file called ‘generic.xaml’ that should be stored in a Folder called “Themes” inside the project that hosts the user control. In this particular case, my Visual Studio 2010 solution looks like this:

SolutionExplorer

 

Instead of creating a new user control, including a control template and a default style, I could also have taken an alternative approach, using Expression Blend to create and modify a copy of the existing Button Control style and store the new style as resource in my Windows Phone application or in the Windows Phone application page where the style will be used. This approach is a little bit easier. I did chose to create a new default style for this particular application because I might want to re-use the PlayButton for a few other applications as well. The style I am using for the PlayButton defines a BorderControl that takes the Background and the Opacity that are defined for Button controls. The Background defaults to a PhoneAccentBrush, allowing the PlayButton to be theme aware. Here is the complete XAML for the PlayButton (definied in generic.xaml):

  1. <ResourceDictionary xmlns="http://schemas.microsoft.com/client/2007&quot;
  2.                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  3.                     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  4.                     xmlns:src="clr-namespace:ClickerControls"
  5.                     xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
  6.     <Style TargetType="src:PlayButton">
  7.         <Setter Property="Width"
  8.                 Value="100" />
  9.         <Setter Property="Height"
  10.                 Value="100" />
  11.         <Setter Property="Margin"
  12.                 Value="2" />
  13.         <Setter Property="Background"
  14.                 Value="{StaticResource PhoneAccentBrush}" />
  15.         <Setter Property="Opacity"
  16.                 Value="0.5" />
  17.         <Setter Property="Template">
  18.             <Setter.Value>
  19.                 <ControlTemplate TargetType="src:PlayButton">
  20.                     <Border x:Name="RootElement"
  21.                             Background="{TemplateBinding Background}"
  22.                             Opacity="{TemplateBinding Opacity}">
  23.                     </Border>
  24.                 </ControlTemplate>
  25.             </Setter.Value>
  26.         </Setter>
  27.     </Style>
  28. </ResourceDictionary>

As you can see in the XAML, both the style and the control template specify the control for which they are intended (being src:PlayButton). All that is left to do is setting the DefaultStyleKey to refer to the default style for the control.

  1. public class PlayButton : Button
  2. {
  3.     public PlayButton()
  4.     {
  5.         DefaultStyleKey = typeof(PlayButton);
  6.     }
  7. }

This is all there is to do to create a PlayButton which inherits Click events from a Button Control. The PlayButtons look identical to the original Rectangles, but they are simpler to use inside this particular application.

Screen1

 

Hopefully, this blog entry helps you making a decision on re-using existing Silverlight controls. You can give existing controls a completely new look and feel by applying new styles. Often you might be thinking about adding functionality to existing controls or adding behavior to existing controls. However, it is also completely valid to limit existing behavior on controls, just like this example shows. The PlayButton acts on Click events, but the PlayButton itself will not give visual feedback when it is clicked or when the PlayButton is disabled. So it is really up to you to get all the functionality you want. In my opinion, Silverlight is extremely powerful in allowing you to alter the appearance of existing controls or create new controls based on existing controls. I get more excited by the day that this Silverlight based programming model is one of the two different technologies that you can use to develop applications for Windows Phone 7.