Category Archives: Windows Phone 7/8

Windows Phone 7/8

Using DataTemplate for visualizing a single item

Data templating is a powerful visualization mechanism used primarily for displaying a large number of objects. Controls such as LongListSelector or ListBox display each item from the bound collection using the appropriate DataTemplate.

But if you have a single instance of some class that has a DataTemplate created for it, you can still use your data templates for visualization. For that we will use ContentControl. read more »

Windows Phone 7/8

Microsoft.Bcl.Async doesn’t work in VS 2012 with XNA projects

Microsoft.Bcl.Async is an awesome library from Microsoft that gives you the full power of the new asynchronous feature for C# 5.0 in .NET 4 projects. You install it via NuGet and it just works.

Unfortunately, it doesn’t “just work” if you are adding it to a XNA Game Studio 4.0/Windows Phone Game (4.0) project. Simple function such as:

public async Task FooAsync()
{
    await TaskEx.Delay(1000);
}

will fail to compile even though the package is added. What gives?

If you take a closer look at the newly added packages, you can see that their path is something like:
\packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.dll. Notice how it says net40? This is clearly the wrong platform, it should be sl4-windowsphone71 instead! The only real solution is to manually add the correct references. First remove any of the following references:

  • Microsoft.Threading.Tasks
  • Microsoft.Threading.Tasks.Extensions
  • Microsoft.Threading.Tasks.Extensions.Desktop
  • System.Runtime
  • System.Threading.Tasks

Now manually add the following assemblies from the packages folder:

  • Microsoft.Bcl.Async.1.0.16\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.dll
  • Microsoft.Bcl.Async.1.0.16\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.Extensions.dll
  • Microsoft.Bcl.Async.1.0.16\lib\sl4-windowsphone71\Microsoft.Threading.Tasks.Extensions.Phone.dll
  • Microsoft.Bcl.1.0.19\lib\sl4-windowsphone71\System.Runtime.dll
  • Microsoft.Bcl.1.0.19\lib\sl4-windowsphone71\System.Threading.Tasks.dll

The versions might change, but the procedure remains the same in case these libraries are updated.

However, there is a catch: you cannot use async/await syntax (or at least I am not sure how to enable it) and you will have to resort to using ContinueWith:

public Task FooAsync()
{
    return TaskEx.Delay(1000).ContinueWith(t => {});
}

If you really want to use async/await in XNA projects, try converting your game to a hybrid XAML/XNA application. It will work like a charm.

Windows Phone 7/8

Using Viewbox for automatic control scaling

Presenting content of varied size can often be tricky. For example, displaying names of metro stations with fixed font size, and it always is a fixed font size, can result in a part of the text being clipped off. Or if you use text wrapping, a large block of text can extend way beyond your intended design. Trimming might help, but you cannot always do that.

Consider the following page:

Simple page without using Viewbox

Simple page using a bunch of controls with default styles

It uses a very simple layout – two equally wide columns. Notice how the default font might be too small for the text on the left and how variation in button captions create problems for buttons on the right. We would like to increase font size for the text on the right, but it is hard to anticipate how large the text would be. Or if there are large words in the text, they might “bleed” onto the right side. As for the buttons, you would want the entire text to be seen.

So how do we do that? Luckily, there is a control that will auto scale any content we give it – Viewbox. Whatever content you give it, Viewbox will auto scale it, either up or down, to fill the space the Viewbox control would normally take. The XAML for the above page looked like this:

<Border BorderBrush="Red" BorderThickness="1"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
    <TextBlock Text="{Binding FullName}"
                TextAlignment="Right"/>
</Border>

<StackPanel Grid.Column="1">
    <StackPanel.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="200" />
            <Setter Property="Height" Value="80" />
            <Setter Property="Margin" Value="10"/>
        </Style>
    </StackPanel.Resources>

    <Button Content="Pick 1" />
    <Button Content="or 2" />
    <Button Content="or any large number" />
    <Button Content="first line&#13;second line" />
</StackPanel>

We wrap the problematic control inside the Viewbox control. The final XAML should look like this:

<Viewbox>
	<Border BorderBrush="Red" BorderThickness="1">
		<TextBlock Text="{Binding FullName}"
			   TextAlignment="Right"/>
	</Border>
</Viewbox>

<StackPanel Grid.Column="1">
	<StackPanel.Resources>
		<Style TargetType="Button">
			<Setter Property="Width" Value="200" />
			<Setter Property="Height" Value="80" />
			<Setter Property="Margin" Value="10"/>
			<Setter Property="Template">
				<Setter.Value>
					<ControlTemplate TargetType="Button">
						<Grid>
							<Border BorderBrush="{TemplateBinding BorderBrush}"
	BorderThickness="{TemplateBinding BorderThickness}"
	Background="{TemplateBinding Background}"
									Margin="{TemplateBinding Margin}">
								<Viewbox>
									<ContentPresenter
		Content="{TemplateBinding Content}"
		ContentTemplate="{TemplateBinding ContentTemplate}"
		Margin="{TemplateBinding Padding}"
		HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
		VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
								</Viewbox>
							</Border>
						</Grid>
					</ControlTemplate>
				</Setter.Value>
			</Setter>
		</Style>
	</StackPanel.Resources>

	<Button Content="Pick 1" />
	<Button Content="or 2" />
	<Button Content="or any large number" />
	<Button Content="first line&#13;second line" />
</StackPanel>

The TextBlock on the left was wrapped in the Viewbox control while the control template for the buttons was modified to put the content inside another Viewbox. The final result can be seen on the image below.

Simple page using Viewbox control

Text scales correctly when using Viewbox control

As you can see from the image, text is now fully visible in the buttons while the text on the left is now scaled up to fill the allocated space. This isn’t full-proof solution because you still need to account for differences between the smallest and the largest text. You could pad the text on both size with spaces, just to ensure that short text doesn’t become really large.

Windows Phone 7/8

Using different WMAppManifest files for release and debug builds

While working on an update for already released application, you might find yourselves having both the marketplace version and developer version. Since they use (almost) the same manifest, you will have a hard time guessing which one is the marketplace version and which one is the one in development. It would be enough to simply change the application’s name, but you might forget to revert the name once the application is published.

Luckily, we can use different manifests for debug and release builds and use build events to replace the manifest depending on the build. read more »

Windows Phone 7/8

Wiki article – Fullscreen XNA games on Windows Phone 8 devices

Windows phone topic So I’ve finally found some time to update the Nokia Developer Wiki article on WP8/XNA problem when running on 720p devices. There are some artifacts present due to the different aspect rations involved.

Read more about it on Nokia wiki.

Thought crime Windows Phone 7/8

“Unfortunately, you can’t do that on Windows Phone”

As I’ve started answering questions about Windows Phone on Stack Overflow, MSDN and Nokia forums, I noticed that many of my answers were essentially paraphrased “Unfortunately, that is not possible to do on Windows Phone.” And it is not as if people wanted to change default search provider to Google (you can’t) or setup your device without Live account (you cannot either), these were developers either anxious to port existing applications from Apple/Android world or fresh ideas for improving Windows Phone platform.

But they’ve all hit dead end in their development career. You simply cannot do lots of cool and interesting applications since you don’t really have access to many APIs, or because you don’t have true multitasking. True, the situation is vastly improved with Windows Phone 8, but some features are still missing. And not only developers are hurting, users are hurting too.

For example, you don’t have read API for accessing SMS messages, mails, internet usage, podcasts, videos, etc. You also don’t have write access to many interesting things. How is that useful, you may ask. Well, I want:

  • …a cool application that tells me with whom I talk or message the most in a given month.
  • …to see cool visualization of my recent activities
  • …backup SMS messages somewhere else
  • …to measure which application is spending most of my expensive bandwidth and maybe block it from accessing internet.
  • …to share which podcast channels I subscribe to and which episodes were my favorite
  • …be able to detect incoming calls and display additional info on screen, like last SMS sent to that person
  • …to be able to hangup a call and send SMS from some template
  • …etc.

Windows Phone features one really cool concept – hubs. The built-in ones cover most of your phone activities: messages, people, games, media. But think of the ways you could extend Message Hub, People Hub, Music+Video hub, Games hub to further increase both my usage of the platform and better engage in various activities.


I could add Steam achievements to Games or put links to HTML5 games directly into the Games hub. I could synchronize custom podcasts from the web – like adding YouTube channels as podcasts or I could add them in music or video libraries. Heck, I might even add my own library. How else am I going to send, receive or edit videos. As for People Hub, the central source for all your social clients, I could add Yammer or Flicker integration. Messaging could also be extended with various clients. Oh, and don’t get me started on music player limitations – you cannot play your own playlists in system player! SongCollection doesn’t have public constructor. How else am I going to turn my phone into cool gadget that I wear all the time with me and recommend to all of my friends. You cannot synchronize cool info for all your local songs, like Last.fm stuff or add scrobbling.

How hard is to enable applications to receive events like “Next Song” or “Pause” from the overlay menu into some sort of application handler?

Really, think about all the possibilities. That would be wonderful for the developers.
That would be wonderful for the users.

But sadly, even with Windows Phone 8 you cannot do any of these stuff. You don’t even have the basic thing like notification center. How hard is to create a ListBox with collection of strings? So how am I going to recommend Windows Phone to someone who wants basic things as internet quota manager or who wants to send template SMSs (e.g. for paying ticket in public transports). Many great ideas, but sandboxed application with severely limited APIs have crippled the platform. And you can’t have podcasts if you are not in USA or something like that.

And don’t compare WP to iOS or Android. Instead of catching up, lead the way for once. If you want people to jump ship, add stuff others don’t have, but sure as hell don’t forget the stuff they already have. Unless Windows Phone evolves, it will be a platform of limited reach and the only people who buy them are going to be the ones that are faithful to the platform.

Others won’t care that much.

Tips Windows Phone 7/8

Debugging C++ components in Windows Phone 8 projects

Windows phone topic When developing Windows Phone 8 applications with C++ components, you will notice that you cannot trigger breakpoint in a native component. Hovering over breakpoint brings tooltip with the text:

The breakpoint will not now be hit. No symbols have been loaded for this document.

To enable debugging for such projects, open project settings for the managed Windows Phone project (the one that references the native component), navigate to Debug and under UI Task select Native only (as seen on the image below). Now the breakpoint will be triggered.

Enabling native debugging

Enabling native debugging

But now you will notice that you cannot debug managed components now. It seems that mixed mode debugging is broken for Windows Phone 8 applications.

Tips Windows Phone 7/8

Enum.GetValues for Windows Phone (and portable libraries)

Windows Phone is missing quite a lot of different things, but I never figured it would be missing something as basic as Enum.GetValues. Since I need it (obviously for my current top secret project), I just went ahead and wrote a replacement. Also, since the original returned Array, I figured that the new and improved method should be much better and that it should return IEnumerable where T should be the enumeration type. It makes code a lot prettier.

So, without further ado, here is the final code:

public static IEnumerable<T> GetValues<T>()
{
    if (!typeof(T).IsEnum)
        throw new InvalidOperationException("Type must be enumeration type.");

    return GetValues_impl<T>();
}

private static IEnumerable<T> GetValues_impl<T>()
{
    return from field in typeof(T).GetFields()
            where field.IsLiteral && !string.IsNullOrEmpty(field.Name)
            select (T)field.GetValue(null);
}

It couldn’t be implemented as an extension method since you cannot define extension methods on a type. You have full freedom to implement this method in e.g. EnumHelpers class. I am also aware that this method has no caching whatsoever implemented and that you will need to do that in case you are using it in highly performant code, but this will suffice for basic daily needs.

Happy coding.

Windows 8 Windows Phone 7/8

Async, portable libraries and Windows Phone 7 in Visual Studio 2012

Windows phone topic Portable classes in Visual Studio 2012 are simply awesome. They allow high code reuse for multiple platforms. Another great addition in Visual Studio 2012 is support for asynchronous programming in C# 5 which, sadly, was not initially available for Windows Phone 7 developers.

If you want to target Windows Phone 8 and Windows Store, you can use Async if you also target .NET 4.5. If you want to target Windows Phone 7.1 and Windows Store, you cannot use asynchronous features from C# 5. But with the prerelease version of Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone 7.5 and 8 you can finally use Async in your Windows Phone 7 applications. If you want to target largest market, you need to support Windows Phone 7 along with Windows Phone 8, it is too large to simply ignore.

So, can we use Async in portable libraries while still targeting both Windows Phone 7 and Windows Store? Luckily, the answer is yes. But, and there is always a but, with one caveat – you must target .NET 4.0 instead of .NET 4.5.

The procedure is simple: create a new Portable Class Library and select the targets as seen on the image below:

Targets for Portable Class Library project

Portable Class Library targets

To add Async support, run the following command in the Package Manager Console:

Install-Package Microsoft.Bcl.Async -Pre

Voila, you can now write asynchronous code in a portable class library which can then be linked in Windows Phone 7, Windows Phone 8 and Windows Store projects. If you build a Windows Phone 7 application and link to such portable class library, you will need to add the same NuGet package to that project also.

Windows Phone 7/8

Using SignalR on Windows Phone 7

Windows phone topic If you need real time communication between two or more clients and you are using Microsoft stack, SignalR is the way to go. If you take a look at their github samples, you’ll notice that they already have sample for Windows Phone 8. What about Windows Phone 7 support? Well, due to the beauty of open source, you simply fork it and write the missing client library.

However, this might not be as easy as one thinks. Open the Microsoft.AspNet.SignalR.sln solution and locate Microsoft.AspNet.SignalR.Client.WP8. If you take a closer look, you’ll notice that this project consists only of linked files shared with other client libraries. So let’s add a new project and name it Microsoft.AspNet.SignalR.Client.WP7 (although it would be better to name it 7.1 or 7.5). Now drag all files and folders from the WP8 project to the WP7 project while holding down the Alt key. This adds files as links instead adding their copies. Once you are done, hit Compile.

It won’t compile you say. Of course it won’t, so let’s fix it. read more »