Archive for the ‘ WP7 ’ Category

Windows Phone 8 Development – MVVM

WP8 Development Serie

1. Introduction
2. Screen resolutions
3. MVVM (this post)
4. Localization

I guess most of us know the core concepts of MVVM, so this post will not talk about the pattern itself, but more highlight a new way of defining our properties that are bound in UI. Shortly anyway, binding to properties in XAML requires the properties to implement the INotifyPropertyChanged interface for the UI to automatically reflect changes.

ViewModel Implementation in Windows Phone 7.1
The old style of implementation was error-prone because of use of “magic strings”. Imagine that you rename/refactor a property name then that will not change the string representation of the property name used and you might end up with bugs that are hard to find.

public class ItemViewModel : INotifyPropertyChanged
 {
    private string _id;
    /// Sample ViewModel property; this property is used to identify the object.
    public string ID
    {
        get { return _id; }
        set {
            if (value != _id)
            {
                _id = value;
                 NotifyPropertyChanged("ID");
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

ViewModel Implementation in Windows Phone 8.0
New style of implementation – CallerMemberName Attribute.

public class ItemViewModel : INotifyPropertyChanged
 {
    private string _id;
    public string ID
    {
        get { return _id; }
        set { this.SetProperty(ref this._id, value);  }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (object.Equals(storage, value)) return false;
        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }
 }

This is not a huge change, you can still use the old way of literal strings for the property name, although I suggest using the new way to be pragmatic about future rename refactorings.

Happy Coding!

Windows Phone – Performance Best Practices

Performance issues is where we usually spend most effort in finding, so it is very important to understand how you find them, and how you prevent them in the first place.

This post will be fairly long containing some basic info about performance in apps and at the end go through some of the more common occasions where I usually see performance issues and how to fix them.

Let’s start with looking at the threading model.

Silverlight for Windows Phone has two threads that handle all the presentation related work. One UI Thread and one Composition/Render thread.

UI Thread

The UI thread is the main thread in Silverlight for Windows Phone and functions very similar to the UI thread for the Silverlight browser plug-in.

The UI thread handles all input, which includes touch, parse and create objects from XAML, layout calculations, data binding, draw all visuals (at least the first time they are drawn), rendering/rastering, process per-frame callbacks and execute other user code and event handlers.

Composition Thread

The composition thread is new for SL on WP7, it’s actually the only platform that has it (as far as I know) and is created to talk directly to the graphics processor, GPU. It basically feeds the GPU with textures to draw and handles transform (scale, rotate, translate) animations and plane projections.

The composition thread handles some work that the UI thread would normally handle, and therefore improves performance of Silverlight applications for Windows Phone. The composition thread combines textures and passes them to the GPU for drawing. Also storyboard-driven animations that run on the composition thread are automatically cached and handled by the GPU on the device in a process called auto-caching.

Note: To use the composition thread, scale transforms must be less than 50 percent of the original size.

In addition, opacity and clip property settings are handled by the composition thread. However, if an Opacity mask or non-rectangular clip is used on the animated object, these operations will be passed to the UI Thread. This means that even if the clip region is a rectangular shape but uses the PathGeometry the operations will be passed to the UI thread. So make sure to always use the RectangleGeometry for clipping paths if possible.

Animations and Threads

As mentioned previously, storyboard-driven animations are handled by the composition thread. This is ideal because the composition thread passes these to the GPU for processing. In addition, the composition thread can run more frequently than the UI thread if the CPU is overloaded.

image_thumb9
Translate animation will run on the Composition Thread

There are times, however, when storyboard animations do not satisfy the requirements of your application. In this case, you may choose to drive animations in code. These animations are handled on a per-frame basis. In many cases, this is fine, but you should be aware of the implications of running animations on a per-frame callback.

Per-frame callbacks are handled strictly on the UI thread. Animations will update only as fast as the UI thread can process them, and depending on what else is happening in your application, the animations may appear less smooth than if they were running on the composition thread. Also, when you update animations in code, the elements are not automatically cached as they would be if they were updated in a storyboard. If you manually place a bitmap cache on these elements, the transformation and blending is passed to the GPU, but the animation is still being updated on a per-frame callback and processed by the UI thread. In these cases, the animation will update only as fast as the frame rate of the UI thread.

image_thumb8
Color animations will run on the UI Thread and if blocked it will miss changing color

Important

It is extremely important to think about threading and have a solid understanding of how critical the UI thread is, it already does a lot as it is, so extremely important not to do to much work on the UI thread then necessary .

Progress bar

One of the most common controls used to show an indication that something is taking time to process is the ProgressBar. Although not everyone knows that the progress bar that is shipped with the SDK is lacking performance, it is running all the animations on the UI thread and is not really a valid option for a progress indicator. If you need to place a progress bar somewhere in the application that is not at the top of the page, then you should use the PerformanceProgressBar that is shipped with the Silverlight Toolkit for WP7. But, that progress bar is not perfect either, it will actually continue executing the animations even if the progress bar is invisible. Toggle visible on and off is often how we show/hide the progress bar, but setting it to indeterminate will make the animation to continue even when it is hidden. So in this case you should also toggle the IsIndeterminate property using the same data binding you use to toggle it’s visibility.

Example:

<ProgressBar IsIndeterminate="{Binding IsProgressBarVisible}" Visibility="{Binding IsProgressBarVisible, Converter={StaticResource VisibilityConverter}}" >

The best option with respect to performance is to use the ProgressIndicator on the system tray on an application page. It performs very well and I have never had any issues with it, even when totally blocking the UI thread and have really advanced animations handled by the composition thread.

I often hear that we don’t want to use the ProgressIndicator since that requires the system tray to be visible and it will make the app look bad. But remember that you can set colors, opacity etc. on the system tray so it should not be to hard to design it to fit to the overall design. Changing the opacity on the system tray to something less than 1.0 will make the system tray hover over the page and let the page take the entire area, so you could also toggle the visibility of the system tray in the same way you toggle the progress indication.

Performance Counters

image_thumb19

These counters are really important to use and understand, they are in great help when you try to find what the actual performance issue is. You enable/disable the performance counters by toggling EnableFrameRateCounter property in the App constructor.

image_thumb22

Composite Thread – Aim for 60 FPS, it becomes red when under 30. 30 FPS doesn’t sound to bad, but MSFT has seen that the experience is not perfect when you come under that threshold, it just doesn’t look and feel good. So try to get at least 45 but aim for 60!

UI Thread – Becomes red when counter is under 15

Video Ram – the number of textures that has been created for all objects, for example a button that has been rasterized to a texture and drawn on the screen.

Internmediate textures – textures that SL has created for us to improve performance. If two or more textures are placed on the same layer, then SL will create one large texture of it so that we do not have to send one texture for each object, instead SL will just send one large.

Fill rate – fill rate tells us how many pixels that we send to the screen in each frame. A fill rate of 1 means that 800×400 pixels are drawn in each frame. There will be performance implications if the fill rate comes larger than 3, to much pixels to process and we get a drop in frame rate.

Redraw Regions

Objects that are animated but does not change, that is, pixels in the image looks identical in each frame but the object is moving, then SL will not have to send all the pixels over and over again to the GPU to calculate what is to be drawn. Instead the composition thread will just animate the object and render the same texture over and over, just in new positions.

By enabling Redraw Regions, then each time SL need to re-calculated and send pixels to the GPU it will be shown by a color tint on the texture with different colors. If we see a lot of flickering then we now something might be wrong.

You enable redraw regions in the same way you enable performance counters, but by toggling the EnableRedrawRegions property.

image_thumb40

If we have a lot of flickering and want to remove that due to performance hit, then what we want is to cache the texture on GPU and only tell it to move the object and draw it again, we do not want to send the same pixels over and over again when they are not changing.

Recall in the section above about performance counters and intermediate textures, these sound really good but there might be times when intermediate textures means performance issues. If we have one or more moving objects on the same layer as for example a button, then SL will try to be smart and create an intermediate texture out of these, but since we are animating the objects the intermediate texture needs to be recalculated in each frame and sent to the GPU, so we get a performance drop due to that.

In this case we want to do two things, first of all make sure that pixels for an object that is not changing is not sent to the GPU in each frame and also prevent an intermediate texture from being created since it doesn’t add anything, just gives us worse performance.

The solution to this is setting cache mode. SL is smart and does this for us, but not in all types of animations. If we use a per-frame callback for animations then SL will not cache the texture for us. You set the cache mode manually by setting

image_thumb36

for each object you want to cache.

image_thumb25

Look at the left part, a lot of redrawing is done while the rectangle is animating to the right

Fill Rate

So fill rate tells us how many pixels we send to be processed in each frame. It’s important to understand that fill rate will increase by 1 if you explicitly set background color on the page. So setting background color on pivots, panels etc. is something you should avoid unless you really need to.

Bitmap Cache sounds like a “silver bullet” if you look at the above example about redraw regions. So shouldn’t we just set cache mode on all objects?

It sounds like a good idea, but the answer is NO! Caching an object means that we increase fill rate since each object becomes its own object that needs to be rendered. And an increased fill rate means a drop in UI thread FPS. For example, if we have an application with a background image of a sky, then several of other images that builds up the scene like trees, hills, bushes, birds etc. If we then set explicit caching on all objects then we will have several layers that the GPU needs to render, even if the texture for one object is not even visible since some other object is drawn in front of it. But if we do not set cache mode explicitly then SL will be smart and create one intermediate texture for us and cache just ONE texture instead of one for each object.

So it really depends on your app, and you have to be smart on when to use and not use bitmap cache, be ware of fill rate. So USE performance counters, use redraw regions etc. to figure out if your app is performing well or not.

Data serialization/deserialization

A Windows Phone app has the possibility to store data on “disc” where all I/O operations are working through Isolated Storage. WP7 works in a sandboxed environment separated from all the other apps on your phone, so it is “safe” to store application specific data on the phone without worrying about other apps accessing your data.

There is a specific API that makes it possible to save application settings as objects in isolated storage really easy, which facilitates storing simple objects a lot.

IsolatedStorageSettings.ApplicationSettings[yourKey] = yourObject;
IsolatedStorageSettings.Save();

Even though it is simple to store objects in application settings, you will probably need to serialize and deserialize more advanced/complex objects in isolated storage throughout the application lifecycle. Below are some common occasions when you need to serialize and deserialize data.

  • App Launch – Deserialize
  • App being dormant/tombstoned – Serialize
  • App being reactivated – Deserialize
  • App being terminated – Serialize

So what do we have to think about when serializing data? The most important thing is how long it takes to serialize/deserialize data and when you do it.

First of all there are certification requirements that could be jeopardized and eventually hinder your app from being accepted to marketplace.

Launch Time, your main screen of the app needs to be rendered and shown within 5 seconds and the user needs to be able to interact with your app within 20 seconds.

Activation Time, if an app is deactivated (for example the user clicks the hardware Start button) and later activated, then the app needs to start with the same criteria as app launch time.

Most of our apps will have to save lists of object that you need to cache for quick access when the user returns to your application. This means that we need to serialize data to XML/JSON or some other format when the app is de-activated and when the user returns and the app is re-activated, data needs to be deserialized from isolated storage to a list of objects.

This serialization and deserialization can take time and if we do it in Application_Launching or Application_Activated event handlers then we could end up with performance issues at app startup. You need to think about where and when you need the data, make sure long running processing is done in background workers to prevent blocking the UI. For example, if you have a lot of data that you need to deserialize when starting your app, your app is useless without it, then think about other “dirty tricks” of how to fool the user into believing that your app is starting quickly. Perhaps use a second splash screen, you could even make the second splash screen look like your app (that is take a snapshot of your app en store it as a jpeg) and show that while you are deserializing data.

It is also important to select the correct serialization type, there are several options where some of them are shown in the table below with metrics showing how long it takes to serialize/deserialize 200 objects and 18 000 objects.

Isolated Storage Demo (executed on phone)

200 serialized 200 deserialized 18000 serialized 18000 deserialized
XML 76ms 174ms 6.1s 14.4s
DataC 149ms 191ms 12.9s 16.3s
DataCJSON 131ms 98ms 11.1s 8.4s
JSON.NET 63ms 147ms 5.2s 12.7s
Sharp 282ms 101ms 10.7s 9.6s

Note that this is just how it turned out in my sample app, the numbers could be totally different for your objects so you need to profile and try out different formats before you decide what format you should serialize data to. Most common is using JSON.NET in my experience.

Communication

As with serialization and deserialization to and from isolated storage, it is equally important to think about the size of messages that you send and receive over the wire. So use the above table to figure out what type of message to send when creating web services that are consumed from your Windows Phone application. It’s really simple to create a RESTful web service that provides JSON formatted output, so start with that unless you need a specific format.

Below is a screen shot of the message size for different types of message formats. (the sample app fetches all the suppliers that exists in the Northwind database)

image

JSON data sent: {“Address”:”49 Gilbert St.”,”City”:”London”,”CompanyName”:”Exotic Liquids”,”ContactName”:”Charlotte Cooper”,”ContactTitle”:”Purchasing Manager”,”Country”:”UK”,”Phone”:”(71) 555-2222″,”PostalCode”:”EC1 4SD”,”SupplierID”:1},{“Address”:”P.O. Box 78934″,”City”:”New Orleans”,”CompanyName”:”New Orleans Cajun Delights”,”ContactName”:”Shelley Burke”,”ContactTitle”:”Order Administrator”,”Country”:”USA”,”Phone”:”(100) 555-4822″,”PostalCode”:”70117″,”Region”:”LA”,”SupplierID”:2},{“Address”:”707 Oxford Rd.”,”City”:”Ann Arbor”,”CompanyName”:”Grandma Kelly’s Hom… and so on…

WebClient vs HttpWebRequest

WebClient is a wrapper class around the HttpWebRequest class that is used to perform Web service requests. WebClient can be easier to use because it returns result data to your application on the UI thread, and therefore your application does not need to manage the marshaling of data to the UI thread itself. However, if your application processes the web service data on the UI thread, the UI will be unresponsive until the processing is complete, causing a poor user experience, especially if the set of data being processed is large.

My suggestion is to use HttpWebRequest instead of WebClient and process the resulting data on the asynchronous request thread and then use BeginInvoke to marshal the data to the UI thread.

Making Large Numbers of Requests for Small Amounts of Data

To preserve battery life, the operating system will turn off the device’s radio after a preconfigured timeout interval. If an application is going to make a large number of requests for small amounts of data, I recommend that these requests be executed in parallel instead of serially. This helps to ensure that the device’s radio stack will not go to sleep, avoiding the lag incurred when the radio is powered on and off for each request and also saving battery life. Although there is a limit on maximum outbound network calls the rest will be queued and processed as soon as possible.

Where does it usually go wrong?

Below I’ll try to summarize some of the common performance issues that I have encountered and how to fix them.

Startup

Performance issues at startup is probably the most common problem I encounter when helping customer with their apps and causes everything from failed marketplace submissions to users giving up on your app since it takes to long to load and you end up with bad reviews and in worst case no one using your app.

Imagine that you start an app, see the splash screen and eventually the app is shown quickly, but it is really jerky, doesn’t seem to respond to user input and so on. These are the performance issues you really need to think about to fix. So what is actually going on at startup?

Assemblies are loaded and jittered, objects are instantiated and loaded and so on. Although the problem usually doesn’t reside here but it could. More common is what happens after that and all processing that needs to be completed before the app is “done” and fully ready for usage, deserialization of state (tombstone), loading UI (which means XAML parsing, element creation, layout calculations, redering etc).

So what can we do and what should we do to increase app startup time?

1. use a Splash screen and load data during startup. But if the app loads really quickly then you should perhaps remove the splash screen, only use if you need it. Don’t spend time designing the super cool and awesome looking splash screen since it could be so that the app starts really quickly and the user will not really see it to long. I have actually heard about cases when developers has put a Thread.Sleep() during startup to make sure the splash screen is visible longer. Not a good approach :) When the app is loaded you continue loading data that should be shown in background threads and when done publish/display it on UI using the dispatcher.

2. Use a second copy of the splash screen and show that as the first thing in your app with a progress bar if you need to load data from a web service or do something that takes time. But try to avoid this since the user wants to get into your app quickly and immediately start interacting with it. And even if you use a second splash screen with a progress bar you cannot take all the time you want, a max of 3-4 seconds, after that the user will start loosing his/her patience.

3. Keep the assembly size small of all the assemblies that are being loaded at startup. If your assemblies contains complex and demanding constructors, make sure to refactor and move the code to separate assemblies. If the app contains a lot of media like images, videos etc. then think about if you can set “build mode” as Content. If build mode is set to “embedded resources” then they will be loaded each time and make the loading of assemblies heavier, as build mode “Content” then assemblies will be loaded a lot quicker and content will be loaded “on demand”.

4. Keep your XAML clean and as simple as possible, try creating a small visual tree as possible to optimize layout calculations and rendering. Delay creation of controls to a later time when they are really needed and shown. For example in a Panorama all items will be loaded and kept in memory, which means that if you have 5 panorama pages, then all pages will be parsed, loaded and rendered (measure, arrange, bind etc.) on all UI if you do not create a custom page/control virtualization. You could optimize this by only loading the first and +/- one page and when the user pans load adjacent panorama pages and controls.

The Pivot control is using virtualization by default. 3 pages are loaded and kept in memory, current, previous and next pivot page.

One way is to set page visibility as Collapsed until they are needed (this means that they will not even be in the visual tree). But remember that even if you set visibility as Collapsed calculations and processing will still happen before they are eventually hidden from UI. A better approach is to remove XAML and manually add it when needed.

5. A somewhat strange but pretty cool solution is to take a screen shot of the app where you have hidden all dynamic data and then use that as a “second splash screen” while the app warms up loading data etc. and then do a nice fade from “splash screen” to the actual app with live data. In this way we are tricking the user to think that the app starts really quickly, loads some data and shows it. But be aware, this solution could give the wrong feedback to the user since the users cannot interact with the app directly if not done correctly.

Lists

When we now have followed all the advices above and the app starts really quickly we often hit the next common performance issue and that is with lists. It often feels like lists are not scrolling fast enough and are a bit jerky, they simply doesn’t perform good enough.

The problem is probably not that the lists doesn’t scroll fast enough, more common is that the phone doesn’t have time to render the UI while you are scrolling quickly.

Long lists are using virtualization by default, which means that SL will keep 3 full “pages” of elements in UI and memory and while we are scrolling new “pages” will be loaded as needed, which means parsing XAML, generating new objects, inserting these into the visual tree, layout calculations, measure, arrange, bind and so on. So there is a lot that needs to be done and if SL doesn’t have time to process this then, bam, you get black “pages” that show up and it feels like the list doesn’t scroll fast enough.

So what should we and can we do to optimize lists?

1. If the list is short, less that 3 full pages, then you should try to use a regular stack panel instead of a virtualizing stack panel (easily accomplished with templates). Using a stack panel all objects will be loaded immediately and you get a perfect scrolling experience.

2. Try to delay loading and processing while you are scrolling, you might end up with scrolling past objects that you will not even see in the end and then it is useless to loaded and process these objects. For example, if you have a list of images that are downloaded from Internet and when you scroll past a lot of images quickly then you do not need to load the images since the user will not even seem them when he/she stops scrolling. Listening to the scroll event is trivial and easy to implement.

3. Another problem is XAML itself. Windows Phone will not cache Data Templates and Control Templates after they are parsed, so by making simpler XAML and binding to less properties you will increase performance. Make sure you do not set properties in XAML that are default values, since that only adds more processing and try to avoid having objects as Collapsed that you don’t even need, they will add processing and eventually a performance hit.

4. Try to avoid value converters in data bindings. Data binding is a low-level operation and if you need to call external code to calculate values then you will have to pay for that. Instead use a ViewModel approach and add convenience properties that gives you the value directly. It is often really easy and possible to add more properties to your ViewModels to contain all the values your UI needs to show, and in the end not use value converters in lists at all.

5. If you still need really advanced XAML and perhaps different XAML for different items in the list then there are some more advanced techniques to use.

A ListBox will by default recycle containers, which is good, we want that to keep our memory footprint low, but there are scenarios where Data Templates becomes really advanced and you might end up with several visuals that are Collapsed or a very complex UI. Again, this means a lot of parsing, object creating etc. that in the en will be hidden for the user. A common solution I usually try to follow is to create one simple base data template that only contains the parts that always will be visible on all items in the list and then manually in code behind decide what XAML should be in the item and manually add them to the visual tree.

The process is fairly simple:

a) start with a “dummy control” with a Control Template that shows elements that are always visible for all list items.

b) create an Attached Property for the control.

c) set the value for the attached property using regular data binding and in the implementation of the attached property and “Property Changed” event handler you generate/create the UI elements needed for the specific item and manually add them to the visual tree.

6. Use third party list controls. There are several developers that has tried to tackle the performance issues with lists, some are good some are not so good, they all seem to have good and bad “features”.

a) DeferredLoadListBox, by David Anson. This list uses a regular stack panel and delays loading of controls. But there is an issue with this control (unless that is fixed in later version then I have tested) and that is that items are not unloaded when they are not used/visible which means that if you have a really long list and scroll a lot, you will hit a memory problem.

b) LongListSelector is an ItemsControl in Silverlight Toolkit that virtualizes the list without using a VirtualizingStackPanel, you can even tweak some parameters like how many pages to keep in memory and how fast it should scroll.

c) LowProfileImageLoader is another awesome control by David Anson and this class helps us with preventing that we load images on the UI thread. This one I have used a lot and think it is a really great asset.

d) LazyListBox by Peter Torr, it basically delays work until we are not scrolling.

So try them out and pick one that suits your needs.

Respons

Problems that usually occur is that the UI doesn’t really feel like it responds to user interaction, it might be hard to pan in a panorama or change pivot, you might have to try several times before anything happens. These are really common in several apps I have used and is extremely frustrating every time.

Issues like this most likely is due to that the UI thread has to much to do, remember that the UI threads is responsible of handling touch, parsing and creating objects, rendering/rastering visuals, processing per-frame callbacks etc. so the UI thread has a lot to do as it is, and if we start to do to much work on it our app will have to pay for it. But it can also happen if we do to much work in background threads which also might result in UI thread gets to little time to process.

So what can we and should we do?

1. Simply stop processing to much work on the UI thread, make sure you move any heavy work to a background thread. If you still have issues since the work is to heavy anyway, then you can add artificial sleeps to give the UI thread some slack. Simply add a 1 ms second sleep, Thread.Sleep(1); , and the UI thread will perform a lot better. A 1 ms sleep is something that the users will most likely not see or know about.

2. Use PerformanceProgressBar or ProgressIndicator

3. Try not to use color animations since these will be executed on the UI thread. You can often accomplish the same effect by animating the opacity, but remember that animations with OpacityMasks will be executed on the UI thread so try to avoid using opacity masks on objects that are animated often. I’m not implying that you should never use opacity masks, but you need to think about the consequences. If you need an opacity mask then there is a simple trick that you can use. Place the object in a Canvas and set the CacheMode to BitmapCache and then animate the container instead of the object itself.

4. Use RectangularGeometry for clipping paths on objects that are animated or drawn often, all other types of paths will be sent to the UI thread for processing.

5. Popup is also rendered on the UI thread, might want to change this to a simple Panel where you set z-index and toggle it’s visibility instead, you will get a lot better performance and even support for orientation change in your app.

As I wrote in my previous post about the importance of UX, the perception of how the user thinks your app performs is key. UX is King! So all the “dirty tricks” your can think of are valid, as long as the users gets the impression that your app is performing really well, then all tricks are valid. So be creative and think about how can we trick the user into believing that your app is super fast.

Background Agents

You have the possibility to schedule one Background Agent per application which is executed while your app doesn’t have focus. Each background agent can execute one or both of the following:

Periodic Task – is executed approximately each 30 min or so and is allowed to execute for 25 seconds, use less than 6MB of memory and is automatically un-scheduled if it has more that two adjacent crashes.

Resource Intensive Task – executed if the phone is charging, has WiFi or USB pass through (connected to the computer), the screen is locked and the battery is over 90% charged. So this will most likely occur for example while you are charging your phone during night. A resource intensive task is allowed to execute for approx. 10 minutes and use a maximum of 6MB of memory.

In any of the tasks you can do/access the following

  • Titles
  • Toast
  • Location
  • Network
  • R/W ISO Store
  • Sockets
  • Most of the framework API

The following is not allowed

  • Display any UI
  • Use XNA
  • Access the microphone or camera
  • Sensors
  • Play media (only use background audio API)

I usually ask myself, do I really need a background agent?

If you do, then make sure you do not have any important functionality in them since there are several ways to disable them or prevent them from even being executed:

  • to many are already running, you cannot schedule any more
  • not available at all on 256MB devices
  • prevented by the user in settings
  • battery is to low

image

You should think about background agents like Batman and Robin, Batman does all the important stuff (your app) while Robin is there once now and then and helps out doing some really simple stuff (your background agent), but Batman is so awesome so he can always handle everything himself, not dependent on Robin at all. You should implement your app the same way, they have to function to a 100% without background agents. I usually try to avoid using background agents in the first place since there are so many cases that could prevent them from being executed in the first place and instead invest in a Push Notification solution.

Location in background agents

if you need to get hold of the geo location in a background task then you might end up not getting them in time. Since a periodic task only has a few seconds to execute them you might not have time to start the GeoCoordinationWatcher to get the exact position. What you can do is to create a GeoCoordinationWatcher object and them immediately get the location, you will then get a cached position that the phone caches for you automatically around each 15 minute or so. Not accurate but might be good enough.

ISO store is available for background agents and is the same used as for the app, so you can easily share information between the app and your background agent. Although there are cases where the agent may try to access the same file in isolated storage at the same time as your app. If you start to or could encounter these types of issues then you should use a Mutex.

Debug background agents using

ScheduleActionService.LaunchForTest(“task name”, TimeSpan);

In that way we can schedule our task to execute each minute or some other timespan that is suitable for testing instead of waiting for 30 minutes. If you start your app debugging and exit the app by pressing the hardware Start button then Visual Studio will not stop debugging so you can easily place break points in your OnInvoke method to debug your task.

Advices

Re-Schedule often, each time you start your app since a scheduled agent will be removed after 2 weeks by the phones OS.

Do NOT implement critical functionality in a background agents since it is not sure that your agent will even execute.

if you need a more secure functionality to execute some code now and then to update Tiles or show Toast notifications then evaluate if you cannot use Push Notifications

Well that’s it for now regarding Performance Best Practices for Silverlight Windows Phone apps. There is so much to think about when it comes to performance optimizations, but this post might have given you something to think about and at least gotten your attention on how important it is and that you should always think about it while developing apps for The phone.

Happy Coding!

Windows Phone – Reactive Extensions (Rx)

In my previous post I talked about how important it is to use page transitions and animations in your application to increase the overall user experience. Wouldn’t it be nice if we could extend this experience a bit, and take it to the next level of user feedback and interaction.

Fortunately there is a framework called Reactive Extensions (Rx) that enables us to do all kinds of super cool stuff in our applications.

This post will show how easy it is to use the Reactive Extensions framework to increase the user experience when loading data from services and showing it to the user in a more elegant way.

Reactive Extensions (Rx)

First of all, Reactive Extensions is a library to compose asynchronous and event-based programs using observable collections and LINQ-style query operators. You can start learning about Rx at MSDN if this is new to you: http://msdn.microsoft.com/en-us/data/gg577609

In the sample project that I’m going to build, I will simulate a call to a web service to fetch data, and when data is returned I will populate a ListBox with the data. The items will be added one by one to the list with a nice subtle animations to give feedback to the user that items are being added to the list. I will simulate fetching from different services and add them result items to the list as soon as they arrive.

1. Create the Phone project

You start by creating a Windows Phone 7.1 project using the “Windows Phone Databound Application” template.

This will give you all the needed UI automatically, we will just refactor it and change so that it uses loading animations and Reactive Extensions when displaying the items to the user.

2. Change the UI

Now let’s change the Item Template for the ListBox so that each row has a solid background color (will be easier to see the animation) and finally add an animation/storyboard that is executed when a row is loaded (using event trigger).

The final ItemTemplate:

    <DataTemplate>
        <Grid x:Name="TileGrid">
            <Grid.Triggers>
                <EventTrigger RoutedEvent="Grid.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation 
                                Storyboard.TargetName="TileGrid"
                                Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationY)"
                                Duration="0:0:0.5" To="0" />
                            <DoubleAnimation
                                Storyboard.TargetName="TileGrid"
                                Storyboard.TargetProperty="Opacity"
                                Duration="0:0:0.5" To="1" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Grid.Triggers>
            <StackPanel Margin="0,0,0,17" Width="432" Height="78" Background="{StaticResource PhoneAccentBrush}">
                <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                <TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
            </StackPanel>
            <Grid.Projection>
                <PlaneProjection CenterOfRotationX="0" CenterOfRotationY="0"
                        RotationY="-90" />
            </Grid.Projection>
        </Grid>
    </DataTemplate>

If we run the application now, we already see an animation for the loaded event.

But all items are loaded at the same time. What if we wanted each row to be loaded one by one with a 200 millisecond delay? How would we do that?
One option is to use a background worker that has a 200 millisecond sleep in each loop that adds an item to the Items collection that is used as ItemsSource on the ListBox.
Let’s try that and see how it would look like and then later simplify the source code using Reactive Extensions.

3. Add item loaded delays
Start by refactoring the MainViewModel.cs LoadData() method to hold the sample data in a temporary list (so that we can use that list in our background worker to finally add them one by one to the Items collection)
Hint: to change the source code on multiple rows at the same time, you can hold down the Alt key while highlighting text in the editor to select parts of the text on multiple rows and then type on your keyboard to change the text on multiple rows at the same time. Realy nice feature :)

The final source code with BackgroundWorker:

    public void LoadData()
    {
        // Temporary hold the items in memory
        ObservableCollection<ItemViewModel> items = new ObservableCollection<ItemViewModel>();

        // Sample data; replace with real data
        items.Add(new ItemViewModel() { LineOne = "runtime one", ... });
        items.Add(new ItemViewModel() { LineOne = "runtime two", ... });
        items.Add(new ItemViewModel() { LineOne = "runtime three", ... });
        ...
        items.Add(new ItemViewModel() { LineOne = "runtime sixteen", ... });

        this.IsDataLoaded = true;

        // Create background worker that adds all items to the Items collection with delays
        var worker = new BackgroundWorker();
        worker.DoWork += delegate(object sender, DoWorkEventArgs args)
        {
            // Loop through all the items
            for (int i = 0; i < items.Count - 1; i++)
            {
                // Create a slight delay and add each item to the Items collection
                Thread.Sleep(200);
                Deployment.Current.Dispatcher.BeginInvoke(
                    () =>
                    {
                        Items.Add(items[i]);
                    });
            }
        };
        worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs args)
        {
        };
        worker.RunWorkerAsync();
    }

If we run the application now we have a nice animation for each row when they are added to the Items collection

4. Add Reactive Extensions (Rx)
So the above use of background worker is working just fine, but can we simplify the source code using Rx?
First of all to use Rx you need to add the following references to the project

  • Microsoft.Phone.Reactive
  • System.Observable

and the following using statements

    using Microsoft.Phone.Reactive;
    using System.Linq;

Then finally remove the Background Worker code section and replace with the following code and also add the method AddItem

    public void LoadData()
    {
    
    ....

    // Convert the result to an Observable sequence
    items.ToObservable()
        // Add selector method that selects each item with 200 ms delay
        .Zip(Observable.Interval(TimeSpan.FromMilliseconds(200)), (d, t) => d)
        // asyncrounously notify observers using the current dispatcher
        .ObserveOnDispatcher()
        // subscribe a value handler to an observable sequence
        .Subscribe(AddItem); 
    }

    private void AddItem(ItemViewModel item)
    {
        Items.Add(item);
    }

If we run the application now we have the same result as expected. Although the source code is now a lot nicer, and we don’t have to worry about cross thread issues, index out of bound when looping through the items etc. This is just a really simple useage of Rx framework, but there is a lot more cool stuff you can do with it. Perhaps I’ll write a post later on a more complicated scenario.

Performance

You should always pay attention to performance on the phone when using animations and transitions. If we enable draw regions we can see that during loading the list box items are redrawn several times, although this is OK in this simple application but something to pay attention to.

    // Show the areas of the app that are being redrawn in each frame.
    Application.Current.Host.Settings.EnableRedrawRegions = true;

Happy Coding!

Windows Phone – Animations and Transitions

Microsoft is introducing a fresh approach on UI design and user experiences based on the Metro design language and principles. Even though you follow the Metro design guidelines you are according to me only half-way there to a perfect design and user experience. If you think about all the out of the box experiences on the phone you realize that they feel a lot more alive than most of the apps you download from the marketplace. How is that? The simple answer is user experience through transitions and animations. Animations and transitions on the Windows Phone platform are fundamental elements that are deeply rooted in the UI concept.

Animations and Transitions

Animations is probably one of the most important features of Windows Phone. Most developers and customers I have talked to in the past tend to see animations as something extra fancy that you don’t need in an application, especially not in a LOB (line of business) application. I would argue and say that they are as important in a LOB app as in any other app.

Animations and transitions extends the user experience by giving subtle feedback to the user on what is going on, what is happening and to what is about to happen. It increases the overall experience.

A lot of applications are really static, no specific feedback to the user for any actions they perform, transition between pages and so on. The apps would feel much more polished and alive if the designers would spend time on creating subtle proper animations and transitions.

The Silverlight toolkit makes page transitions and user feedback super easy to implement. But be careful, overdoing animations will only annoy the users and detract the user experience.

Let’s go through how simple it is to add page transitions to your application.

  • First of all you need to install the Windows Phone Toolkit
  • add a reference to Microsoft.Phone.Controls.Toolkit to your project
  • in App.xaml.cs locate the InitializePhoneApplication method and change the RootFrame from a regular PhoneApplicationFrame to a TransitionFrame
        RootFrame = new Microsoft.Phone.Controls.TransitionFrame();
    
  • you have now prepared your application to use any of the page transitions provided by the toolkit.
  • finally add a page transition to your page. Either add xaml code to each page (which eventually leads to a lot of copy-paste) or create a Style that you reference in each page.

Xaml in each page

Start by creating a name space to the Windows Phone Toolkit

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

add the following xaml to the page. This example uses the Turnstile transition. A good sample application that shows all the different page transitions is found at codeplex: http://pagetransitions.codeplex.com/

<phone:PhoneApplicationPage
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
… >
    <toolkit:TransitionService.NavigationInTransition>
        <toolkit:NavigationInTransition>
            <toolkit:NavigationInTransition.Backward>
                <toolkit:TurnstileTransition Mode="BackwardIn"/>
            </toolkit:NavigationInTransition.Backward>
            <toolkit:NavigationInTransition.Forward>
                <toolkit:TurnstileTransition Mode="ForwardIn"/>
            </toolkit:NavigationInTransition.Forward>
        </toolkit:NavigationInTransition>
    </toolkit:TransitionService.NavigationInTransition>
    <toolkit:TransitionService.NavigationOutTransition>
        <toolkit:NavigationOutTransition>
            <toolkit:NavigationOutTransition.Backward>
                <toolkit:TurnstileTransition Mode="BackwardOut"/>
            </toolkit:NavigationOutTransition.Backward>
            <toolkit:NavigationOutTransition.Forward>
                <toolkit:TurnstileTransition Mode="ForwardOut"/>
            </toolkit:NavigationOutTransition.Forward>
        </toolkit:NavigationOutTransition>
    </toolkit:TransitionService.NavigationOutTransition>

Better approach with Styles

To make the transitions easier to maintain, and easier to switch between different page transitions when trying out your application, I would suggest you to create a style resource for each different page transition you want to use.

    <!--Application Resources-->
    <Application.Resources>
        <Style x:Key="TurnstilePage" TargetType="phone:PhoneApplicationPage">
            <Setter Property="toolkit:TransitionService.NavigationInTransition">
                <Setter.Value>
                    <toolkit:NavigationInTransition>
                        <toolkit:NavigationInTransition.Backward>
                            <toolkit:TurnstileTransition Mode="BackwardIn"/>
                        </toolkit:NavigationInTransition.Backward>
                        <toolkit:NavigationInTransition.Forward>
                            <toolkit:TurnstileTransition Mode="ForwardIn"/>
                        </toolkit:NavigationInTransition.Forward>
                    </toolkit:NavigationInTransition>
                </Setter.Value>
            </Setter>
            <Setter Property="toolkit:TransitionService.NavigationOutTransition">
                <Setter.Value>
                    <toolkit:NavigationOutTransition>
                        <toolkit:NavigationOutTransition.Backward>
                            <toolkit:TurnstileTransition Mode="BackwardOut"/>
                        </toolkit:NavigationOutTransition.Backward>
                        <toolkit:NavigationOutTransition.Forward>
                            <toolkit:TurnstileTransition Mode="ForwardOut"/>
                        </toolkit:NavigationOutTransition.Forward>
                    </toolkit:NavigationOutTransition>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>

Then in each page where you want to use a page transition (note that we could omit x:Key to make this an implicit style and default for all pages) you simply reference the wanted page style in the following way

<phone:PhoneApplicationPage Style="{StaticResource TurnstilePage}" ... >

Enhance user actions with visual feedback

It’s also a good practice to add feedback to the user when he or she presses a button or selects an item in a list that performs an action. This can easily be done by using the Tilt Effect.

Conclusions

Adding page transitions to your app is really simple and increases the user experience a lot, but as noted before, be careful, overdoing animations and transitions will make your app annoying and potentially get really bad ratings.

Happy Coding!

Windows Phone Mango – Encrypt Data

Windows Phone 7 Mango has focused on the end consumer market. The phrase “Put people first” is something we have seen in all of Microsoft’s Windows Phone 7 Mango promotions. The market place is filling up with apps targeting the common user, so for most applications encryption has not been super important, although more and more enterprise apps and data sensitive apps are coming and protecting your data is key in many scenarios.

Saving data in a phone’s isolated storage is not secure, there is a tool that comes with the SDK that enables you to list, copy and replace files and directories in isolated storage. You can read about how to use the tool at MSDN. There is an excellent tool that allows the developers to do a lot more with their applications, like uninstalling developer XAPs, get detailed device information, browse the Isolated Storage, copy phones local SQL CE DB to your PC to extract and change data and so on, all this through a really nice UI. Get your hands on the Windows Phone Power Tools at CodePlex.

image

This article will go through the basics in how you encrypt/decrypt sensitive and confidential data such as username, password, PIN code etc. using the Data Protection API (DPAPI) to prevent anyone from accessing your data using tools like the isolated storage explorer.

DPAPI

Encrypting the data will not increase the security if the decryption key resides on the phone, no matter how well the key is hidden. DPAPI solves the problem of explicitly generating and storing a cryptographic key by using the user and phone credentials to encrypt and decrypt data.  This means that the only place where you can decrypt your encrypted data is on the phone itself !

ProtectedData class

You can use the ProtectedData class that provides you access to DPAPI through Protect and Unprotect methods. On a Windows Phone device, every application gets its own decryption key when the application executes for the first time. Calls to Protect and Unprotect methods will implicitly use the decryption key and make sure all data remains secure and private to the application.

Protect – Use this method to encrypt your data
Unprotect – Use this method to decrypt your data

I have created a CryptoUtils class that enables you to encrypt and decrypt strings to isolated storage.

 public static class CryptoUtil
    {
        /// <summary>
        /// Encrypt a string and store it in the phone's isolated storage
        /// </summary>
        /// <param name="value"></param>
        /// <param name="path"></param>
        public static void EncryptAndStore(string value, string path)
        {
            // Convert the string to a byte[].
            byte[] PinByte = Encoding.UTF8.GetBytes(value);

            // Encrypt the string by using the Protect() method.
            byte[] ProtectedBytes = ProtectedData.Protect(PinByte, null);

            // Store the encrypted string in isolated storage.
            CryptoUtil.WriteProtectedStringToFile(ProtectedBytes, path);

        }

        /// <summary>
        /// Decrypt a string that is stored in the phone's isolated storage in the provided path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string DecryptString(string path)
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!file.FileExists(path)) return string.Empty;
            }
            // Retrieve the string from isolated storage.
            byte[] ProtectedPinByte = CryptoUtil.ReadStringFromFile(path);

            // Decrypt the string by using the Unprotect method.
            byte[] PinByte = ProtectedData.Unprotect(ProtectedPinByte, null);

            // Convert the PIN from byte to string and display it in the text box.
            return Encoding.UTF8.GetString(PinByte, 0, PinByte.Length);
        }

        private static void WriteProtectedStringToFile(byte[] strinData, string path)
        {
            // Create a file in the application's isolated storage.
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream writestream = new IsolatedStorageFileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write, file);

                // Write stringData to the file.
                Stream writer = new StreamWriter(writestream).BaseStream;
                writer.Write(strinData, 0, strinData.Length);
                writer.Close();
                writestream.Close();
            }
        }

        private static byte[] ReadStringFromFile(string path)
        {
            // Access the file in the application's isolated storage.
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(path, System.IO.FileMode.Open, FileAccess.Read, file);

                // Read the PIN from the file.
                Stream reader = new StreamReader(readstream).BaseStream;
                byte[] pinArray = new byte[reader.Length];

                reader.Read(pinArray, 0, pinArray.Length);
                reader.Close();
                readstream.Close();

                return pinArray;
            }
        }
    }

Conclusions

It is really easy to use DPAPI with Protect and Unprotect methods and if you create a CryptoUtils class that can be easily used in all of your applications there is no excuses not to do it :)

Note: If you want to encrypt large amount of data and the data is stored in the local database on the phone, then encrypting the entire database is a better options. See my next post about encypting Local DB.

Happy Coding!!

Windows Phone Mango – Background Agents

There is often the need of executing code in the background while your application is not in the foreground. You might want to synchronize data through WCF or just simply alert the user of something. In Windows Phone Mango we have “multitasking” in the sense that scheduled tasks and background agents allow an application to execute code. This is however not a true multitasking feature since there are limits on how often and how long each task man run.

An application may only have one background agent registered and capable of performing periodic tasks, and/or resource intensive tasks. Depending on what type of task you implement they will be scheduled differently.

Let’s start by explaining the different tasks and when to use them, and then follow up on how you actually implement background agents.

PeriodicTask

Periodic agents run for a small amount of time (typically for 25 seconds) on regular reoccurring intervals (typically every 30 minutes). Use this type to do small tasks, small data synchronizations etc.

ResourceIntensiveTask

Resource intensive agents run for a relatively long period (typically 10 minutes), although only when certain constraints are met:

  • External power required
  • Non-Cellular connection required (needs Wi-Fi connection or through PC connection)
  • Minimum battery power (needs to be greater than 90%)
  • Device screen lock required (device screen needs to be locked)
  • No active phone call
  • Cannot change network to cellular

As we see there are a lot of constraints that needs to be met for resource intensive tasks to be executed, so most applications will only use period tasks.

Unsupported APIs

There are also a lot of APIs that you cannot use when executing code in a background agent. Take a look at the MSDN page for details: http://msdn.microsoft.com/en-us/library/hh202962%28v=VS.92%29.aspx

How to implement Background Agents

First of all you create a Windows Phone project and implement your application as usual. Next you need to add a Scheduled Task Agent project to your solution to add background agents use to your application

  1. From the File menu select Add-New Project and select Windows Phone Scheduled Task Agent project. Name the project and hit OK.
  2. Now in your Windows Phone project you need to add a project reference to the agent project.

In the Scheduled task agent project there is now a file called ScheduledAgent.cs. This file contains the source code that will be executed in the background. Add functionality to method OnIvoke() that you want to be executed, this method is called by the OS when the scheduled tasks executes.

Each application can only register one background agent, although you can implement both Periodic tasks and Resource Intensive Tasks. The below code section shows how you check task type and how to run the task more often when debugging. Since the tasks are executed each 30 min, it would be cumbersome to test your application if that period could not be adjusted. Luckily you can set that during debugging by calling ScheduledActionService.LaunchForTest() method.


protected override void OnInvoke(ScheduledTask task)
{

//TODO: Add code to perform your task in background

// If your application uses both PeriodicTask and ResourceIntensiveTask
// you can branch your application code here. Otherwise, you don't need to.
if (task is PeriodicTask)
{
// Execute periodic task actions here.
}
else
{
// Execute resource-intensive task actions here.
}

// If debugging is enabled, launch the agent again in one minute.
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif

// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}

Now to actually use background agents we have to register and add a background agent in our foreground application. This is also fairly straightforward to accomplish. You simply create either a PeriodicTask object or ResourceIntensiveTask object and add them to the ScheduledActionService.

Create PeriodicTask

PeriodicTask periodicTask;
string periodicTaskName = "PeriodicAgent";

private void StartPeriodicAgent()
{
  // Obtain a reference to the period task, if one exists
  periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

  // If the task already exists and background agents are enabled for the
  // application, you must remove the task and then add it again to update
  // the schedule
  if (periodicTask != null)
  {
    RemoveAgent(periodicTaskName);
  }

  periodicTask = new PeriodicTask(periodicTaskName);

  // The description is required for periodic agents. This is the string that the user
  // will see in the background services Settings page on the device.
  periodicTask.Description = "This demonstrates a periodic task.";

  // Place the call to Add in a try block in case the user has disabled agents.
  try
  {
    ScheduledActionService.Add(periodicTask);
    PeriodicStackPanel.DataContext = periodicTask;

    // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
  }
  catch (InvalidOperationException exception)
  {
    if (exception.Message.Contains("BNS Error: The action is disabled"))
    {
      MessageBox.Show("Background agents for this application have been disabled by the user.");
    }
  }
}

Create ResourceIntesiveTask

ResourceIntensiveTask resourceIntensiveTask;
string resourceIntensiveTaskName = "ResourceIntensiveAgent";

private void StartResourceIntensiveAgent()
{
  resourceIntensiveTask = ScheduledActionService.Find(resourceIntensiveTaskName) as ResourceIntensiveTask;

  // If the task already exists and background agents are enabled for the
  // application, you must remove the task and then add it again to update 
  // the schedule
  if (resourceIntensiveTask != null)
  {
    RemoveAgent(resourceIntensiveTaskName);
  }

  resourceIntensiveTask = new ResourceIntensiveTask(resourceIntensiveTaskName);

  // The description is required for periodic agents. This is the string that the user
  // will see in the background services Settings page on the device.
  resourceIntensiveTask.Description = "This demonstrates a resource-intensive task.";

  // Place the call to Add in a try block in case the user has disabled agents
  try
  {
    ScheduledActionService.Add(resourceIntensiveTask);
    ResourceIntensiveStackPanel.DataContext = resourceIntensiveTask;

    // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
    ScheduledActionService.LaunchForTest(resourceIntensiveTaskName, TimeSpan.FromSeconds(60));
#endif
  }
  catch (InvalidOperationException exception)
  {
    if (exception.Message.Contains("BNS Error: The action is disabled"))
    {
      MessageBox.Show("Background agents for this application have been disabled by the user.");
    }
  }
}

That’s all there is to it. Pretty simple and straightforward to implement.

In the OnInvoke() method you can call WCF services, do simple synchronizations and store data in Isolated Storage or the local SQL DB or what ever fits you needs. One thing that I have not figured out yet is if it is possible to alert the foreground application that data has changed and that it needs to refresh data from, for example, Isolated Storage.

Happy coding!

Windows Phone Mango – Tombstoning and life cycle

Before Mango the Windows Phone application could be in four states, Running, Deactivate, Tombstoned and Activate. In Mango there is a new state called Dormant. This extra state is there to provide us with fast app switching. It is important for the developer to understand the Windows Phone application life cycle and to understand what actions the developer needs to take at each state and event to provide an application that is responsive and provides a consistent experience.

The following overview explains the life cycle of Windows Phone applications and all the actions the developer should take and be aware of.

Windows Phone Life Cycle - Image taken from MSDN

Continue reading

%d bloggers like this: