Tag Archives: WP7

Delight

When the Windows Phone 7 ad campaign started airing, I unfortunately  misunderstood the message.  I thought the point of the campaign was that Microsoft was coming out with a new device that would captivate consumers so thoroughly they would abandon their quotidian activities to use it.  I was also moved by Microsoft’s apparently willingness to make fun of themselves about how good their product would be – a product so wonderful it would stop traffic and so sexy it would pull men away from their lovers.

The final voice over, however, thoroughly confused me.  “A phone to save us from our phones.” 

It actually took me a few weeks before I realized that Microsoft was making a completely different kind of play.  They were claiming to understand smartphones while their competitors, Google and Apple, did not.  Smartphones, it turns out, aren’t supposed to enchant, bind and compel.  They are, according to Microsoft marketing, primarily functional devices intended as content delivery systems.  They are, in effect, the hardware equivalent of Sharepoint.

For me this is a problem with Microsoft messaging and not with Windows Phone itself.  These are delightful commercials that spread an insidious and misguided philosophy emphasizing functionality over experience. 

But isn’t that the Microsoft philosophy that was supposed to have died when Windows Mobile was replaced with Windows Phone? Windows Mobile was an expensive tool.  Windows Phone is an expensive toy.  And the most successful smartphone toy is the one that a room full of children want to pick up and play with because it enchants them, it binds them, it delights them.

I don’t claim to fully understand the experience of delight but I have a strong instinct that Microsoft marketing does not appreciate it despite the lengths to which they go to talk about it. 

Delight, for me, is not about utility but rather concerns itself with superfluity.  And while there is a current trend against “distraction” in the UX world, something delightful should at least make us tarry.  Even better it should make us wonder.  It should have a minimum of functionality but a vast degree of intricacy.  It should emphasize this with depth rather than magnitude – that is, it should be small and rich rather than provide a long feature list of things it can do.

Most of all, something delightful shouldn’t have to be explained.  This is, nevertheless, what I will attempt to do in this post – to explain what delight is. 

I will do this, however inadequately, by culling examples from various arts: food, film, poetry, and tactile art.  I won’t try to tie any of this directly to the design of smartphone devices or the development of smartphone apps, but all the same expect that these analogies will be apparent to the reader.

My main thesis is that there are four important elements to delight: superfluity, delicateness, enchantment and intricacy.  These are all, moreover, elements completely within the grasp of the Windows Phone developer and which the Windows Phone Metro style will support, if used correctly.

It might be more straightforward to say, however, that these are some of the things that delight me and I’d like to share them with you.

 

Superfluity

Something which delights is received as a gift.  It is given freely and nothing is expected in return for it.  It also has no purpose other than itself.  The scent of a flower does not delight because the smell is useful to us or because it enables us to smell.  The delightful thing does not enable anything.  It is purposeless. 

Even Aristotle, as practical as any philosopher can be, said of the origins of the useless arts,

“… as more arts were invented, and some were directed to the necessities of life, others to recreation, the inventors of the latter were naturally always regarded as wiser than the inventors of the former, because their branches of knowledge did not aim at utility.”

Useful things always serve another purpose.  Useless things are an end in themselves and are just for us.  This sense of our own specialness is essential to the experience of delight.

 

Delicacy

In finer restaurants around the world, there is a course known as the amuse bouche.  It is typically a one-mouthful dish selected by the chef and delivered to his guests.  It also will typically not ever appear on the bill.  It is a gift intended simply to “delight-the-mouth” as well as the mind.

amusebouche1

Presentation is always impeccable.  The game for the chef is to pack as much visual and flavorful complexity as he can into a small package.

Salmon-Amuse-Bouche_6

One of the finest I’ve ever had was a fresh oyster in a half-shell with a tiny square of green, absinthe jello placed on top.

amuse2

The miniature size is essential to the effect not only because it establishes a rule within which the chef must operate (only a single mouthful of food) but also because of the inherent delight we experience when we encounter the small.  Large meals make us full.  Large pieces of art evoke a sense of the sublime.  Large works of poetry stay with us and cannot be shaken.  The amuse bouche, on the other hand, simply leaves behind a sense of happiness and gratitude.

 

Enchantment

Enchantment has become an overused word, as have all the synonyms we might use in its place: magic, uncanny-ness, wonderment.  The purpose of enchantment is to lift us out of our own sense of being.  For just a moment time stops, goals are put aside, and we are allowed to simply be.  The delightful object puts the real world aside and provides a space for us to rest from it.

This notion of enchantment was at the heart of the 19th century Romantic movement in poetry.  In his preface to the Lyrical Ballads, Wordsworth wrote of the new poetry he and Coleridge were devising,

“The principal object, then, proposed in these Poems was to choose incidents and situations from common life, and to relate or describe them, throughout, as far as was possible in a selection of language really used by men, and, at the same time, to throw over them a certain colouring of imagination, whereby ordinary things should be presented to the mind in an unusual aspect.”

One of my favorite film-makers, Jean Cocteau, was himself a poet and novelist who – almost uniquely – brought this unique sensibility to his movies.  The techniques of visual poetry he improvised have over time become part of the common idiom of filmmaking.  No one, however, has ever quite been able to replicate the sense of the uncanny he created in films such as La belle et la bête or Orphée.

Watch, for instance, the arrival of Belle to the Beast’s castle. 

The techniques are simple – people with their arms poked through a wall, slow motion filming, and a rolling palette upon which Josette Day is pulled forward.  By pulling all these effects together, however, Cocteau was able to create something light and otherworldly.

Here is another effect Cocteau originally attempted in his film from the 30’s Le Sang d’un Poete but didn’t get right until Orphée.  It is an adult play on Lewis Carroll’s Through the Looking Glass.  My favorite line: “It is not about understanding.  It’s about believing.”

 

Intricacy

A key notion in UX is discoverability.  Something should always be left to the end-user to discover on their own.  Discovery is a way for users of an experience to make the experience their own.  They form an emotional connection with devices and experiences that are discoverable and achieve a sense that the object of delight is for them because they are the ones who figured it out.

Dan Ohlmann is an artist whose works are exhibited at the Musée des miniatures et des décors de cinéma in Lyons. 

IMG_32321

His talent is not just in mastering the art of the small, but in perfecting the attention to detail needed to enchant his audience and keep them riveted to one spot.

lyon-miniatures-library

1242746618

I feel like I could step into one of these dioramas at any time and will find a full world in miniature simply by stepping through the door at the back of the piece.

Post_0138_07

Dan Ohlmann’s art always hints at there being more just around the corner – a whole new world yet to be discovered.

IMG_3397

Windows Phone 7 Side Loading

Side loading is a topic familiar to Windows Phone developers but not so familiar to those who might need to work with these developers and require an understanding of the functionality in order to be more effective.

Side loading refers to deploying applications directly to a device without going through the official Microsoft Marketplace. You may want to side load an application for prototyping, demos and reviews. 

In an enterprise environment, you may additionally want to side load applications that are intended only for internal consumption. Unfortunately, an enterprise solution is not available for the first iteration of Windows Phone. It may be included in a future release.

The side loading capabilities of Windows Phone 7 are somewhat restrictive. You may side load applications either to a software emulator running on a PC or to a physical device. Side loading to the WP7 software emulator requires the installation of the Windows Phone Developer Tools. In addition to various products (Visual Studio Express, Blend for WP7), the Windows Phone Developer Tools includes the Application Deployment utility which you will use for side loading. You must be running Windows Vista or Windows 7 in order to install the Developer Tools.

The Windows Phone Developer Tools may be downloaded here.

Side loading to a Windows Phone device additionally requires installation of the latest Zune software.

The Zune software may be downloaded here.

Deploying to a WP7 device is similar to deploying to the WP7 emulator. Besides the requirement that Zune software be running in order to deploy to a device, there is an additional restriction that you can only deploy to an “unlocked” developer device. A Marketplace account is required to unlock a WP7 device, and only five three developer devices can be unlocked for each marketplace account. A Marketplace account requires an annual membership fee of $99. A full membership, allowing for the publication of applications to the marketplace, can be purchased here and generally requires a two to three week verification period. Finally, only ten applications may be side loaded onto any device.

Deploying to the Emulator

Once the Windows Phone Developer Tools have been successfully installed, you may side load to the emulator by using the Application Deployment utility. You can find the Application Deployment utility by going to your Start Menu on the taskbar.

taskbar

Select “All Programs” from the Start Menu. Find and open the menu folder named Windows Phone Developer Tools.

admenu

This will open the Application Deployment utility.

ad

The Target dropdown has two entries. From the Application Deployment utility, apps can be deployed either to the emulator or to a device. To deploy to the emulator, select “Windows Phone 7 Emulator” as the target.

You will be deploying a XAP file, which is a file with a “.xap” extension. A XAP file is the basic unit for a phone application, much as an executable is the basic unit for a typical windows application. It includes the code as well as all the images and other assets required to run a specific phone application. Use the browse button to find the XAP file you want to deploy to the emulator.

Once a XAP file has been selected, press the “Deploy” button. If the emulator is not already running, deployment will start the emulator for you.

The emulator is a bare-bones version of the Windows Phone OS. It has most of the functionality found on a Windows Phone device but is lacking many of the applications you will typically find on a standard WP7 device. In fact, the Start screen on the emulator only contains Internet Explorer.

wp7startscreen

Select the right facing arrow at the top right corner to bring up all applications. You will find your newly loaded app on the applications screen.

Deploying to a Windows Phone

Once the WP7 Dev Tools and the Zune software have been successfully installed, you must run the Zune software before attempting to side load. You do not need to be logged into your Zune account in order to side load an app.

zune

While the Zune software is running, open the Application Deployment utility by following the steps enumerated above for side loading to the software emulator.

As pointed out above, the device must be “unlocked” as a developer device in order for deployment to occur.  The device does not have to be unlocked by you.  Hypothetically, you can simply ask someone with an annual Marketplace subscription to unlock the device for you.

Connect your device to your PC using a micro-USB cable (typically included with the device). The lock screen must be slid out of the way for deployment to occur.

In order to deploy to your device, you will select “Windows Phone 7 Device” as the deployment target in the Application Deployment utility rather than “Windows Phone 7 Emulator”.

To finish deploying to an unlocked device, follow the steps outlined above for deploying to the emulator.

* Special thanks to WP7 MVP Joel Johnson for reviewing this document and making necessary corrections to my understanding of how side loading works.

Telerik RadControls for Windows Phone: First Look

Telerik has been quick to fill in some of the gaps in Windows Phone development with the new RadControls for Windows Phone.  They made a similar move previously with their support for ASP.NET MVC and, going back even further, jumped in earlier than most control suite developers when Silverlight first came out.  Jumping onto new technologies in this is always a risky proposition – and I am grateful to Telerik for repeatedly doing this.  I truly hope it pays off for them.

While the Windows Phone platform was still in CTP and Beta, the main course for extending the control library was to incorporate open and proprietary projects such as the Silverlight 3 Toolkit, Silverlight 3 SDK, and Silverlight Contrib.  This usually worked but there were always issues with making everything play smoothly. 

As the marketplace rules were released, it also became evident that all controls would have to be compiled against the WP7 runtime, which made things just slightly hairier.  Eventually Microsoft released its own official Silverlight Toolkit for Windows Phone, which provides the most requested UI components: a Pivot Control, Panorama Control and Date and Time Pickers which are consistent with the other native apps built for the phone.

The RadControls for Windows Phone has some overlap with the Silverlight Toolkit for WP7 – no doubt due to fluctuating expectations about what actually would be provided in the Microsoft Toolkit and what would be most useful in a suite.  Duplications include the Date and Time Pickers, Picker, and the Wrap Panel.

The UniformGrid, DockPanel, and Window controls are found in RadControls but not in the Toolkit.  Window is probably one of the most useful of these controls.  It has functionality similar to the ChildWindow control from the Silverlight 3 SDK and allows us to build modal windows – very useful when a MessageBox will not suffice and especially when a phone application requires an initial login – the tales of woe surrounding building an initial login that complies with the Marketplace rules are legendary.  Telerik also continues a tradition of porting nice-to-have WPF functionality to Silverlight.  The standout in their phone suite is the LayoutTransform control which allows us to use Layout Transforms instead of just Render Transforms (for an illustrative example of the difference, see Charles Petzold’s blog entry).

For those having trouble with page transitions, Telerik provides assistance with their implementation of the PhoneApplicationFrame.  There has been a technique going around the internet involving cannibalizing the Silverlight 3 Toolkit and customizing the default PhoneApplicationFrame in order to set all page transitions from one location.  Telerik has simplified the process by providing their own implementation.

The RadControls are still in Beta and I know better than to judge the final work by any issues I find in the preview.  That said, the RadControls for Windows Phone examples seem remarkably and pleasantly performant – especially the page transitions. 

Telerik’s RadControls for Windows Phone are a great addition to the Windows Phone ecosystem.  Telerik is definitely on the right track and their controls provide what any Phone developer would want – an easier way to build interesting and attractive WP7 applications with tools to make development go faster.

Back-Chaining in WP7

Customizing App.xaml.cs

The Windows Phone 7 navigation system has certain limitations from a development perspective.  Chief among these are an inability to inspect the navigation backstack, an inability to remove items from the backstack, and an inability to navigate multiple pages on the backstack.

Because we are only able to programmatically back-navigate one page at a time, a technique has been devised in the developer community called back-chaining.  Back-chaining simply involves setting certain flags in your pages so that, if anyone ever backs into the page, it will continue to navigate backwards.  In this way, we can chain several back navigations together until we arrive at the page we want to stop at.

Here is a basic implementation that forces any back-navigation to always return to the first page in an application when this code is placed in every PhoneApplicationPage:

bool done;

protected override void OnNavigatedTo(
        NavigationEventArgs e)
{
    if (done && NavigationService.CanGoBack)
        NavigationService.GoBack();
}

protected override void OnNavigatedFrom(
    System.Windows.Navigation.NavigationEventArgs e)
{
    done = true;
}

Instead of repeating this code in every page, however, we can centralize it in the App class.  Additionally, we can provide extra methods for more complex navigation such as going back a certain number of pages or going back to a particular page wherever it is on the backstack.

We can do all of this from the App class because of an event on the PhoneApplicationFrame called Navigated that allows us to centrally hook into every navigation event in our applications.

In the default Windows Phone Application template, the PhoneApplicationFrame is instantiated in the App.InitializePhoneApplication method in the App.xaml.cs file.  We can declare our new handler for the event somewhere in there:

//boilerplate code
RootFrame.Navigated += CompleteInitializePhoneApplication;
//new code
RootFrame.Navigated += RootFrame_Navigated;

Next, we need to create some infrastructure code.  For convenience, we want to use static methods and properties in order to make our methods accessible off of the App class.  App.Current, which can be called from anywhere in your application, will return an Application type, which is the base class for App.  Consequently, to access the App class’s RootFrame property (which is boilerplate if you use one of the default project templates), you have to write code like this:

var rootFrame = ((App)App.Current).RootFrame;

A static member of the App class, on the other hand, can conveniently be called like this:

App.DoSomething();

Because we are spreading logic between several page navigations and consequently several calls to RootFrame_Navigated, our infrastructure will need to keep track of what we are trying to accomplish between all of these navigations.

The current implementation will include five methods for back navigation, a simple GoBack, GoBack for a number of pages, GoBack to a named page, GoBack to the first page, and GoBack past the first page.  The last is equivalent to exiting the application (it also doesn’t work, by the way, and I’ll talk more about that later).

Here is the implementation for the first back navigation — which is simply a standard one page back navigation placed in a more convenient place – as well as a property to expose CanGoBack:

public static void GoBack(string pageName)
{
    CurrentMode = GoBackMode.BackToPage;
    BackPageStop = pageName;
    GoBack();
}

private static bool CanGoBack
{
    get
    {
        var navFrame = App.Current.RootVisual
            as PhoneApplicationFrame;
        return navFrame.CanGoBack;
    }
}

GoBack can now be called from anywhere in a Silverlight application like this:

App.GoBack();

Our infrastructure code also requires an enum to keep track of these navigation types:

private enum GoBackMode
{
    Default = 0,
    BackNumberOfPages,
    BackToPage,
    Home,
    Quit
}

private static GoBackMode CurrentMode 
{ get; set; }

To implement going back a given number of pages, we will create a static property to track how many pages we need to go back and expose a method to start the GoBack chain:

private static int GoBackPageCount
{ get; set;}

public static void GoBack(int numberOfPages)
{
    CurrentMode = GoBackMode.BackNumberOfPages;
    GoBackPageCount = numberOfPages;
    GoBack();
}

The magic is what happens in the RootFrame_Navigated method, which is triggered every time we arrive at a new page in the application.  We check to see how many pages we have traversed through the backstack.  If we have gone far enough, we stop.  If not, we call App.GoBack():

static void RootFrame_Navigated(object sender
    , NavigationEventArgs e)
{
    switch (CurrentMode)
    {
        case GoBackMode.BackNumberOfPages:
            if (CanGoBack && --GoBackPageCount > 0)
            {
                GoBack();
            }
            else
                CurrentMode = GoBackMode.Default;
            break;

The setup code for going back to a named page tracks the targeted page name rather than the number of pages traversed:

private static string BackPageStop
{ get; set;}
public static void GoBack(string pageName)
{
    CurrentMode = GoBackMode.BackToPage;
    BackPageStop = pageName;
    GoBack();
}

The code fragment in the switch statement in RootFrame_Navigated parses the name of the page we have arrived at (e.Content returns the full class name along with its namespace but does not return the “.xaml” extension) and then compares it against the page we are trying to reach:

case GoBackMode.BackToPage:
    var pageName = e.Content.ToString();
    var periodPosition = pageName.LastIndexOf(".");
    if (periodPosition > -1)
        pageName = pageName.Substring(periodPosition + 1);
    if (CanGoBack && pageName != BackPageStop)
        GoBack();
    else
        CurrentMode = GoBackMode.Default;
    break;

The syntax for returning to MyPhoneApplication.Page1.xaml looks like this:

    App.GoBack("Page1");

If there are multiple instances of Page1 on the backstack, this implementation will stop at the last one.  If Page1 does not exist on the backstack, the routine will not stop until it finds the first page of the application.

GoHome is fairly straightforward.  It continues stepping backwards until the CanGoBack property returns false.  CanGoBack returns false on the first page of the application but returns true for every other page:

public static void GoHome()
{
    CurrentMode = GoBackMode.Home;
    GoBack();
}
    case GoBackMode.Home:
        if (CanGoBack)
            GoBack();
        else
            CurrentMode = GoBackMode.Default;
        break;

Finally, it would be really nice to be able to implement a Quit method.  Hypothetically, we could just navigate past the first page of an application to exit.  Taking advantage of the infrastructure we have written, the code would look like this:

public static void Quit()
{
    CurrentMode = GoBackMode.Quit;
    GoBack();
}
    case GoBackMode.Quit:
        GoBack();
        break;

Sadly, however, this doesn’t work. We cannot programmatically back navigate past the first page of an application.  When we try, the navigation is automatically cancelled and a NavigationFailed error is thrown. 

Since back-chaining as an exit strategy does not work, an alternative way to exit a Silverlight application is outlined here: How to Quit a WP7 Silverlight Application .  Unfortunately, the marketplace guidelines say that an application cannot have unhandled exceptions.  I’m not currently clear on whether this would apply to throwing an exception that is understood an controlled (hence handled) but at the same time intentional.

A word of caution:  Back-chaining causes flickering, and the more pages you navigate through, the worse the flickering gets.  This is because every page tries to display itself as you navigate past it.   A quick fix for the flickering problem is to set the RootFrame’s Opacity property to zero when you begin and complex back navigation and then set it back to one when you complete the navigation [thanks go to Richard Woo for pointing this out to me.]

For copy/paste convenience, here is the entire back-chaining code base:

RootFrame.Navigated += RootFrame_Navigated;
#region go back methods

private enum GoBackMode
{
    Default = 0,
    BackNumberOfPages,
    BackToPage,
    Home,
    Quit
}

private static GoBackMode CurrentMode 
{ get; set; }

public static void GoBack()
{
    var navFrame = App.Current.RootVisual
        as PhoneApplicationFrame;
    navFrame.GoBack();
}

private static void ShowRootFrame(bool show)
{
    var navFrame = App.Current.RootVisual
        as PhoneApplicationFrame;
    if (show)
        navFrame.Opacity = 1;
    else
        navFrame.Opacity = 0;
}

private static int GoBackPageCount
{ get; set;}

public static void GoBack(int numberOfPages)
{
    CurrentMode = GoBackMode.BackNumberOfPages;
    GoBackPageCount = numberOfPages;
    ShowRootFrame(false);
    GoBack();
}

private static string BackPageStop
{
    get;
    set;
}
public static void GoBack(string pageName)
{
    CurrentMode = GoBackMode.BackToPage;
    BackPageStop = pageName;
    ShowRootFrame(false);
    GoBack();
}

private static bool CanGoBack
{
    get
    {
        var navFrame = App.Current.RootVisual
            as PhoneApplicationFrame;
        return navFrame.CanGoBack;
    }
}

public static void GoHome()
{
    CurrentMode = GoBackMode.Home;
    ShowRootFrame(false);
    GoBack();
}

public static void Quit()
{
    CurrentMode = GoBackMode.Quit;
    ShowRootFrame(false);
    GoBack();
}

static void RootFrame_Navigated(object sender
    , NavigationEventArgs e)
{
switch (CurrentMode)
{
    case GoBackMode.BackNumberOfPages:
        if (--GoBackPageCount > 0 && CanGoBack)
        {
            GoBack();
        }
        else
        {
            ShowRootFrame(true);
            CurrentMode = GoBackMode.Default;
        }
        break;
    
    case GoBackMode.Home:
        if (CanGoBack)
            GoBack();
        else
        {
            ShowRootFrame(true);
            CurrentMode = GoBackMode.Default;
        }
    break;
    case GoBackMode.BackToPage:
        var pageName = e.Content.ToString();
        var periodPosition = pageName.LastIndexOf(".");
        if (periodPosition > -1)
            pageName = pageName.Substring(periodPosition + 1);
        if (CanGoBack && pageName != BackPageStop)
            GoBack();
        else
        {
            ShowRootFrame(true);
            CurrentMode = GoBackMode.Default;
        }
        break;
    case GoBackMode.Quit:
        GoBack();
        break;

    }
}

#endregion

20, 50, 90, 400 and 2

the-count

There are certain numbers every Windows Phone developer should be familiar with: 20, 50, 90, 400, and 2.

20 MB is the maximum size of a XAP file that can be downloaded over the air.  XAPs larger than this must use Wi-Fi or the Zune desktop app to be downloaded to a device.

50 MB is the maximum size of additional content that can be downloaded after installation to make the application functional.  If more than 50 MB is needed to make the application functional, this must be noted in the marketplace submission and a notification should be provided to the end-user of the fact.

90 MB is the memory usage limit for your app assuming the device has the min-spec 256 MB of RAM.  Of course, another way to look at this is that Windows Phone 7 reserves 166 MB of RAM for itself – your app can use the rest.  If the device has 512 MB of RAM, then your app gets 256 + 90.

400 MB is the max allowable size for your XAP. 

2 Gigs is the total size your app can grow to.  This includes the XAP as well as any data you throw into isolated storage — though some people have proposed that the 2 Gig limit applies only to isolated storage usage.  (If you check the isolated storage quota programmatically, it appears to be unlimited which, obviously, isn’t the case). 

The 2 Gig limit seems to have been lifted.  To read more about this, see the old MSDN forums.

Just another ViewModelBase class

Great developers like Laurent Bugnion, Rob Eisenberg and Rocky Lhotka write Frameworks.

At the opposite end of the spectrum are developers like me.  I write helper classes.  Usually I don’t even do that and simply resort to copy and pasting from text files I have saved all over my harddrive.

In the zip file you will find a ViewModel base class designed specifically for doing MVVM in a Windows Phone Silverlight application.  It can be used with either the Satellite VM pattern or the Anchor VM pattern as described in the Patterns of Windows Phone Architecture series.  It supports Blendability, State persistence, Tombstoning and Xaml-only instantiation.

Also included are the helper classes for saving state described in this post.

Basic usage looks like this:

public class MainViewModel: 
    SerializableViewModelBase<MainViewModel>{}

All the features mentioned above come free simply by inheriting the base class.  Add a property, rinse, repeat.

And here’s the implementation below.  The code in the base constructor takes the currently newed up instance and throws it into the static instance. 

You’ll also note that unlike a typical Singleton implementation, the instance property is not static.  This allows XAML instantiation to work properly.  A protected Singleton property is provided if you want the Instance property to be static in the derived class.  To implement a static Instance property in the derived class, just add one with the new qualifier like this:

public static new MainViewModel Instance
{
    get { return Singleton; }
}

BackupMore and RestoreMore can be overridden to save additional state data that might not get serialized with the ViewModel but belongs with it nonetheless (for instance, private fields that need to be saved off).

InitializeDesigner and InitializeInstance can be overriden to perform any initialization logic.  Since with XAML instantiation using a static Instance can create your object more than once, the base class is written so these two methods are only called on the first instantiation of the singleton.  Additionally, they automatically perform forking logic for instantiation code running in the designer versus instantiation code at runtime.

Your comments and advice are, as always, welcome.

public abstract class SerializableViewModelBase<T>
    : INotifyPropertyChanged
    where T : SerializableViewModelBase<T>, new()
{

    private static T _instance;
    private static object _lockObject = new object();

    /// <summary>
    /// Initializes a new instance of 
    /// the <see cref="SerializableViewModelBase&lt;T&gt;"/> 
    /// class.
    /// </summary>
    public SerializableViewModelBase()
    {
        lock (_lockObject)
        {
            if (IsInstanceEmpty)
            {
                _instance = (T)this;
                Initialize();
            }
        }
    }

    /// <summary>
    /// Gets a value indicating whether 
    /// the singleton instance T is empty.
    /// </summary>
    /// <value>
    ///     <c>true</c> if this instance is empty;
    ///     otherwise, <c>false</c>.
    /// </value>
    protected static bool IsInstanceEmpty
    {
        get { return _instance == null; }
    }

    /// <summary>
    /// Override to perform runtime intialization.
    /// </summary>
    virtual protected void InitializeInstance() { }
    /// <summary>
    /// Override to perform initialization for 
    /// the designer.
    /// </summary>
    virtual protected void InitializeDesigner() { }

    private void Initialize()
    {
        if (DesignerProperties.IsInDesignTool)
            InitializeDesigner();
        else
            InitializeInstance();
    }

    /// <summary>
    /// Gets the singleton instance of type T.
    /// </summary>
    /// <value>The instance.</value>
    protected static T Singleton
    {
        get
        {
            lock (_lockObject)
            {
                if (IsInstanceEmpty)
                    new T();
            }
            return _instance;
        }
    }

    /// <summary>
    /// Gets the singleton instance of type T.
    /// </summary>
    /// <value>The instance.</value>
    public T Instance
    {
        get
        {
            return Singleton;
        }
    }

    private string _title;
    /// <summary>
    /// Gets or sets the Title.
    /// </summary>
    /// <value>The title.</value>
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            OnPropertyChanged("Title");
        }
    }

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (null != PropertyChanged)
            PropertyChanged(this
            , new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    /// Backs up the class instance.
    /// </summary>
    /// <param name="store">The data store.</param>
    /// <returns></returns>
    public static bool Backup(IDataStorage store)
    {
        _instance.BackupMore(store);
        return store.Backup(typeof(T).Name, _instance);
    }

    /// <summary>
    /// Restores the class instance.
    /// </summary>
    /// <param name="store">The data store.</param>
    public static void Restore(IDataStorage store)
    {
        _instance = store.Restore<T>(typeof(T).Name);
        _instance.RestoreMore(store);
    }

    /// <summary>
    /// Override this method to backup additional state.
    /// </summary>
    /// <param name="store">The store.</param>
    protected virtual void BackupMore(IDataStorage store) { }

    /// <summary>
    /// Override this method to restore additional state.
    /// </summary>
    /// <param name="store">The store.</param>
    protected virtual void RestoreMore(IDataStorage store) { }
}

Patterns of Windows Phone Architecture Part III

The Anchor ViewModel pattern described in part 2 of this series is especially well adapted to Hub style layouts where related user controls are organized under a common parent.  For instance, a Pivot Control can have a MainViewModel object assigned to its DataContext.  If the MainViewModel class has properties with additional ViewModels, for example DetailsName, DetailsAddress, and so on, each of these properties can be used as the DataContexts of the Pivot Items contained in it.

Here’s a simple illustration of what that would look like:

<controls:Pivot 
    DataContext="{Binding  
    Source={StaticResource MainVM}}" 
    Name="pivot1" Title="{Binding Title}" 
    >
    <controls:PivotItem 
        DataContext="{Binding DetailsName}"
        Header="{Binding Title}">
        <StackPanel >
            <TextBox Text="{Binding FirstName, Mode=TwoWay}"/>
            <TextBox Text="{Binding LastName, Mode=TwoWay}" />
        </StackPanel>
    </controls:PivotItem>
</controls:Pivot>

Using the tip from Tombstoning Simplified, tombstoning your application only requires a single call in order to save to transient storage not only the MainViewModel but also all of its dependent ViewModels:

private void Application_Deactivated(object sender
    , DeactivatedEventArgs e)
{
    MainViewModel.Backup(new TransientDataStorage());
}

This pattern work less well if your phone application consists of unrelated pages with unrelated view models backing them. 

In order to maintain the one line tombstoning code, you can still have a RootViewModel that consists only of properties for each ViewModel in the application.  The RootViewModel can be assigned to the DataContext of the PhoneApplicationFrame of your application, and each subsequent page in the app can simply have its DataContext bound to the properties of the RootViewModel.

Practically speaking, this is an effective architecture.  It will accomplish everything you need in your app for tombstoning. 

On an aesthetic level, however, I find it displeasing to have unrelated ViewModels dependent on one another.  Additionally, having a super ViewModel, the purpose of which is only to host other ViewModels, makes my eye twitch.

In my own applications I use a different pattern called the Satellite ViewModel pattern.  It complements the Anchor ViewModel pattern and shouldn’t be considered opposed to it.  Each pattern ought to be used where it is most appropriate to do so.

3. Satellite ViewModel

Satellites orbit the earth without any awareness of each other.  Each can be communicated with independently of its fellow crafts.  Where the Anchor ViewModel pattern privileges one object above all others, satellites are all equal with respect to one another.

In order to implement the Satellite View Model Pattern for Windows Phone applications, we will simply take advantage of one of the oldest and best-known design patterns: The Singleton.  In order to make it play well in the Phone environment, however, we will give it a little twist.

The goals of this pattern are:

  1. to preserve state for a View (a PhoneApplicationPage or UserControl) even when the View is out of scope.
  2. to allow fine-grained access to Views as needed
  3. to support easy backup to transient or isolated storage if the application is tombstoned or simply terminated.
  4. to provide an MVVM architecture that is Blendable.

A ViewModel, at minimum, should of course implement INotifyPropertyChanged.  Here is the boiler-plate implementation most people use:

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (null != PropertyChanged)
            PropertyChanged(this
                , new PropertyChangedEventArgs(propertyName));
    }
}

To allow for general access to this ViewModel while preserving state no matter what happens to associated Views, we implement the singleton pattern:

protected static MainViewModel _instance;

private static object _lockObject = new object();
public static MainViewModel Instance
{
    get
    {
        lock (_lockObject)
        {
            if (_instance == null)
                _instance = new MainViewModel();
        }
        return _instance;
    }
}

So far this is pretty standard code.  We’ve even added a standard thread-safety measure with the lock keyword.

The Singleton Pattern (as well as the related Factory Method Pattern) typically implements a private no parameter constructor in order to prevent instantiation using the new() keyword.

We can’t do this for windows phone for two reasons.

First, both Isolated Storage and transient storage to the State object use XML serialization in a partial trust environment.  Consequently, if we want to backup our ViewModels to persistent or transient storage, our ViewModels must have public no param constructors.

Second, in order to make our ViewModels blendable, we also require public no param constructors since Silverlight for Phone does not support referencing static classes in XAML.  The constraints of the Silverlight environment on the phone force us down certain architectural paths and we are obligated to tweak some old tried-and-true patterns in order to create new ones.

In order to support both blendability and serialization, our MainViewModel’s constructor will look like this:

public MainViewModel(){}

It’s awkward, I grant you. 

With respect to serialization, we are required to have a public no param constructor even if it has no code in it.  Furthermore, when the ViewModel is deserialized, the constructor is never actually called (even though we were required to have it).  If you are using a base class for your ViewModels, as many people do, you must also provide a public no param constructor for your base class  (yes! even if it is marked as an abstract base class).

In order to instantiate our ViewModel in XAML and use it as our DataContext, we will add it to our class DataContext attribute using some special syntax. The XAML for assigning a MainViewModel instance to the page’s DataContext looks like this:

d:DataContext="{d:DesignInstance local:MainViewModel,
IsDesignTimeCreatable=True}" 

Instantiating the MainViewModel instance in XAML like this makes our VM blendable.  The point of making the MainViewModel blendable is to be able to visualize how the View and the ViewModel work together.  Additionally, you may want to show data when you are designing the application which you do not want to show when you are actually running the application.  You can handle this in the Constructor method (the one we originally didn’t want to have) for your VM like so:

    public MainViewModel()
    {
        if (DesignerProperties.IsInDesignTool)
        {
            Title = "Design Mode";
        }
        else
        {
            Title = "My Application";
        }
    }

The IsInDesignTool is the magic sauce that tells us whether we are running this code through a designer or in a live application.

On the XAML side, there is an additional chunk of XAML I haven’t shown you yet.  The code presented so far will allow you to instantiate and run code in the designer only.  In order to have VM code that runs in both the designer and at runtime, however, we will set the DataContext again.  This will look like we are duplicating code, but we aren’t really. 

The purpose of this code segment is simply to set the PhoneApplicationPage’s DataContext to the Instance property for the running application as well as the design-time application (for runtime purposes, of course, it isn’t necessary to perform binding in the xaml.  It could just as well be done programmatically in the Page’s constructor):

    <phone:PhoneApplicationPage 
    ...
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DataContext="{d:DataInstance local:MainViewModel,
    IsDesignTimeCreatable=True}" >
    <phone:PhoneApplicationPage.DataContext>
        <Binding Path="Instance">
            <Binding.Source>
                <local:MainViewModel/>
            </Binding.Source>
        </Binding>
    </phone:PhoneApplicationPage.DataContext>
    ...

Now to put in some code for tombstoning.  For this we just require two static methods, one for serializing the VM and one for rehydrating it.  Using the helper classes from here the serialize/deserialize code on MainViewModel looks like this:

private string token = "MainViewModel";

public static bool Backup(IDataStorage store)
{
    return store.Backup(token, _instance);
}

public static void Restore(IDataStorage store)
{
    _instance = store.Restore<MainViewModel>(token);
}

In the App class, we hook into the phone services events to call Backup and Restore for all of our VMs.  The code below assumes that we have three ViewModels we want to save off.  RestorePersistentData and BackupPersistentData are simply custom methods for saving to IsolatedStorage explained in this Tip

They are in this sample code simply to illustrate that any data you want to save off when the application permanently terminates should also be saved off when you prepare your app for tombstoning since there is no guarantee the application will be revived after tombstoning :

private void Application_Activated(object sender
    , ActivatedEventArgs e)
{
    RestorePersistentData();

    var store = new TransientDataStorage();
    TwitterDetailsViewModel.Restore(store);
    ContactsViewModel.Restore(store);
    MainViewModel.Restore(store);
}

private void Application_Deactivated(object sender
    , DeactivatedEventArgs e)
{
    var store = new TransientDataStorage();
    MainViewModel.Backup(store);
    ContactsViewModel.Backup(store);
    TwitterDetailsViewModel.Backup(store);

    BackupPersistentData();
}

private void Application_Launching(object sender
, LaunchingEventArgs e)
{
    RestorePersistentData();
}
       
private void Application_Closing(object sender
    , ClosingEventArgs e)
{
    BackupPersistentData();
}

To summarize, the Satellite ViewModel – which is really a somewhat deviant mixing of the Singleton pattern and the ViewModel pattern to make them work on the Phone – is intended to accomplish four goals:

  1. Support a stateful phone application architecture.
  2. Allow easy accessibility to ViewModels.
  3. Facilitate tombstoning scenarios.
  4. Provide a Blendable ViewModel pattern.

If you don’t like some of the jury-rigging required to make the above code work, I would highly recommend you look at Laurent Bugnion’s ViewModel Locator pattern: http://www.galasoft.ch/mvvm/getstarted/ .  As of this writing, the MVVM Light ViewModel base class doesn’t deserialize correctly because it doesn’t have a public no param constructor.  To work around this, you simply have to copy the BaseViewModel class into your own implementation and add a constructor.

[Note: this code was cleaned up on 10/17/10 to use the DataInstance extension for design time binding to the DataContext.  Many awkward issues regarding instantiation go away by using this syntax.]

WP7 Tip: tombstoning simplified

In order to prepare your phone app to go into tombstone mode (to make it tomb-worthy) it is necessary to save off state data associated with your app.  My preference is to simply save off view models – but you may want to also save off model objects or even individual field values.

There are two dictionaries for doing this. 

IsolatedStorageSettings.ApplicationSettings is available to save persistent data between runs of the application (whether the application gets tombstoned or simply gets closed down).

PhoneApplicationService.Current.State allows one to save and restore data when the application gets tombstoned.  It is handy if we only want to save off data temporarily – for instance if we do not need it for a fresh run of the application. 

Since State and ApplicationSettings are both dictionaries that automatically handle serialization and deserialization for us, much of the underlying code we are required to write when using them is also very similar.

In my own applications, I use a set of utility classes to ease saving and restoring my application state.

Since I generally only want to use State and ApplicationSettings to save and restore data, I encapsulate the plumbing behind a very simple interface.

    public interface IDataStorage
    {
        bool Backup(string token, object value);
        T Restore<T>(string token);
    }

The concrete classes aren’t particularly sophisticated.  I use this for transient data storage:

    public class TransientDataStorage: IDataStorage
    {

        public bool Backup(string token, object value)
        {
            if (null == value)
                return false;

            var store = PhoneApplicationService.Current.State;
            if (store.ContainsKey(token))
                store[token] = value;
            else
                store.Add(token, value);

            return true;
        }

        public T Restore<T>(string token)
        {
            var store = PhoneApplicationService.Current.State;
            if (!store.ContainsKey(token))
                return default(T);

            return (T) store[token];
        }
    }

And this for isolated storage:

    public class PersistentDataStorage: IDataStorage
    {

        public bool Backup(string token, object value)
        {
            if(null == value)
                return false;

            var store = IsolatedStorageSettings.ApplicationSettings;
            if (store.Contains(token))
                store[token] = value;
            else
                store.Add(token,value);

            store.Save();
            return true;
        }

        public T Restore<T>(string token)
        {
            var store = IsolatedStorageSettings.ApplicationSettings;
            if (!store.Contains(token))
                return default(T);

            return (T) store[token];
        }
    }

You’ll notice that the only real difference between these two code segments is that I need to call Save for isolated storage but do not have to for State updates.

Now when I need to save to isolated storage I simply call:

    var store = new PersistentDataStorage();  
    store.Backup("token", myObject);

While a transient save to State is simply:

    var store = new TransientDataStorage();  
    store.Backup("token", myObject);

No sticky kids mess afterwards.

I like having an interface as it allows me to throw some methods on the VMs themselves:

public static bool Backup(IDataStorage store)
{
    return store.Backup("MainViewModel", this._instance);
}

public static void Restore(IDataStorage store)
{
    this._instance = store.Restore<MainViewModel>("MainViewModel");
}

In this case, each VM is responsible for what actually gets saved to storage: for instance, we might want to save off the VM as well as the  associated model object. 

Whether this state is saved off to IsolatedStorage or State, however, gets determined elsewhere – generally in the ApplicationService lifecycle events: Launching, Closing, Activated and Deactivated.

WP7 Tombstoning Pattern Tip

Customizing App.xaml.cs

If you are familiar with tombstoning on Windows Phone, you know there are four events in the Windows Phone application lifecycle that can be handled: PhoneApplicationService.Launching, PhoneApplicationService.Closing, PhoneApplicationService.Activated and PhoneApplicationService.Deactivated.  The first two are for normal app startup and shutdown, while the latter two are for tombstoning scenarios.

Along with these events are two different property bags that application data can be saved to. 

IsolatedStorageSettings.ApplicationSettings  is typically used for backing up persistent data that you want available every time the application starts up. 

PhoneApplicationService.Current.State is used for transient data that you only want persisted if your Silverlight application gets tombstoned.  It is the equivalent of session data in an ASP.NET web application.

In the Launching and Closing event handlers you would typically save to Isolated Storage, while in handlers for Activated and Deactivated you would want to use Current.State.  The former coding artifacts are for persistent data while the latter are for transient data.

These categories are imperfect, however.  It is possible to go through the Deactivated event but never have Activated called.  This occurs if for memory management reasons your application is permanently terminated (a permanent death scenario rather than the temporary death that tombstoning is supposed to trigger).  This can also happen, of course, if the user for whatever reason just decides not to return to your app after it gets tombstoned.

Another way to look at this is that your application is permanently terminated without ever invoking the PhoneApplication.Closing event.

In order to handle this common scenario, you must save any persistent data in the Deactivated event as well as the Closing event.

A simple pattern for structuring your code to cover all these possibilities is to make sure the code fragment for saving persistent data is called in both the Dectivated and Closing event handlers.  Similarly, the fragment for restoring persistent data should be called in both the Activated and Launching handlers.  We do this by taking care of persistent data backup and restores in two new methods: BackupPersistentData and RestorePersistentData. Those who remember the IDisposible pattern in C# will recognize some of the same coding idioms being used here.

The following code goes in App.xaml.cs:

private void BackupPersistentData()
{
    var store = IsolatedStorageSettings.ApplicationSettings;
    //save persistent data
    store.Save();
}
private void RestorePersistentData()
{
    var store = IsolatedStorageSettings.ApplicationSettings;
    //restore persistent data
}

private void Application_Closing(object sender
    , ClosingEventArgs e)
{
    BackupPersistentData();
}

private void Application_Launching(object sender
    , LaunchingEventArgs e)
{
    RestorePersistentData();
}

private void Application_Deactivated(object sender
    , DeactivatedEventArgs e)
{
    BackupPersistentData();
    var store = PhoneApplicationService.Current.State;
    //save transient data
}

private void Application_Activated(object sender
    , ActivatedEventArgs e)
{
    RestorePersistentData();
    var store = PhoneApplicationService.Current.State;
    //restore transient data
}

Sticking to this pattern has helped me to avoid a lot of unforeseen mistakes in my own phone apps.

 



Getting the current theme in WP7 for Silverlight

Customizing App.xaml.cs

Windows Phone devices allow users two theme options, either dark or light.

In the WP7 beta dev tools, however, there no straight-forward way for Windows Phone Silverlight developers to find out what the current theme is, though there is a hack.  The developer must interrogate the app resources to find the color of the PhoneBackGroundColor.  Under the dark theme it is black, while under the light theme it is white.

The following code can be thrown into App.xaml.cs to add a little elegance to this hack. 

First, a brief enum is needed.  It can be added in App.xaml.cs above the App class, or simply placed in its own cs file in the project:

public enum Theme{Light,Dark}

A CurrentTheme property is added to the App class:

private static Theme _currentTheme;

public static Theme CurrentTheme
{
    get { return _currentTheme; }
    private set { _currentTheme = value; }
}

And then we assign a value to CurrentTheme in the App class constructor by interrogating Resources:

public App()
{
    var bgc = Resources["PhoneBackgroundColor"].ToString();
    if (bgc == "#FF000000")
        CurrentTheme = Theme.Dark;
    else
        CurrentTheme = Theme.Light;

    //etc.

The CurrentTheme is now retrievable from anywhere in the application like so:

    switch(App.CurrentTheme)
    {
        case Theme.Dark:
            MessageBox.Show("Dark");
            break;
        case Theme.Light:
            MessageBox.Show("Light");
            break;
    }

Moreover, if a user presses the Windows button at lower center on a device and resets the theme, the new theme will be assigned to CurrentTheme when the application returns from tombstoning.

There is a rumor that in the RTM of the WP7 dev tools, two new properties will be available for picking up the current theme: DarkThemeVisibility and LightThemeVisibility.

For ease of migration to the RTM, you can add the following two properties to App.xaml.cs for now as placeholders – you should be able to simply switch them out later should the new methods become available:

public static bool DarkThemeVisibility
{
    get { return CurrentTheme == Theme.Dark; }
}

public static bool LightThemeVisibility
{
    get { return CurrentTheme == Theme.Light; }
}