Leveraging ETag caching in Windows Phone and Windows apps

In my previous article I showed you how to implements server side caching using ETag. HTTP clients on other platforms can usually work with ETag automatically, but of course, the portable HTTP client used on Windows platforms cannot. You have to implement ETag handling yourself.

In TvTime, all the server requests are GET request, so I remember the ETag values for each Url (= each GET request). I store the ETag values in application local settings.

When the app wants to get some data, I perform a GET request including the ETag as the If-None-Match header. If my ETag matches with the ETag on the server, the server returns HTTP 304 Not Modified and I return the cached data from disk. Otherwise I read the response body and return it.

[Read More]

Changing the PivotItem header color in Windows Phone 8.1 XAML

Windows Phone 8.1 XAML contains a Pivot control that looks like the one from Windows Phone 78 and also should behave the same way, but does not. You will find the first problem with the new Pivot when you want to change the PivotItem header color.

Windows Phone 78

If you want to change the PivotItem header color in Windows Phone 78, you just define the color in the Header template:

<controls:PivotItem.Header> 
  <TextBlock Text="{Binding}" Foreground="{StaticResource PhoneAccentBrush}"/> 
</controls:PivotItem.Header> 

This works great, changing the color of the active PivotItem Header to the color you want and applying some opacity to the inactive PivotItem Headers.

[Read More]

Dialog helper for Universal Apps the easy way

Today I read Joost van Schaik’s blog post called A behavior to show a MessageDialog from a MVVMLight viewmodel in Universal apps–with callbacks. I am not a MVVMLight guy (I use Caliburn.Micro) and I personally use an approach that uses a little less code, employing a helper class.

Helper class

/// <summary>
/// Helper class for showing message dialogs
/// </summary>
public static class DialogHelper
{
    /// <summary>
    /// Shows a dialog with given message and ok/cancel buttons. 
    /// </summary>
    /// <param name="message">Message</param>
    /// <param name="title">Title</param>
    /// <param name="okText">OK text (optional)</param>
    /// <param name="cancelText">Cancel text (optional)</param>
    /// <returns>True if ok pressed, false otherwise</returns>
    public static async Task<bool> ShowMessageDialog(string message, string title, string okText, string cancelText)
    {
        bool result = false;
        var dialog = new MessageDialog(message, title);

        if (!string.IsNullOrWhiteSpace(okText))
        {
            dialog.Commands.Add(new UICommand(okText, cmd => result = true));
        }

        if (!string.IsNullOrWhiteSpace(cancelText))
        {
            dialog.Commands.Add(new UICommand(cancelText, cmd => result = false));
        }

        await dialog.ShowAsync();            
        return result;
    }
}

with a simple usage in ViewModel

[Read More]

Creating a fake splashscreen for your Universal App

Sometimes you may want your app to display the startup splashscreen a bit longer, so you can initialize or fetch some data necessary for the app to run. To achieve this, you can create a fake splaschreen, a View that looks just like the splashscreen, does all the work and redirects to the real main View afterwards.

In theory, it is quite simple:

  • Create a SplashScreenView with just the right background and the splashscreen image
  • Set the app to display SplashScreenView at startup
  • Do all the initializing and data fetching in SplashScreenViewModel and redirect to there real MainView

This works quite well with Windows 8.1, but on Windows Phone 8.1 there is a problem. When you run the Windows Phone 8.1 app, you will see a page transition happen between the real splashscreen and your SplashScreenView. This looks strange, so it is better to get rid of it.

[Read More]

Why Universal Apps as not as universal as you may think

I have been developing Windows Phone apps for a few years now, always sticking to Silverlight and keeping using Silverlight also after Microsoft announced the WinRT flavor of Windows Phone apps and the so called Universal Apps. The Windows Phone 8.0 and 8.1 Silverlight APIs have some limitations, but are now well known do not contain many bugs. They are the safe choice if you want to create a Windows Phone apps. And do not forget that there are still many device running Windows Phone 8 (like Verizon customers in the US) that never got the 8.1 updated promised to everyone during the summer.

Really universal?

Windows Phone 8.1 XAML and Universal Apps included WinRT APIs that have many problems, including some that there is no solution for. I used the WinRT APIs when creating first Windows 8 apps about 2 years ago, so I am not new to the APIs. I have not touched the WinRT APIs again until recently, because there was no demand for Windows 8 or Windows 8.1 apps. Why would it? People use Windows 8 or 8.1 but do not care about Metro apps, they give them no value compared to “normal” Win32 and Windows tablets are practically non-exists (expect for the Surface tablets owned by few programmers and maybe no one else).

[Read More]

REST service base class for Windows Phone 8.1 XAML apps

Communicating with a JSON based REST service is a task that many Windows Phone apps have to do. My apps sure do it a lot so I came up with a base class that I use in all of them, put it on Github and created a Nuget package, so your apps could use it to.

The usage of this base class is simple. Create your service class and inherit from BaseRestService. The minimum you need to do to make it work is to override the GetBaseUrl() method to set the base url for all the requests. You can (but do not have to) also override the GetRequestHeaders() method to set the default request headers.

public class MyDataService: BaseRestService
{
  protected override string GetBaseUrl()
  {
    return "my base url";
  }
  
  protected override Dictionary<string, string> GetRequestHeaders()
  {
    return new Dictionary<string, string>
    {
      {"Accept-Encoding", "gzip, deflate"},
      {"Accept", "application/json"},
    };
  }
}

and you can now use the following protected methods

[Read More]

Automatic ViewModels and Services registration for (not only) Caliburn.Micro

My MVVM framework of choice, Caliburn.Micro, provides a simple Dependency Injection container, where you have to register all your ViewModels and Services. This is done in the Bootstraper’s Configure method and may look like this:

container.PerRequest<MainViewModel>():
container.PerRequest<AboutViewModel>();

container.Singleton<SessionService>();
container.RegisterSingleton(typeof(ISettingsService),null,typeof(SettingsService));

where you typically register your ViewModels as per request and services as singletons.

Of course this is done just once, but having to register a ViewModel each time you create a new one can be a nuisance, especially in a large project.

[Read More]

Ignoring certificate errors in Windows Phone 8.1

Connecting to servers with self-signed, expired or otherwise problematic certificates has always been a problem in Windows Phone. There is no way to ignore certificate errors in Windows Phone 7 and Windows Phone 8, not even using the new Portable HTTP Client Libraries. If you are dealing with a self-signed certificate on the server, you have to somehow get it (may not always be possible) and install it on the device or in the emulator (for emulator every time you close and start it again). Ignoring certificate errors would be a much more comfortable approach. Of course, only do it in development with dev servers, not in production.

In Windows Phone 8.1 there are strangely two HttpClient classes, one in System.Net.Http and another in Windows.Web.Http. Normally you would go with the one in System.Net.Http because you are probably using it thanks to the mentioned Portable HTTP Client Libraries on every other platform. You are out of luck in Windows Phone 8.1 XAML, if you want to ignore certificate errors, you have to use the one from Windows.Web.Http, because only this one accepts an IHttpFilter as an argument.

[Read More]

Developing Windows Store apps with Caliburn Micro Part 4: services and dependency injection

In this installment of the series I will show you how user data services. We will finally use the Unity DI container that is part of the project setup.

Data and Services

In next installment we will be showing a list of products, so let’s create a simple Product class first in the Data directory:

PropertyChangedBase is a base class implementing the INotifyPropertyChanged interface and the ImplementPropertyChanged attribute makes sure it’s method is called for all the property changes. (More about Fody here)

[Read More]

Developing Windows Store apps with Caliburn Micro Part 3: saving and restoring state

In the previous post I stated that a well-behaved Windows Store app should remeber the View the user navigated to before suspension and navigate to this View upon next run. The View can contain some input that the user can fill in. A well-behaved Windows Store app should remember the user’s input and restore it after suspension.

Saving and restoring state

Implementation of the above-mentioned scenario is not very complicated, thanks to the project setup. If you want your ViewModel to be able to save and restore state, implement the IHaveState interface. It contains two method that you can override; SaveState and LoadState. In bith method you have access to a page state dictionary that you can use to save and load the state.

[Read More]