Category Archives: Tips

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.

Tips Windows Phone 7/8

Naive HashSet implementation for Windows Phone 7

Windows phone topic HashSet<T> is a nifty little class that is, sadly, missing from Windows Phone 7. Since I need it in some of my projects, I made this simple and naive implementation that is compatible with Windows Phone 8 version of it. This will make the code sharable between Windows Phone 7 and Windows Phone 8 projects.

It is implemented as a naive wrapper around Dictionary<T, bool>. I really hope that Windows Phone 7.8 will have (better) native implementation. You can check out the implementation over at GitHub.

You can also get it as package from NuGet:
PM> Install-Package WP7Helpers.Common.HashSet

Tips

Visual Studio 2012 gives strange error when adding reference? Unblock the file first

I have come across this strange error Visual Studio 2012 gives when adding reference to an assembly freshly downloaded from the internet:

Visual Studio 2012 complains about adding assembly reference

Visual Studio 2012 complains about adding assembly reference

Although the message is cryptic, the solution is to find the assembly in Windows Explorer, right click on it and click Unblock. As simple as that.

Tips

Deserializing POC objects from strings using RestSharp deserializators

Windows phone topic RestSharp is a wonderful little library for communicating with REST services. There is one thing I like in particular – their forgiving deserialization classes. They are awesome, but they cannot deserialize plain strings. If you take a closer look at the Deserialize methods, you will notice that they accept an object of the class that implements IRestResponse. If you inspect the source code (it is open source over at github), you will see that only Content property is used.

So, let’s implement our FakeResponse class that will wrap our string:

public class FakeResponse : IRestResponse
{
    public string Content { get; set; }

    // default implementation is OK
}

You can now deserialize it with the following snippet (xml holds the XML text read from some source other than web response):

var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
var rss = xmlDeserializer.Deserialize<Data.Rss>(new FakeResponse() { Content = xml });
Tips

Iterate over enumeration values in C#

C# topic This is Just a small method that allows iterating over enumeration values. I needed strong type and LINQ support for enumeration values, but the built in method returns Array which is unusable. You have to convert each value to the enumeration type using Cast<T>.

The generator function is given as:

static class EnumEx
{
    public static IEnumerable<T> GetValues<T>()
    {
        foreach (T value in Enum.GetValues(typeof(T)))
        {
            yield return value;
        }
    }
}

You can use it in the following manner:

foreach (var value in EnumEx.GetValues<someEnum>())
{
    // ...
}

The official way to achieve the above functionality with built in stuff in .NET 4 is using the following not-so-short code:

foreach (var value in typeof(enumStructureParameters)
                             .GetEnumValues()
                             .Cast<enumStructureParameters>())
{
    // ...
}

Happy coding.

Tips

Never return null collection

Empty or null, that is the question The distinction between an empty collection and a non-existent collection is rarely required. If a method is supposed to return IEnumerable<T>, you should definitely return Enumerable.Create<T>(). It is simply horrifying that one should return null to indicate that the collection does not have any elements or that some error happened.

Chaining LINQ operators should never be followed with the question “but what if the collection is null?” It should never be null, only empty.

If you have some method for which you are unsure if it will return null or if you know that it can return null, but you do not want to handle that, you can use this handy extension method:

public static IEnumerable<T> Ensure<T>(this IEnumerable<T> @this)
{
    return @this ?? Enumerable.Empty<T>();
}

Now you can be sure that the LINQ query is well formed by simply chaining the Ensure method after a problematic function call:

conglomerate.GetValidCompanies()
            .Ensure() // don't worry
            .Where(c => c.Country == "Germany");
Tips Windows Phone 7/8

Text button that tilts when you tap it

While designing a Windows Phone app, I came a across a simple design problem: how to display text control which will serve as a button. You can tap it, it will display visual cue i.e. it will tilt when tapped and the application will then perform some action.

If you want to catch the tap event on the text control, you must first set the IsHitTestVisible property to true. If you forget to set it, you will not receive anything in your event handler.

However, the text won’t display any visual cue that you have tapped it, it remains static. You can add the Silverlight Toolkit for WP7 package which contains the TiltEffect class. But it still won’t work. The text simply will not tilt.

Luckily for us, we can use the control that is usually used for such purpose – button. However, we must style it to hide the border. We will simply change the default template and set the desired text as its content. The XAML code looks like this:

<Button>
    <Button.Template>
        <ControlTemplate>
            <Grid>
                <ContentPresenter />
            </Grid>
        </ControlTemplate>
    </Button.Template>
    <Button.Content>
        <StackPanel>
            <TextBlock Style="{StaticResource PhoneTextLargeStyle}"
                        Text="Call number"
                        toolkit:TiltEffect.IsTiltEnabled="True" />
            <TextBlock Style="{StaticResource PhoneTextNormalStyle}"
                        Foreground="{StaticResource PhoneAccentBrush}"
                        Text="555-505234"
                        toolkit:TiltEffect.IsTiltEnabled="True" />
        </StackPanel>
    </Button.Content>
</Button>

The final result is visible on the following image:

Tips Windows Phone 7/8

Drawing accuracy circle in bing maps on WP7

While developing a location-based application, I was experiencing strange problems with the GPS service accuracy. My location varied wildly all over the place and I needed a better way to visualize my location. Along with drawing a marker on the map indicating where I am, I also a wanted to draw a circle around it to see what is the accuracy threshold for it.

When GeoCoordinateWatcher sends a notification about a new position, you can retrieve the horizontal accuracy information via the GeoCoordinate.HorizontalAccuracy property. Since there is no circle or ellipse shape for map, you can approximate it with MapPolygon. I’ve declared it in the following way:

<my:MapPolygon Fill="#99FF0000" Stroke="Red"
                StrokeThickness="1"
                Opacity="0.6"
                x:Name="precision" />

The code is adapted from Steve Strong’s blog post. The full code for drawing a circle:

private void UpdatePrecision(GeoCoordinate location)
{
    precision.Visibility = Visibility.Collapsed;
    if (location == null)
        return;

    precision.Visibility = Visibility.Visible;
    precision.Locations = new LocationCollection();

    var earthRadius = 6371;
    var lat = location.Latitude * Math.PI / 180.0; //radians 
    var lon = location.Longitude * Math.PI / 180.0; //radians 
    var d = location.HorizontalAccuracy / 1000 / earthRadius; // d = angular distance covered on earths surface 

    for (int x = 0; x <= 360; x++)
    {
        var brng = x * Math.PI / 180.0; //radians 
        var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));
        var lngRadians = lon + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));

        var pt = new GeoCoordinate(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);
        precision.Locations.Add(pt);
    }
}

On the image below you can see it in action.

Since emulator is very “precise”, I had to zoom in a bit. In regular usage the accuracy will vary.

Tips Windows Phone 7/8

Changing the background for panorama title and panorama header

Control styling is an important feature in XAML and all controls that come with any framework based on it are subject to styling. Panorama is no exception to this and although it can be styled, it is not immediately obvious how to do it. For example, if we want to add background color to the panorama title and the panorama item header (similar to the Facebook app for WP7), changing the background for either control will not do the trick.

Then there are Panorama.TitleTemplate or PanoramaItem.HeaderTemplate and you can change them with the following code:

<Style TargetType="controls:Panorama">
    <Setter Property="TitleTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border Background="AliceBlue">
                    <TextBlock Text="{Binding}" />
                </Border>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="controls:PanoramaItem">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border Background="AliceBlue">
                    <TextBlock Text="{Binding}" />
                </Border>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

But the result is not satisfying:
read more »