This is first post in the series describing the navigation pattern in XAML based application. The series will focus on problems and solutions that arise when using MVVM (Model-View-ViewModel) and XAML. Even though they are meant to be used together, the MVVM pattern does not solve navigation completely nor correctly.

WPF and Silverlight: introduction

Windows Presentation Foundation was introduced almost 10 years ago. Besides introducing a new and beautiful way of creating UI declaratively, it also introduced a new pattern based on the powerful data binding mechanism: MVVM. Since it was born on desktop, WPF applications consisted of windows and dialogs.

A few years later we got Silverlight: a version of WPF (also known as WPF/E where E stands for everywhere) trimmed down and optimized for the web. Due to its architecture and the fact it was used in browsers, it also introduced a navigation stack and navigation capabilities. Its primary purpose was mimicking how browsers navigate from one page to another. The Frame contained Pages and navigation was done through (mapped) URIs. Using URIs for navigation had one serious implication: when navigating from one page to another, you could only send strings, or objects that can be converted to strings, through the query string. read more »

Xamarin.Forms are awesome for building applications, but eventually you have to get dirty and fix platform specific issues. And once down there, one quickly realizes that native development is not so much different than native development for that platform itself.

Let’s take a look at the relatively simple problem with iOS: changing the unselected color for the tab bar icons. Searching the web brings us to the den of programming solutions, Stack Overflow, with the following solution http://stackoverflow.com/questions/11512783/unselected-uitabbar-color. The code is straightforward:

UIColor * unselectedColor = [UIColor colorWithRed:184/255.0f green:224/255.0f blue:242/255.0f alpha:1.0f];
item.image = [[item.selectedImage imageWithColor:unselectedColor] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

read more »

If you are using Xamarin Forms for your next awesome cross-platform mobile app, there are things you need to remember when dealing with images for Android.

1. No folders

Even though you can group images into subfolders at root level for Windows Phone or under Resources for iOS, all images have to be inside the Drawable folder for Android. Images in folders are not used.

However, Images/picture.png still resolves on Android.

Which brings us to the obvious…

2. No duplicates

You cannot have two images with the same name in two different folders like Company1/Logo.png and Company2/Logo.png.

Because you cannot have two files with the same name in the same folder.

However, there are still problems with file names…

3. Invalid characters in file names

After reading point 2, you renamed your files and put all images into Drawable. You renamed those files with the same name to something more obvious like Company1-Logo.png and Company2-Logo.png. And it still doesn’t work.

// aapt resource value: 0x7f020020
public const int Icon = 2130837536;

Picture above: Android’s awesome resource handling code.

Due to the way resources are processed in Android, all file names are converted to C# identifiers. And you can resolve images by using their C# counterpart. This, unfortunately, means that only those file names which are valid C# identifiers are valid file names.

This means removing dashes and using underscores. This also means that your images starting with numbers are also invalid. Forget all those 1.png and 13thStreet.pngh, use some “better” names.

Till’ next time, happy coding.

This advice is no longer valid as of Xamarin.Forms 1.3.3. The current implementation for the ObservableCollection fixed this bug.

Xamarin.Forms are awesome, but the framework is young and there are some very annoying bugs. Consider the following common, and simple, scenario: you have a ListView bound to an ObservableCollection. If you want to clear/fill that list, e.g. you are building a search page, you will get the following errors (the numbers may vary):

MonoTouch.Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

There is a simple workaround: clear the list by removing each item individually. Instead of writing:

list.Clear();

use:

while (list.Any())
    list.RemoveAt(list.Count - 1);

Happy coding :)

2014 was a turbulent year with lots of fun stuff. I finally quit my day job and became a full time freelancer working on Windows Phone, Windows Store, Xamarin and ASP.NET projects. Even though it’s only been a few months, I must say I am enjoying it so far. As usual I gave a few talks at regional conferences, blogged a little, and was renewed as MVP for C# for the second year in a row.

With all that behind me, it’s time to prepare for the future and this post will serve as both a todo list and a reminder for next year’s me. It will be fun comparing what I wanted to do and what I actually managed to do.

Without any particular ordering, here is the grand list of things for the year 2015:

  • Working more on side projects – there are quite a lot of ideas gathered over the year, let’s see which projects are worth pursuing and which projects are not. Hopefully some of them will create some income, but I wouldn’t bet on it. Lots of these side projects include .NET Compiler Platform aka Roslyn in one form or another. If I manage to finish any of ideas based on Roslyn, they might prove beneficial for the community.
  • Startup stuff – yes I know they are all the rage right now. My brother and I joined Core Hub contest with the idea of building scalable real-time platform on .NET. There are some other ideas in the pipeline, mostly about tourism and IT, but those are ideas for this summer/autumn.
  • Blog a little bit more – I should blog more regularly about what I am doing and fun stuff I encounter. I have a bad habit of starting a new series and forgetting all about it. Not anymore! Writing should ease my mind, not add more burden to it. So let’s make that 52 blog posts this year.
  • Games! – ever since I became a programmer I wanted to work in game industry. Actually, creating games was the sole reason for learning programming in the first place. That’s why I decided to join One Game a Month Challenge and see if I can do it. I’ve made zero games so far in my career so let’s make 12 games this year alone :)
  • Open source stuff – most of my side projects/ideas/games can and will be open source. In fact, the first game I am working on this year is already at GitHub and you can check it out here
  • Speaking at conferences – speaking at conferences became a regular thing for me, but there is always next level stuff. This year I will speak about Roslyn at DevWeek conference in London which marks my first conference outside of mainland Europe :)
  • Traveling – so it seems I travel twice a year to USA, once for Build and once for MVP Summit. I want to keep that tradition and I want to add a few more locations around the world if possible. After all, technology does connect us all.
  • Learn a new language – and by that I mean programming language. Since functional programming is all the rage, let’s dive into Haskel and/or F# to see what they can offer.

Well, that will keep me busy :) It will be fun working on any and all of these, but realistically I cannot do all of them. Some things I am already working on. Some things can be combined (open source and games/side projects). The more I manage to do, the better.

So, what is your list for 2015?

Update: the code was updated to support two additional scenarios: inherited classes and classes that cannot inherit DependencyObject<T>.

Writing dependency properties for XAML controls is annoying and contains some redundant parts. Let’s take a look at an example dependency property (generated from snippet):

public static readonly DependencyProperty PropertyTypeProperty = DependencyProperty.Register(
    "PropertyType", typeof (propertyType), typeof (SampleDependencyObject), new PropertyMetadata(default(propertyType)));

public propertyType PropertyType
{
    get { return (propertyType) GetValue(PropertyTypeProperty); }
    set { SetValue(PropertyTypeProperty, value); }
}

While the property (at the bottom) itself cannot be simplified anymore, the registration part at the top can be simplified quite a lot. Let’s take a closer look at the necessary parameters:

  • First is the property name which one should never write in string literals. The new feature in C# 6: nameof will help fix that, but for now we are stuck with this.
  • The second parameter is the type of our property, which is already written below and should somehow be inferred automatically. Reflection could help with that, but it’s a heavy artillery and is not an ideal solution here.
  • The third parameter is the type of the enclosing class, a context sensitive information that should be omitted.
  • Finally, in most cases the default value is the default value for the property type.

Our goal here is to remove redundancy, use contextual information and remove string literals all in once. And to shorten our code, of course. Luckily, we can already do that in C# 5 without the upcoming nameof feature and the final syntax for the registration part (the property, unfortunately, stays the same) can be reduced to this:

public static readonly DependencyProperty SampleProperty = Register(d => d.Sample);

read more »

Converters are an essential building block in XAML interfaces with one simple task: converting values of one type to another. Since they have a input, usually a view model property, and an output, it would be wonderful if we could somehow chain them to create a new converter that processes all internal converters. Luckily, this is quite simple to do, but we do need to create a new converter which will hold other converters and whose implementation will iterate over nested converters. Full code can be found over at Github repository here, only interesting parts will be highlighted in this blog post.

Our combining converter class is also a converter itself, but it can contain other converters inside it:

[ContentProperty("Converters")]
public class ChainingConverter : IValueConverter
{
	public Collection<IValueConverter> Converters { get; set; }
}

Converter functions are trivially implemented and iteratively go through the converters list and apply the converter on the previous value.
read more »

When it was introduced, LINQ to Objects brought something very interesting to C# world – fluent API. Take a look at the following code:

var result = list.Where(i => i.Extra != null)
                 .Select(i => i.Extra)
				 .OfType<Advanced>()
				 .ToList();

Ignoring the types of objects involved, the underlying algorithm, nay, the purpose of this code is visible at a glance. We take the list of objects, extract only those that satisfy the given condition, create a projection, cast to a new type, filter out null values, and finally create the resulting list.

Working with collections allows method chaining because all methods are actually defined as extension methods on IEnumerable<T>. Chaining is something we are also used to when dealing with objects. Calling a member function or changing the property of a property is a simple matter of typing dot, writing member name, typing dot again, etc.

In case you are a fan of that coding style, you might find the following code slightly annoying to write:

((Bar)foo).Invoke();

Why would that be annoying, that is perfectly legal C#! And quite common actually. To better understand the source of frustration, let’s see how one would arrive at such code.
We start with innocent variable foo of some type. It is irrelevant which type it is and all we know at that point is that we want to invoke the method cleverly named Invoke on it. However, after typing dot, we realise that foo is actually an instance of some other type and that we need to cast it first to get to an appropriate type. Let’s ignore type checking and presume that we know that foo is indeed what we need (e.g. attached properties in XAML platforms have this pattern; even though it is an object, you know what type it is).

So have the following code currently on the screen at that moment:

foo.

To cast foo to an appropriate type from we need to add go back to the beginning of the expression and add two left braces, the appropriate type, right brace, go to end of the expression, put the brace just before the dot and then move cursor to the right and we can now find Invoke in our auto complete list.

This little process disrupts our natural flow. It would be so much easier if we could somehow continue typing to the right of dot once we realise that our variable is not of the correct type.

Something like:

foo.Cast<Bar>().Invoke()

read more »

One can argue that BooleanToVisibilityConverter is rooted deeply in the XAML-based platforms. It is the simplest IValueConverter one can implement and you can find it implemented in various toolkits, frameworks or simply reimplemented time and time again by developers. Part of the reason is that the default facility for showing and hiding is unbindable to regular boolean property.

Historical reason for this can be found in WPF where controls can be in one of the three following states: Visible, Hidden, and Collapsed. When Silverlight was introduced, the Hidden state was removed and only two possibilities existed and which correspond to boolean states.

However, the syntax is atrocious. Look at the following example:

Visibility={Binding IsVisible,
                    Converter={StaticResource BooleanToVisibilityConverter}}

Imagine writing that every time you need to hide a control? Well, you just imagined a lot of code out there.

So, how can we fix this and shorten the syntax? By using attached properties of course. Even though there is no such thing as an IsVisible property, it doesn’t mean we cannot invent one ourselves. The final syntax appears similar to this one:

common:Alt.IsVisible={Binding IsVisible}

Isn’t that much readable? Both the namespace and the owner class names can be shortened to get an even shorter syntax.

Here is the implementation:

/// <summary>
/// Definition of alternative attached properties for various
/// controls.
/// </summary>
public static class Alt
{
	public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
		"IsVisible", typeof(bool?), typeof(Alt), new PropertyMetadata(default(bool?), IsVisibleChangedCallback));

	private static void IsVisibleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		var fe = d as FrameworkElement;
		if (fe == null)
			return;

		fe.Visibility = ((bool?)e.NewValue) == true
			? Visibility.Visible
			: Visibility.Collapsed;
	}

	public static void SetIsVisible(DependencyObject element, bool? value)
	{
		element.SetValue(IsVisibleProperty, value);
	}

	public static bool? GetIsVisible(DependencyObject element)
	{
		return (bool?)element.GetValue(IsVisibleProperty);
	}
}

The source code and the accompanying sample project can also be found on the Github repository here: github.com/MassivePixel/wp-common.

In case you haven’t heard the news, the new version of Visual Studio is out: Visual Studio 2015 Preview. You can grab it here. With you’ll get:

  • A new version of C# language currently at version 6
  • .NET Compiler Platform formerly known as Roslyn: the new compiler for C# and VB.NET which is open source and exposes quite a lot of the underlying infrastructure for the user
  • New JIT compiler i.e. RyuJIT which is also open source
  • Open source subset of .NET Framework

Small things really :) This post will focus on the new features in C# 6 which can both shorten your code and make it more understandable. So let’s begin. In fact, only a couple of new features can be used to add more code to your existing code base.

Class properties enhancements

Writing immutable classes is relatively hard in C# and a few small additions to the language make things easier. Take a look at the following class: read more »