Tag Archives: C#

Windows Phone 7/8

Async and RestSharp for Windows Phone 7

Windows phone topic I have mentioned RestSharp quite a lot of times, it is simply an essential library for building applications that communicate to the outside world. Ever since Async CTP shipped for Windows Phone 7, I wanted to make everything asynchronous. RestSharp comes with asynchronous methods already built in, but they are not compatible with Async since they don’t return Task.

But we can fix that easily with our good friend TaskCompletionSource<T> read more »

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.

Windows Phone 7/8

ListBox empty template – using control templates and behaviors (part 2)

This article requires update, please wait for it. For those who can’t wait, the problem is that you need to define an additional dependency property for empty template. You cannot simply set control template to null. I apologize for the inconvenience.

Windows phone topic In the previous post I have shown how to fake “empty ListBox template” using visual states. The proposed solution is very intrusive since it requires editing the built-in (or customized) control template. You have to design the template carefully to avoid any visual state corruption.

And if we want to introduce the third template, let’s say we want to have also “download in progress” template (similarly to the way Marketplace search works), the control template would become unmanageable. It would be best to completely separate each template from normal template, and this is exactly what we are going to do today.

The final result will give us something like this:
All states for list box; from left to right: progress, default, empty
read more »

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");
Development

FastSharp – building a fast C# prototyping tool using Roslyn and AvalonEdit

FastSharp in action I’ve had this idea about building a fast code prototyping tool for a while now. You can use LINQPad to test LINQ queries against lots of data sources, but it cannot provide fast code prototyping. The obvious solution was to go and build a custom tool. Open source to the rescue.

For such tool I needed two parts: visual editor for displaying source code and an interpreter to actually compile and execute that code. I wanted to use WPF for building UI and there is an excellent control that offers syntax highlighting – AvalonEdit. As for the code compiling and execution, I use Roslyn – a great project from Microsoft. read more »

Windows Phone 7/8

Using ImageTile control from Coding4Fun v1.6

New version of Coding4Fun Toolkit was released three days ago, you can grab it at Codeplex. One control immediately grabbed my interest – ImageTile. It offers a variation of standard hub tile and looks similar to the people hub tile, although you can easily customize it. The following screenshot shows the ImageTile control in action.
read more »

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.

Windows Phone 7/8

ListBox empty template – using visual states (part 1)

ListBox can be customized in a lot of different ways: you can change the item template, the container or the control template. However, there are some common states which cannot be easily set. For example, if you want to display “No items match your query” as a property of the ListBox itself, there is no such template. Similarly, the template for “data is loading” does not exist. These are all common requirements for building a pleasant UX.

When you are searching the WP7 marketplace from your phone you will get a message when no applications can be found with the specified criteria. Also, before the search is complete, the progress indicator is displayed in the middle of the ListBox indicating that it is currently being filled. This is somewhat better UX than using the progress indicator in the system tray since the user knows that the list box is not ready rather than the generic “application is doing something so please wait.” We want to replicate such design easily. Luckily, you can achieve this functionality in several different ways:

  1. Place an invisible TextBlock element which will be visible when there are no elements found. Toggle the visibility in your OnCompleted handler.
  2. Create a user control which contains the logic and a dependency property for the “empty message”
  3. Inherit custom control from ListBox and create custom control template.

In the first solution you have to add elements to the page which should not belong there, maintenance is reduced and you have to c/p the same snippet all over the place. In the second solution you lose the ability to simply style the ListBox control inside the UserControl. There should be a simple, portable (in a sense that we can apply it to other ListBox-like control like controls), maintainable and customizable solution. The third solution prevents you from enhancing other inherited ListBox controls which might be detrimental.

In this post I will present one method for adding such “empty template” and “progress template” using visual states. read more »