Category Archives: Development

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 8

Create app bar button icons using Segue UI Symbols font

Creating app bar buttons for WinRT applications is easier than creating them for Windows Phone applications. While Windows Phone uses transparent images for app bar buttons, WinRT applications use built-in Segoue UI Symbol font for that purpose. This simplifies things quite a bit since we don’t have to trouble ourselves with scaling, picking correct size for the app bar images and theming (in case we need black and white versions). If you took a look at the default styles that come for WinRT applications, you could notice that they don’t use any images, they are simply referencing a particular symbol in the font. read more »

Web

CSS Grid Layout – layout for everyone

One of the best things about XAML is the ability to create both simple and complex layouts with a handful of container controls. Although clearly inspired by HTML, XAML introduces a bunch of controls that serve mostly for managing layouts rather than displaying some content. If you wanted simple layout and if you wanted to avoid being labeled as “the one who used tables”, you would have to resort to some pretty nasty stuff. But no matter what you did to your floating divs, you could not create a simple 2×2 grid layout.

So if you want the power of tables, but wanted to write correct HTML+CSS, you could use Bootstrap or similar frameworks. You get fluid grid design and you can spend time designing other things instead of battling with HTML and writing your own JS code. Finally, all was well…or at least better. We still lacked “native” solution for designing grid layouts. Browsers are capable of doing that, if only there was a way…

And that way is CSS Grid Layout. The strange thing is that I am testing it in Internet Explorer 10. The same browser made popular by the definition “does it work in IE? No? It is HTML5 feature”. You still need to add -ms- prefix though.

After small fiddling with jsbin, here is a result (remember, only in IE10):
JS Bin

You can read more on Hugo’s blog post: Future of CSS layout: CSS Grid.

Web

Combining three.js and KineticJS [updated]

I wrote already how to combine three.js and Kinetic.js in the previous blog post. Since then, both libraries have evolved and the same code won’t work anymore so here is the update.

First, KineticJS is now initialized slightly differently. Instead of passing arguments, you pass a config object. The following code will construct a new KineticJS.Stage object:

stage = new Kinetic.Stage({
    container: "container",
    width: 700,
    height: 700
});

Three.js requires an HTML5 canvas element, not KineticJS wrapper around it. The correct way to initialize it is:

renderer = new THREE.CanvasRenderer({canvas: layer3D.getCanvas().getElement()});

Note: if you want to use WebGLRenderer instead of CanvasRenderer, the above code will not work. I will write a follow up post for that scenario soon.

You can see my new sample here.
Here is a jsfiddle version http://jsfiddle.net/hXw6D/3/.

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.