22Sep/134

Portable Class Libraries with WP7 support in Visual Studio 2013 (RC)

Note: This is my personal blog. Although I did an internship at Microsoft and this post is about a product made by Microsoft, I figured out the info in this blog post after the internship in my own time without any help. The "hack" described in this blog post, leaves Visual Studio 2013 RC in an unsupported state. Perform it at your own risk.

Update 10/17/2013: It looks like this trick still works for the final release of Visual Studio 2013. Use it at your own risk.

With the recent release of Visual Studio 2013 RC and the Windows 8.1 RTM for MSDN subscribers, I started upgrading some of my code to work with Windows 8.1. Part of this code resided in a Portable Class Library (PCL) that also targets Windows Phone 7.5 (and therefore Silverlight 4) next to Windows Phone 8, Windows 8 and .NET 4.5. Visual Studio 2013 has dropped support for some older platforms including Windows Phone 7.5, Silverlight 4 and older.

Since you can install Visual Studio 2012 and 2013 side by side, you can still continue building Windows Phone 7 apps in 2012 if needed. Problems occur as soon as you want to use a PCL for Windows 8.1 development that also targets Windows Phone 7. Several others also came accross this issue. When opening such a PCL in Visual Studio 2013, it will upgrade the project to Windows Phone 8, Windows 8 and .NET 4.5 as in the picture below and breaks the compatibility with Windows Phone 7 in Visual Studio 2012.

Visual Studio 2013 will upgrade the project.

While I was investigating if I could work around this issue, I found that all the portable profiles are actually there on disk in the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable folder, when you install Visual Studio 2013, including those with support for Windows Phone 7 and Silverlight 4. As Daniel Plaisted pointed out on Twitter, this is because different versions of Visual Studio share the portable profiles.

Folder containing the portable profiles.

I was wondering why Visual Studio would upgrade the project while the profile was there on disk. While digging through the xml files for Profile104 (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile104\), which is the profile I was using, I found some xml files in the SupportedFrameworks subfolder. These xml files defined a MinimumVisualStudioVersion and a MaximumVisualStudioVersion. For Profile104, one of the files contained MaximumVisualStudioVersion="11" which means Visual Studio 2012. Changing all xml files for the profile to have MaximumVisualStudioVersion="12", which means Visual Studio 2013, made my scenario work after a restart of Visual Studio. I can now open the PCL in Visual Studio 2013 without it being upgraded. Make sure you restart VS after this change to make it work.

Xml file that defines the minimum and maximum Visual Studio versions

Note that changing these xml files is unsupported and leaves you in an unsupported state. It might decrease the stability of Visual Studio 2013 RC, although I did not find any issues with this yet, but that does not mean there are none. Make these changes at your own risk and only for the profiles you really need!

Hope this helps for everyone who still needs to do Windows Phone 7.5 development. If you want support for Windows Phone 7 in Visual Studio 2013, please let the team know via their uservoice site.

Did you like this? Share it:
13Mar/1322

Preview of the new Managed Client for Windows Azure Mobile Services

Note: This is my personal blog. Although I’m currently doing an internship at Microsoft and this post is about a product released by Microsoft I worked on, the opinions on this blog are my own. They do not represent the opinions of Microsoft in any way.

Update: Carlos Figueira has a detailed list of breaking changes at his blog.

Update 2: We published an update to fix the issues with Windows Phone 7.5. The update can be found here.

Today we are releasing a pre-release version of the new Managed Client for Windows Azure Mobile Services on NuGet. This release adds several new features and also adds support for Windows Phone 7.5.

The managed client now supports the following platforms:

  • Windows 8
  • Windows Phone 8
  • Windows Phone 7.5
  • Portable class libraries.

Windows Phone 7.5 support and Portable Class Libraries have been among the top requested features by our customers!

uservoice

Great! How do I get it?

The preview is available as a pre-release NuGet package. To use the package you need at least NuGet 2.1.

Note: This version is not officially supported. The latest officially supported client is available as a stable NuGet package or as an extensions sdk.

nuget-pre

To be able to see the package in Visual Studio you need NuGet 2.1 and you need to explicitly tell Visual Studio to show you pre-release packages.

includepre

New features

Beside support for new platforms and bug fixes, this release also adds a bunch of new features:

  • Enum support. Enum types are now supported in queries and for serialization. Enums will be serialized automatically into strings by the client. If for some reason you want to serialize enums as integers, you can still use the following technique to expose the enum as int for serialization.
[JsonProperty("value")]
public int ValueInt { get; set; }

[JsonIgnore]
public EnumType Value { get; set; }
  • Nullable types. Nullable types are now fully supported for queries and serialization. You can read more about Nullable Types here.
  • Contains support in queries. We already supported string.Contains in queries, but now you can also write Contains queries on lists. These queries will now automatically be translated into a sequence of “or” statements:
List names = new List() { "John", "Tom" };
from p in table
where names.Contains(p.Name)
select p
  • MobileServiceCollection. We added a new collection that replaces our previous MobileServiceCollectionView. This class had some problems and was less portable going forward. You can read more about the new collection further on.
  • HttpMessageHandlers. Service Filters available in our previous release are now replaced by HttpMessageHandlers. These classes are part of the recently released HttpClient library and are reusable by everything that uses HttpClient. More on this also further on.
  • Improved unit-testability. We removed the sealed keyword from most of the public facing classes and added interfaces for some of them. This heavily improves the unit testability of the library for us and make it easier for developers to substitute our classes for mocks.

Portable Class libraries

Currently we have separate clients for Windows and Windows Phone 8. This release unifies these platforms by moving towards a Portable Class Library. Portable Class Libraries offer several advantages for developers, since they can now share their codebases using Mobile Services more easily between the different platforms. Also it allows us to rollout changes faster and brings consistency across the supported platforms. You can read more about Portable Class Libraries on MSDN.

Our portable library targets:

  • Windows Store apps
  • Windows Phone 7.5 and higher
  • .Net 4.5
  • Silverlight 4 and higher

This does not mean we support all these platforms. The Portable Class Library need a platform extension assembly to work correctly and it won’t work without it. We only provide platform extension assemblies for Windows Phone 7.5, Windows Phone 8 and Windows Store apps. If you need to support other platforms, you can get the source code from GitHub. More on platform extension assemblies further on. We are considering adding .Net 4.5 support in the future.

Architecture

Although Portable Class Libraries are a great addition to the Managed Mobile Services client, we cannot move all of our code into the Portable Class Library. Some functionality is only available on one platform and other functionality differs between platforms. Therefore, to be able to use the new Managed Client you also need a platform specific assembly, which contains code to be able to use features available on that specific platform. UI authentication is an example of a feature that works different on different platforms and is not portable.

diagram

The design of the managed client is roughly as shown in the diagram. For you as a developer this means you need two assemblies for your Windows Store app to use Mobile Services. For Windows Phone this works a little different. For Windows Phone there is an additional assembly. This assembly contains functionality which is not allowed in background agents. In our case that means that login functionality involving UI lives there. So, if you install this package into a background agent project, make sure to remove the reference to Microsoft.WindowsAzure.Mobile.UI.dll.

With the platform extension assemblies we take an approach similar to what the Reactive Extensions team earlier did with Rx 2.0. We are constantly evaluating what platforms to support with our Portable Class Library with respect to the functionality we can actually put in the portable part, because support for more platforms in general means we have to move more functionality to the platform extension assemblies.

A new collection

MobileServiceCollection is our new collection type that replaces MobileServiceCollectionView going forward. The functionality it offers is similar to its predecessor and it offers more extensibility.

  • Support for paging. Simply give the collection a page size as part of the constructor and it will request the data in batches.
  • Client-side LINQ queries. We acknowledge that OData does not cover all query scenarios for users. To make this as easy as possible you can specify a custom selector function over the data after it has been retrieved from the server. This can be useful for example to wrap your Model objects into a ViewModel before insertion or to do grouping.
  • ISupportIncrementalLoading for Windows Store apps. Some controls in the Windows Runtime support an interface called ISupportIncrementalLoading. This interface allows controls to request extra data when the user scrolls. We have built-in support for this interface for Windows Store apps. Our windows store extension assembly contains the MobileServiceIncrementalLoadingCollection which automatically handles the calls from the controls.

To use the new collection you can simply use our ToCollection() extension methods on IMobileServiceTableQuery<T> and IMobileServiceTable<T> or use on of the available constructors for more customizability.

To actually load data you have to call LoadMoreItemsAsync(). When you have specified a page size before, the collection will only retrieve so much items as you specified, otherwise it will just send the original query to the server. Make sure you always await the calls to LoadMoreItemsAsync and wrap it with a try { } catch { } to handle any exceptions from the server.

MobileServiceCollection<TodoItem, TodoItem> collection = await client.GetTable().ToCollectionAsync();

or with page size 10:

MobileServiceCollection<TodoItem, TodoItem> collection = await client.GetTable().ToCollectionAsync(10);

Note that to load more pages you have to call LoadMoreItemsAsync() yourself.
If you want to do paging in a Windows Store app, you can also use the MobileServiceIncrementalLoadingCollection<TTable, TCol> which implements ISupportIncrementalLoading. For this class you cannot specify a page size since the controls automatically request a number of items. You also do not need to call LoadMoreItemsAsync() since the control will call this method for you.

If you want to do paging on a platform other than the Windows Store you currently don’t have ISupportIncrementalLoading. Instead you have to wire this up yourself. For Windows Phone you can use Scroll Compression states and call LoadMoreItemsAsync yourself.

HttpClient

In this release we are replacing Service Filters, on the Managed C# client, with HttpMessageHandlers which are part of HttpClient. HttpClient offers several advantages over our previous implementation and HttpMessageHandlers allow developers to reuse their handlers for other projects using HttpClient.

ServiceFilters can be easily transformed into HttpMessageHandlers. Consider the following filter created by Josh Twist:

public class BusyServiceFilter : IServiceFilter
{
	private int _callCount = 0;
	private Action _busyIndicator;

	public BusyServiceFilter(Action busyIndicator)
	{
		_busyIndicator = busyIndicator;
	}

	public IAsyncOperation Handle(IServiceFilterRequest request, IServiceFilterContinuation continuation)
	{
		return HandleAsync(request, continuation).
			  AsAsyncOperation();
	}

	private async Task HandleAsync(IServiceFilterRequest request, IServiceFilterContinuation continuation)
	{
		// update the count by one in a single atomic operation. 
		// If we get a 1 back, we know we just went 'busy'
		var outgoingCount = Interlocked.Increment(ref _callCount);
		if (outgoingCount == 1)
		{
			_busyIndicator(true);
		}

		IServiceFilterResponse response = await continuation.Handle(
			request).AsTask();

		// decrement the count by one in a single atomic operation.
		// If we get a 0 back, we know we just went 'idle'
		var incomingCount = Interlocked.Decrement(ref _callCount);
		if (incomingCount == 0)
		{
			_busyIndicator(false);
		}

		return response;
	}
}

This filter creates a busy indicator based on in-flight requests. It can be easy transformed into an HttpMessageHandler. The following sample show an HttpMessageHandler which does the same. Custom HttpMessagehandlers should in most cases derive from DelegatingHandler as they are meant to be “pass-through”.

public class BusyHandler : DelegatingHandler
{
	private int _callCount = 0;
	private Action _busyIndicator;

	public BusyHandler(Action busyIndicator)
	{
		_busyIndicator = busyIndicator;
	}

	protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
	{
		// update the count by one in a single atomic operation. 
		// If we get a 1 back, we know we just went 'busy'
		var outgoingCount = Interlocked.Increment(ref _callCount);
		if (outgoingCount == 1)
		{
			_busyIndicator(true);
		}

		HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

		// decrement the count by one in a single atomic operation.
		// If we get a 0 back, we know we just went 'idle'
		var incomingCount = Interlocked.Decrement(ref _callCount);
		if (incomingCount == 0)
		{
			_busyIndicator(false);
		}

		return response;
	}
}

Breaking Changes

The switch to HttpClient, the Portable Class Library and the new collection are breaking changes compared to our previous client, but we believe they all benefit developers.

Other breaking changes we made include a switch to Json.NET. While we did our best to keep the behavior the same, there are small changes that could affect you. Most of them actually make your life easier. For example Uri instances can now be serialized without a custom converter.

We also fail early when you try to send numbers, such as longs, ulongs and decimals, to the server which can’t be handled by the server because the number is too large or needs too much precision. As most of you will know, our server runtime is running on JavaScript, in which every number is a double. This means for example you can’t send a long to the server which is greater than 2^53.

exception

Our behavior with multiple calls to Skip(int) and Take(int) has also changed. Multiple Skip calls will now add up, so Skip(10).Skip(8) will result in Skip(18). Multiple calls to Take(int) will result in the lowest being used, so Take(2).Take(30) will result in Take(2). This makes our API consistent with other OData client libraries such WCF Data Services.

More about breaking changes here.

Pre-release

As mentioned before, this is a pre-release of our new library. Things are likely to change between now and the stable release, although we always try to keep the public changes at a minimum. We do NOT recommend the use of this library if you have critical business depending on it, as it is likely to have bugs and is not officially supported.

This release is meant for testing purposes and for us to get feedback on the changes we made. Try it out if you have the chance and submit your feedback and bugs via the forums!

NuGet

This pre-release client is only available on NuGet. Did I already mention you need NuGet 2.1 for it to work? Otherwise Portable Class Libraries and Windows Phone 8 won’t work. If you receive errors such as:

6507_NuGetFailedNeedsUpdate_thumb_3C41099C

Then you need to update your NuGet version via Tools -> Extensions and Updates.

8662_ExtensionsAndUpdates-2_thumb_3BD4D6A7

What’s next?

We plan to update the NuGet package regularly with the latest bug fixes and improvements. Stay tuned for more things to come in the months ahead!

Johan Laanstra (SDE Intern, Windows Azure Mobile Services)

Did you like this? Share it:
16Jan/131

The case of the not working Youtube app on Windows Phone 8

Somewhere in November I received my new Windows Phone 8 device, the Lumia 920. I do not often watch youtube videos on my phone, but when I tried to play a movie, the Phone asked me if I wanted to search for an app in the store.

wp_ss_20130116_0001

There is a youtube app for Windows Phone that allows you to play movies, which is basically just a wrapper around the mobile youtube site since Google is actively blocking Windows Phone access to the youtube api. Although I had that app already installed, it still asked me to look in the store. When I chose "yes" there were actually no apps found.

wp_ss_20130116_0002

It turns out that the mobile youtube site is not working on Windows Phone if you set your Website preference to "desktop version" instead of  "mobile version". Why this happens is unclear to me but if you have this problem you could check if you might have it set to  "desktop version". Changing it to "mobile version" fixes the problem and you can play videos fine.

Did you like this? Share it:
Tagged as: , , 1 Comment
29Jun/123

Introducing Windows.UI.Interactivity: Behaviors for the Windows Runtime

Update: a NuGet package is now available here.

In the Windows Runtime and Blend for Visual Studio 2012 there are no behaviors. This brings lots of problems when you are using the MVVM pattern or you come from the Windows Phone or Silverlight platform. Windows.UI.Interactivity tries to fill this gap by porting the whole System.Windows.Interactivity assembly, where the behaviors live in the Blend SDK, to the Windows Runtime. The project builts on work done by Windows Phone MVP Joost van Schaik a.k.a. LocalJoost and Silverlight MVP Andrea Boschin.

What is a behavior?

A behavior can be seen as an extension method for XAML. Behaviors leverage the power of attached properties and by using them you can extend the functionality of a control without modifying that controls' code.

Why would I care?

When using the MVVM pattern, you want to separate the view from the model. You bind the view to the viewmodel using the powerful data binding properties and the viewmodel should handle the interactions between the view and the model. Unfortunately you can not bind events easily to the viewmodel. This is where behaviors come in. Behaviors can be bound to the viewmodel and they also have access to the object they were attached to. In this way a behavior can register for an event and update a property on the viewmodel or fire a command, whenever an event fires. This is basically what EventToCommand from Laurent Bugnion does. By using Windows.UI.Interactivity you can again use behaviors as before and it also makes porting Windows Phone apps easier.

Great! How do I use it?

Using the library is very simple. Just use it as if it was System.Windows.Interactivity from the Blend SDK. Of course you need to update the namespace to the new Windows Runtime format (xmlns:i="using:Windows.UI.Interactivity"), but that is all you need to do! Any existing behaviors also need to be recompiled to work with this library. To get you started, a sample application is included with a basic ClickBehavior to show how it all works. Just download the code from github and add a reference to it to your app or install the library via NuGet.

Did you like this? Share it:
12Apr/122

Fixing the LongListSelector part 2: Making the SelectedItem bindable.

One of the problems of the LongListSelector in the current release of the Silverlight for Windows Phone Toolkit comes to the surface in MVVM scenarios. You often bind the SelectedItem to some property on the viewmodel so you can have access to the selected item. This works fine for a ListBox, but on the LongListSelector it doesn't work.

The problem is that the SelectedItem property on the LongListSelector is not a dependency property, and is therefore not bindable. The solution to this problem is of course to change it to a dependency property. But if you don't want to change the source and recompile there is also another way to add this.

The following piece of code creates a new control which inherits from the normal LongListSelector.

- It adds a new dependency property called SelectedItem and hides the SelectedItem property of the base class by using the "new" modifier.

- It explicitly sets the SelectedItem dependency property when the selection changes, which in fact comes down to syncing the dependency property with the  SelectedItem property of  the base class.

 public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
{
    public LongListSelector()
    {
        SelectionChanged += LongListSelector_SelectionChanged;
    } 

    void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedItem = base.SelectedItem;
    } 

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register(
            "SelectedItem",
            typeof(object),
            typeof(LongListSelector),
            new PropertyMetadata(null, OnSelectedItemChanged)
        ); 

    private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var selector = (LongListSelector)d;
        selector.SelectedItem = e.NewValue;
    } 

    public new object SelectedItem
    {
        get { return GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }
}

If you are going to recompile the toolkit, than don't forget to get the latest sources from codeplex. There are some new fixes checked in in the past few days.

If you have any question regarding this blog post or another related thing, feel free to contact me via the comments, the contact form or twitter.

Did you like this? Share it:
Tagged as: , , 2 Comments
27Mar/124

Fixing the LongListSelector part 1: Recompile the source.

Today I came across an issue with the LongListSelector, part of the Silverlight for Windows Phone Toolkit. Solving the issue seemed pretty simple in the end, but first some background.

The LongListSelector is a control that can be used to create a list of groups. A good example of this is the contacts list in the people hub. In that list the contacts are organized based on the first letter of their name. Every group contains a header, in this case the first letter, and using this header you can very easily switch between groups. By using the LongListSelector from the toolkit, developers can create the same experiences in their apps.

The issue I encountered was the fact that I was getting ArgumentOutOfRange exceptions when an item was added to a group dynamically. This issue was supposed to be fixed in the November 2011 release, as stated in the release notes:

LongListSelector bug fixes around OutOfRange exceptions, wrong ordering of items, grouping issues, and scrolling events. ItemTuple is now refactored to be the public type LongListSelectorItem to provide users better access to the values in selection changed handlers.

Well this doesn't seem to be the case exactly. Most of those fixes were actually in changeset 71191 and 71199, which according to the codeplex site are included in the November release. This appears to be not so. When comparing some of the code in the installed Microsoft.Phone.Controls.Toolkit.dll to the source on codeplex it seems to be the case that the installed dll is compiled from a revision at least before 70993.

The solution is simple:

- Download the latest source from codeplex (this currently also includes some fixes to the PhoneTextBox, changeset 74775).

- Compile it.

- Use the resulting dll instead of the one installed by the toolkit.

Happy coding!

Did you like this? Share it:
24Mar/121

FontSize and pixel height in Silverlight for Windows Phone

Recently I came accross the issue where I wanted to limit the number of lines shown in my TextBlock on Windows Phone to for example 3. If the text was longer than 3 lines, the rest of the text should just not be shown. To do this I wanted to set the height of the TextBlock to a fixed height, to be exact 3 times the height of one line. This seems trivial, but to find the height of a line, you need to know something about the way Silverlight measures and calculates heights.

In Silverlight on the desktop and Silverlight for Windows Phone the measuring system is based on pixel units instead of Device Independent Pixel (DIP) units, as it is in WPF. Also the measuring system does not support unit measure string suffixes such as pt, cm or px. Silverlight measurements are always pixel units.

So if we specify the height of a Grid or a TextBlock to be 30 it actually is 30 pixel units. FontSize is no exception to this rule so when you specify 30 as the FontSize, you get a font that from the top of its ascenders to the bottom of its descenders measures approximately 36 pixels. Nevertheless the height of the corresonding TextBlock will be higher, because additional space is used to preserve space between successive lines. This concept is called leading.

In classical typography font sizes are expressed in units of points where a point is almost 1/72th of an inch. Digital typography assumes almost always a value of exactly 1/72th of an inch. This means that text with a font size of 72 points measures approximately 1 inch. Converting between pixels and points is difficult because it depends on the device you are using. Using a printer with 600 dpi (dots per inch) a font with size 72 will measure 600 pixels.

Windows assumes video displayes to have a dpi of 96. Using this assumption one can easily transform pixels into points and the other way around using the following two formulas:

points = 72/96 * pixels = 3/4 * pixels
pixels = 96/72 * points = 4/3 * points

Although Windows Phone screens have a much higher dpi than 96 these formulas also work for the phone. Suppose you want to set a 45 point font. Then you need to set the FontSize property to 60. On top of this Silverlight will add leading, which is approximately 33% of the size set as FontSize, which will result in the height of the TextBlock being 80 pixels.

It is possible to change this behavior by using the LineHeight and LineStackingStrategy properties of a TextBlock. You can read more about it here.

Did you like this? Share it:
13Aug/113

How to override theme resources in Windows Phone 7.5 (Mango)

Windows Phone 7 standard comes with some predefined themes and accent colors the user can choose of. You can read more about them here. This enables aaplications to automatically get adjusted to the users theme which makes the experience for user a lot better, because applications can adjust to the user's preferences. But sometimes this is not what you as a developer want. When you are for example building a facebook application you probably want the app to use the colors facebook uses, but you can of course have your own reason to not have your app always adjust to the current theme.

Windows Phone Themes

The different themes Windows Phone 7 comes with are included in the SDK and can be found in C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Design on 64-bit windows installations and in C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Design on 32-bit installations. Each theme consists of a System.Windows.xaml file which defines the styles for the controls and a ThemeResources.xaml file which defines theme colors, brushes and text styles.

Overriding themes on Windows Phone 7.0

On Windows Phone 7.0 overriding the theme on the phone was quite easy and was well explained here and here. The technique comes down to defining a custom ResourceDictionary and add this ResourceDictionary to the Resources section in the app.xaml file.

<Application x:Class="ThemedApplication.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">

    <!--Application Resources-->
    <Application.Resources>
        <ResourceDictionary x:Key="styles">
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/styles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
    <!--Required object that handles lifetime events for the application-->
    <shell:PhoneApplicationService
        Launching="Application_Launching" Closing="Application_Closing" 
        Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

This resource dictionary can then be used to override theme resources, for example the PhoneBackgroundColor and PhoneBackgroundBrush can be defined to be always white in your application as shown below.

<ResourceDictionary
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls">

	<!-- 100 percent White-->
	<Color x:Key="PhoneBackgroundColor">#FFFFFFFF</Color>

	<SolidColorBrush x:Key="PhoneBackgroundBrush" Color="{StaticResource PhoneBackgroundColor}"/>
</ResourceDictionary>

An example solution is attached at the bottom of this post.

Overriding themes in Windows Phone 7.5 (Mango)

When using the above overriding in a Windows Phone Mango application the technique does not work anymore. The reason behind this probably has to do with the switch between the silverlight 3 runtime and the silverlight 4 runtime which added support for implicit syles and a lot of other xaml changes. In a thread on the App Hub forums, about this technique not working anymore, Peter Torr, Program Manager in the Windows Phone 7 Application Platform team, explained that this was actually a bug in Silverlight on Windows Phone 7.0 and that this is "fixed" in Mango. He also gives two work-arounds you can use in Mango.

The first is the use of implicit styles which is a feature of silverlight 4 that now comes with mango. The problem with this approach is that you have to override the style for all controls to get them use the theme overrides. If you only want to change some colors this option costs a lot more work than before.

The second option is a lot better to implement if you just want to change some theme colors, although it is not as beautiful as simply including an extra resource dictionary. It works by changing the built-in styles instead of overriding them. This changing of styles can be done in the following way.

(App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush).Color = Colors.White;

Another advantage of this technique over implicit styles is that this should also works on Windows Phone 7.0 although I did not test that. A disadvantage is that there is no design-time support when using this technique. One question that comes up is were to place these overrides. I found out by experience that the most useful place to put this overrides is after the InitializeComponent() method call in app.xaml.cs as shown below.

public partial class App : Application
{
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Change default styles
            InitializeStyleChanges();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

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

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        private void InitializeStyleChanges()
        {
            //87 percent Black - #DE000000
            (App.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush).Color = Color.FromArgb(0xDE, 0x0, 0x0, 0x0);
            //100 percent White - #FFFFFFFF
            (App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush).Color = Colors.White;
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }

An example using this technique is also attached below. If you have any questions on this don't hesitate to ask them in the comments.

WP7ThemedApplication

WP75ThemedApplication

Did you like this? Share it:
19Jul/111

Building the City Cloud part 2: WCF Data Services and JSON

When we developed our OData web service we came accross a situation in which we needed our webservice to return JSON in stead of XML. According to the specification OData supports both JSON and XML by including the $format query option. Unfortunately WCF Data Service does not support the $format query option and will return the following error when this query option is provided:

<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <code /> 
    <message xml:lang="en-US">
        The query parameter '$format' begins with a system-reserved 
        '$' character but is not recognized.
    </message> 
</error>

The service tells you that it indeed saw the $format query option but that it didn't recognize it as a valid query option. In this blog post I'm going to show you the different options you have for resolving this little problem.

JSON

JSON stands for JavaScipt Object Notation and is used to interchange data. It is an alternative to XML and became very popular because of its simplicity and the fact that it is very lightweight, easy readable and supported on almost all platforms. It was originally derived from JavaScript, but it is a language independent technology. It especially works pretty fine with JavaScript, because in JavaScript there is no extra parser needed. JSON is primarily used to exchange data between webservices and webapplications.

Enable support for the $format query option

Although WCF Data Service does not support the $format query option it actually supports JSON as an output format. All you need to do is specify "application/json" in the Accept header of your request, but sometimes it is not easy to modify the request headers and sometimes you just want to built an OData compliant data service that supports the $format query option. The basic solution to this problem comes down to removing the $format query option and changing the Accept header to application/json.

You don''t have to do this all by yourself. There are two pieces of code out there that do the job for you:

Both of these pieces of code comes with the nice advantage that they also add support for JSONP callbacks. JSONP is a technique commonly used to circumvent the same origin policy of modern browsers. The same origin policy prevents scripts running on domain1.com to communicate with domain2.com.

DataServicesJSONP

Using the DataServicesJSONP library is very simple. You just need to add the JSONPSupportBehaviour to your data service definition, just like in the picture below and you have full support for JSON and JSONP in your OData web service.

 WCF Data Services Toolkit

Using the WCF Data Services Toolkit not only gives you support for JSON and JSONP, but also adds caching capabilities and offers solutions for a lot different data sources. To use the toolkit in your data service, simply inherit your service from ODataService instead of DataService, just like in the picture below and you have full support for JSON and JSONP in your OData web service.

I created a solution that contains examples of both techniques. You can download it here. The solution contains two wcf services, one that uses DataServicesJSONP and one that uses the toolkit. To compile the code you need to have SQL Compact Edition 4.0 installed. You can install it via the Web Platform Installer or directly via the Microsoft Download Center.

Did you like this? Share it:
Tagged as: , , 1 Comment
16Jul/115

Enabling Smart DJ in the Zune software outside the US

Today I started the Zune software for the first time on my computer. I like the zune software because of the way it looks and how it works. When you start the software for the first time, it starts with an awesome video on the features it provides and how cool it looks. It also shows off Smart DJ, which I find a really great feature, because it is able to generate dynamic mixes based on artist, album or song . Unfortunately when I opened the zune software I couldn't find this feature anywhere in the zune software. It appears that with Zune 4.2 this feature was removed for international users and is only availbale in the US. However there are two workareounds availbale to re-enable Smart DJ outside of the US.

  1. Change the system locale in Windows to US.
  2. Add a specific registry key by following these steps or use this archive, which contains a registry file that, when executed, adds the necessary keys automatically.
    • Close Zune
    • Open the Registry Editor by clicking Start, type regedit in the searchbox and then click regedit.exe.
    • Navigate to HKEY_CURRENT_USER\Software\Microsoft\Zune
    • Right-click the Zune key and choose new->Key
    • Name the key "FeaturesOverride" (without the quotation marks)
    • Select the newly created key and right-click in the right pane.
    • Choose new -> DWORD (32 bit) and give it the name "QuickMixLocal" (again without the quotation marks)
    • Double click "QuickMixLocal" and give it the value "1" (again without the quotation marks)
    • Close the Registry Editor
    • Start Zune. You should now be able to use Smart DJ.

Did you like this? Share it:
Tagged as: , 5 Comments