Colin Eberhardt's Adventures in .NET

Windows Phone 7 – Browsing your Photos via Bing Maps

January 16th, 2012

The Windows Phone 7 camera gives you the option to record the location where a picture was taken (under Settings => applications => pictures+camera). With this feature turned on, each application has their latitude, longitude and altitude stored as part of the standard EXIF data. I thought it would be fun to combine the previous blog post I wrote on pushpin clustering with the photos on my camera, to allow me to explore them via a Bing Maps control. With not much more than 100 lines of code I came up with an application which I think is a lot of fun to use.

Here are all the photos on my phone, note the way the pushpins are clustered.

Here are a few pictures I took in New York, of the One World Trade Centre and the Stock Exchange.

Here are some pictures around Europe, including one of Gergely Orosz waiting for his turn in the Edinburgh Marathon Relay.

And finally, some pictures I took whilst running around Kielder Water during Kielder marathon.

Accessing the EXIF data

You can access the photos on a WP7 device via the XNA MediaLibrary class. The interface that this class provides gives you access to Picture instances which have properties that allow you to access the width / height and a few other basic attributes. They also have methods that return streams which can be used to read the thumbnail and image data, however, they do not expose the picture location. This is ‘hidden’ within the EXIF data.

Fortunately there is a C# implementation of an EXIF decoder available on codeproject, which, with a few tweaks by Tim Heuer works just fine within Silverlight for Windows Phone 7.

With this library, accessing the EXIF data is a one-liner:

JpegInfo info = ExifReader.ReadJpeg(picture.GetImage(), picture.Name);

The JpegInfo class exposes the raw EXIF geolocation data, which is detailed in the EXIF specification as being expressed as separate components of degrees, minutes and seconds together with a reference direction (North / South, East / West). We can convert from the sexagesimal numeric system used in EXIF, to the decimal system as follows:

private static double DecodeLatitude(JpegInfo info)
{
  double degrees = ToDegrees(info.GpsLatitude);
  return info.GpsLatitudeRef == ExifGpsLatitudeRef.North ? degrees : -degrees;
}
 
private static double DecodeLongitude(JpegInfo info)
{
  double degrees = ToDegrees(info.GpsLongitude);
  return info.GpsLongitudeRef == ExifGpsLongitudeRef.East ? degrees : -degrees;
}
 
public static double ToDegrees(double[] data)
{
  return data[0] + data[1] / 60.0 + data[2] / (60.0 * 60.0);
}

Analysing the images

When the application starts a BackgroundWorker is used to read the EXIF data for all of the pictures in the phone’s media library, with those that have geolocation data available being stored in a separate list:

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
 
// analyse the pictures that reside in the Media Library in a background thread
bw.DoWork += (s, e) =>
{
  var ml = new MediaLibrary();
 
  using (var pics = ml.Pictures)
  {
    int total = pics.Count;
    int index = 0;
    foreach (Picture picture in pics)
    {
      // read the EXIF data for this image
      JpegInfo info = ExifReader.ReadJpeg(picture.GetImage(), picture.Name);
 
      // check if we have co-ordinates
      if (info.GpsLatitude.First() != 0.0)
      {
        _images.Add(new LocatedImage()
        {
          Picture = picture,
          Lat = DecodeLatitude(info),
          Long = DecodeLongitude(info)
        });
      }
 
      // report progress back to the UI thread
      string progress = string.Format("{0} / {1}", index, total);
      bw.ReportProgress((index * 100 / total), progress);
 
      index++;
    }
  }
};
 
// update progress on the UI thread
bw.ProgressChanged += (s, e) =>
  {
    string title = (string)e.UserState;
    ApplicationTitle.Text = title;
  };
 
bw.RunWorkerAsync();
 
// when analysis is complete, add the pushpins
bw.RunWorkerCompleted += (s, e) =>
  {
    ApplicationTitle.Text = "";
    AddPushpins();
  };

When the pictures have all been analysed, a pushpin is created for each image which is then added to the clusterer described in my previous blog post.

private void AddPushpins()
{
  List<Pushpin> pushPins = new List<Pushpin>();
 
  // create a pushpin for each picture
  foreach (var image in _images)
  {
    Location location = new Location()
    {
      Latitude = image.Lat,
      Longitude = image.Long
    };
 
    Pushpin myPushpin = new Pushpin()
    {
      Location = location,
      DataContext = image,
      Content = image,
      ContentTemplate = this.Resources["MarkerTemplate"] as DataTemplate
    };
 
    pushPins.Add(myPushpin);
  }
 
  // add them to the map via a clusterer
  var clusterer = new PushpinClusterer(map, pushPins, this.Resources["ClusterTemplate"] as DataTemplate);
}

The template used for the pushpins simply renders the image thumbnail:

<DataTemplate x:Key="MarkerTemplate">
  <Border BorderBrush="White" BorderThickness="1">
    <Image Source="{Binding Picture, Converter={StaticResource PictureThumbnailConverter}}"
            Width="80" Height="80"/>
  </Border>
</DataTemplate>

This makes use of a simple value converter which takes a Picture instance and converts it into a BitmapImage which is used as the Source for the image:

public class PictureThumbnailConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    Picture picture = value as Picture;
    BitmapImage src = new BitmapImage();
    src.SetSource(picture.GetThumbnail());
    return src;
  }
 
  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return null;
  }
}

The puhspin clusterer allows you to specify a separate template for clustered pushpins. The DataContext for this template is a list of the DataContexts of the clustered pins that it represents. For this application I created a template which renders what looks like a ‘stack’ of images. The number of pictures in the cluster is rendered as a TextBlock and the last image in the cluster rendered.

<DataTemplate x:Key="ClusterTemplate">
  <Grid Width="75" Height="75">
    <Canvas>
      <Border Style="{StaticResource FakePhoto}"
              Canvas.Left="0" Canvas.Top="0"/>
      <Border Style="{StaticResource FakePhoto}"
              Canvas.Left="5" Canvas.Top="5"/>
      <Border BorderBrush="White" BorderThickness="1"
              Canvas.Left="10" Canvas.Top="10"
              DataContext="{Binding Path=., Converter={StaticResource LastConverter}}">
        <Image Source="{Binding Picture, Converter={StaticResource PictureThumbnailConverter}}"
                Width="60" Height="60"/>
      </Border>
      <TextBlock Text="{Binding Count}"
                  Opacity="0.5"
                  Canvas.Left="25" Canvas.Top="15"
                  FontSize="35"/>
    </Canvas>
  </Grid>      
</DataTemplate>
 
<Style TargetType="Border" x:Key="FakePhoto">
  <Setter Property="Width" Value="60"/>
  <Setter Property="Height" Value="60"/>
  <Setter Property="BorderBrush" Value="White"/>
  <Setter Property="Background" Value="Black"/>
  <Setter Property="BorderThickness" Value="1"/>
</Style>

The code that renders the last image is a bit cunning, it uses a value converter that performs a Linq style ‘last’ operations, extracting the last items from a collection of objects:

public class LastConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    IList enumerable = value as IList;
    return enumerable.Cast<object>().Last();
  }
 
  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return null;
  }
}

This feels quite neat to me :-)

The clustered pins look like the following, which is a cluster of 5 images around Paris, with the stunning La Grande Arche de la Défense as the image at the top of the cluster:

Despite its simplicity, I have had a lot of fun playing with this application. It has certainly encouraged me to take as many photos as possible whenever I go travelling.

You can download the full sourcecode here: PhotoBrowser.zip

Regards, Colin E.

A Windows Phone 7 Slide View with Page Pips

December 8th, 2011

A popular user-interface in the iOS world is the UIPageControl which renders a small set of dots to indicate the number of pages, with the current page highlighted in some way. This is often used in conjunction with a UIScrollView to navigate between pages in a multi-page layout.

Windows Phone 7 has a Pivot control which allows you to swipe in order to navigate content across multiple screens. However, the Pivot control is most often used when each ‘page’ has some logic header – in some ways it is analogous to a desktop tab control. I decided to use this control, without specifying headers for each PivotItem, then add my own control to render the ‘pips’.

The control that displays the location pips is defined in XAML, with the relationship between this control and the Pivot created via an ElementName binding:

<local:PivotLocationView Source="{Binding ElementName=pivot}"
                          HorizontalAlignment="Center"
                          VerticalAlignment="Bottom"
                          Margin="0,0,0,10"/>
 
<controls:Pivot Margin="0,-30,0,40" 
                x:Name="pivot">
  <controls:PivotItem>
    ...
  </controls:PivotItem>
  <controls:PivotItem>
    ...
  </controls:PivotItem>
  <controls:PivotItem>
    ...
  </controls:PivotItem>
</controls:Pivot>

Note the negative top margin for the Pivot, this control still allocates some header space, even when no headers are defined.

The PivotLocationView user control is backed by a simple view model, with model-items for each pip. When the view model is associated with a Pivot control, it creates a child view model for each Pivot Item, then handles the SelectionChanged event in order to keep the selection state synchronized:

public class PivotLocationViewModel
{
  private Pivot _pivot;
 
  public PivotLocationViewModel()
  {
  }
 
  public PivotLocationViewModel(Pivot pivot)
  {
    PivotItems = new PivotItemViewModelCollection();
    SetPivot(pivot);
  }
 
  /// <summary>
  /// Gets or sets the collection of child view-models
  /// </summary>
  public PivotItemViewModelCollection PivotItems { get; set; }
 
  private void SetPivot(Pivot pivot)
  {
    _pivot = pivot;
 
    // handle selection changed
    pivot.SelectionChanged += Pivot_SelectionChanged;
 
    // create a view model for each pivot item.
    for(int i=0;i<pivot.Items.Count;i++)
    {
      PivotItems.Add(new PivotItemViewModel());
    }
 
    // set the initial selection
    PivotItems[_pivot.SelectedIndex].IsSelected = true;
  }
 
  /// <summary>
  /// Handle selection changes to update the view model
  /// </summary>
  private void  Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
 	  var selectedModel = PivotItems.SingleOrDefault(p => p.IsSelected);
    if (selectedModel != null)
      selectedModel.IsSelected = false;
 
    PivotItems[_pivot.SelectedIndex].IsSelected = true;
  }
 
}

The view model for each pivot item is a simple model that implements INotifyPropertyChanged. It has an IsSelected property that reflects the selection state of the Pivot, it also exposes a Color property that indicates the color for each ‘pip’. This could have been implemented as a value converter, but there is little point as we already have a view model:

/// <summary>
/// A view model for each 'pip'
/// </summary>
public class PivotItemViewModel : INotifyPropertyChanged
{
  // ... INotifyPropertyChanged implementation
 
  private bool _isSelected;
 
  public bool IsSelected
  {
    get { return _isSelected; }
    set
    {
      if (_isSelected == value)
        return;
 
      _isSelected = value;
      OnPropertyChanged("IsSelected");
 
      Color = IsSelected ? Colors.Black : Colors.White;
    }
  }
 
  private Color _color;
 
  public Color Color
  {
    get { return _color; }
    set
    {
      _color = value;
      OnPropertyChanged("Color");
    }
  }
}

The XAML for this control is very simple, using an ItemsControl to render an ellipse for each ‘pip’:

<UserControl ...
    d:DataContext="{d:DesignData Source=PivotLocationViewModel.xml}">
 
  <Grid x:Name="LayoutRoot">
    <ItemsControl ItemsSource="{Binding PivotItems}">
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Ellipse Width="12" Height="12" Margin="15,0,15,0"
                   Stroke="Black"
                   StrokeThickness="0.5">
            <Ellipse.Fill>
              <SolidColorBrush Color="{Binding Color}"/>
            </Ellipse.Fill>
          </Ellipse>
        </DataTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
  </Grid>
</UserControl>

Note, the use of design-time data. The following file defines a view model instance:

<PivotLocationViewModel xmlns="clr-namespace:SlideView">
  <PivotLocationViewModel.PivotItems>
    <PivotItemViewModelCollection>
      <PivotItemViewModel IsSelected="False" Color="Red"/>
      <PivotItemViewModel IsSelected="True"  Color="Green"/>
      <PivotItemViewModel IsSelected="False"  Color="Red"/>
      <PivotItemViewModel IsSelected="False"  Color="Red"/>
    </PivotItemViewModelCollection>
  </PivotLocationViewModel.PivotItems>
</PivotLocationViewModel>

This makes creating the above user control much easier, because it can be visualised in the designer:

And there you have it, a simple user-control, which when used in conjunction with a Pivot, provides an interface where the user can swipe between pages.

You can download the full sourcecode: SlideView.zip

Regards, Colin E.

Tombstoning with PhoneGap for Windows Phone 7 (and KnockoutJS)

October 24th, 2011

A few weeks back I wrote a blog post about how the recent announcement of PhoneGap support for Windows Phone 7 (WP7) which makes it possible to develop HTML5-based applications. In my previous blog post I showed the development of a simple HTML5 / JavaScript application which PhoneGap wraps up within a Silverlight application ‘shell’ allowing it to be deployed to your phone and potentially submitted to the Marketplace.

However, in order to pass the various Marketplace requirements and gain certification, your application must correctly handle the application lifecycle. With the recent Mango release, the lifecycle has become a little more complicated (although better! in that it adds multi-tasking / fast-app switching). I have also covered the lifecycle in a previous blog post and demonstrated how you can handle the various lifecycle events within an MVVM application.

The most tricky part of the application lifecycle that as a developer you need to handle is the tombstoned state, where your application is terminated (i.e. stopped and removed from memory). It is your responsibility to save enough state in order that when your tombstoned application is restarted, it looks to the user as if your application never stopped running, i.e. you restore your application UI to its original state.

The Mango application lifecycle is illustrated below:

The PhoneGap events API includes pause and resume events, which can be used to detect when the application transitions to and from the dormant state, however, for WP7 these events do not give us enough information. When resuming, we need to know whether it has resumed from a dormant or a tombstoned state. Considering that the tombstoned state is peculiar to WP7 (Android, and iPhone simply have a suspend / resume model), I don’t think it makes sense for the PhoneGap APIs to change in order to accommodate this. In this blog post I will show how the WP7 PhoneGap application host can be modified in order to support tombstoning.

But before we get there, I want to digress a while and look at using the MVVM pattern with JavaScript …

Using the MVVM pattern in JavaScript

Handling tombstoning is much easier if you have a good separation between your view and your logic, with the MVVM pattern being a sensible choice for achieving this. When your application is tombstoned (and your application terminated), then re-activated, it is your responsibility to recreate the original state. Your view-model, is a model-of-a-view, so technically should provide all the information required to fulfil this requirement. See my previous blog post for details.

There are numerous JavaScript UI frameworks available (MVC, MVP, MVVM), however, because I feel tombstoning lends itself particularly well to the MVVM pattern, I decided to give KnockoutJS a try. When reading about this framework you will find references to WPF and Silverlight, it is clear that it has been heavily inspired by the Microsoft XAML frameworks.

The application I have built to demonstrate tombstoning is a very simple, single page twitter search application.

The Knockout view model is a JavaScript object where the properties are defined as ‘observables’. These are JavaScript functions which provide change notification, much like CLR properties with INotifyPropergtyChanged within Silverlight / WPF.

The View-Model

The view model for my twitter search application is shown below:

/// <summary>
/// A view model for searching twitter for a given term
/// </summary>
function TwitterSearchViewModel() {
 
  var that = this;
 
  // --- properties
 
  this.isSearching = ko.observable(false);
 
  this.searchTerm = ko.observable("#wp7dev");
 
  this.tweets = ko.observableArray();
 
  // --- functions
 
  // search twitter for the given string
  this.search = function () {
    if (that.searchTerm() != "") {
 
      that.isSearching(true);
      var url = "http://search.twitter.com/search.json?q=" +
            encodeURIComponent(that.searchTerm());
 
      $.ajax({
        dataType: "jsonp",
        url: url,
        success: function (response) {
          // clear the results
          that.tweets.removeAll();
          // add the new items
          $.each(response.results, function () {
            var tweet = new TweetViewModel(this);
            that.tweets.push(tweet);
          });
 
          that.isSearching(false);
        }
      });
    }
  }
}

It comprises a few simple properties and a search function. Note, the items property is an observableArray, this is analogous to the WPF / Silverlight ObservableCollection, which raises events when its contents are modified, allowing the UI to update automatically. The search function queries the twitter APIs to find matching tweets, updating the observable items array with the results.

The TwitterSearchViewModel items collection is populated with TweetViewModel instances:

/// <summary>
/// A view model that represents a single tweet
/// </summary>
function TweetViewModel(tweet) {
 
    // --- properties
 
    this.author = tweet.from_user,
    this.text = tweet.text,
    this.time = parseDate(tweet.created_at);
    this.thumbnail = tweet.profile_image_url;
 
    // --- functions
 
    // parses the tweet date to give a more readable format
    function parseDate(date) {
      var diff = (new Date() - new Date(date)) / 1000;
 
      if (diff < 60) {
        return diff.toFixed(0) + " seconds ago";
      }
 
      diff = diff / 60;
      if (diff < 60) {
        return diff.toFixed(0) + " minutes ago";
      }
 
      diff = diff / 60;
      if (diff < 10) {
        return diff.toFixed(0) + " hours ago";
      }
 
      diff = diff / 24;
      return diff.toFixed(0) + " days ago";
    }
};

Note, here the properties are not observables, again much like WPF / Silverlight you can bind to a property that does not notify of changes if this is not required.

Also, the Knockout documentation typically defines view-models as literal objects. I prefer to use constructor functions, allowing the creation of multiple instances of the same view model.

The View

With Knockout the view is defined in HTML, you can create it directly, or via a template. I have created the following templates:

<script type=text/x-jquery-tmpl" charset="utf-8" id="twitterSearchView">
  <form data-bind="submit: search">
      <input data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
      <button type="submit" data-bind="enable: searchTerm().length > 0 &amp;&amp; isSearching() == false">Go</button>  
  </form>    
  <ul data-bind="template: {name: 'tweetView', foreach: tweets}"> </ul>
</script>
<script type="text/x-jquery-tmpl" charset="utf-8" id="tweetView">
  <li class="tweet">
    <div class="thumbnailColumn">
      <img data-bind="attr: { src: thumbnail }" class="thumbnail"/>
    </div>
    <div class="detailsColumn">
      <div class="author" data-bind="text: author"/> 
      <div class="text" data-bind="text: text"/> 
      <div class="time" data-bind="text: time"/> 
    </div>
  </li>
</script>

The data-bind attribute is used by Knockout to set up the various bindings, connecting your view model properties and observables to the UI.It also defines functions to invoke when DOM events are raised, in much the same way as commands do in WPF / Silverlight.

The application code

Instantiating the view-model and the view is as simple as the following:

$(document).ready(function () {
  document.addEventListener("deviceready", onDeviceReady, false);
});
 
// phonegap is initialised
function onDeviceReady() {
 
  // create the view model
  twitterSearchViewModel = new TwitterSearchViewModel();
 
  // create an instance of the view
  $("#twitterSearchView").tmpl("").appendTo("#app");
 
  // wire-up
  ko.applyBindings(twitterSearchViewModel)
}

Originally I wanted to have the HTML for each view within a separate file, loading them via jQuery as described in this blog post. However, I just couldn’t get this to work within the embedded WP7 browser.

The tweetView tempate is used via the template / foreach Knockout binding, mimicking the Silverlight / WPF ItemsControl.ItemTemplate concept.

The application, after a bit of styling, looks like this:

Tombstoning

Now that the application has a decent structure, we can tackle the application-lifecycle. We need a way to store the view model state when the application transitions into a dormant state. Fortunately Knockout makes this very easy by supplying a toJSON function, which can create a JSON representation of your view-model graph (minus the observables). I have added a getState function to the TwitterSearchViewModel as follows:

// gets the view model state as a JSON string
this.getState = function () {
  return ko.toJSON(this);
}

Now we need a way to invoke this function when the application pauses. PhoneGap provides a pause lifecycle event, however, we need to store the output of this function in the WP7 PhoneApplicationService.Current.State dictionary. Because this is a very much WP7 specific feature, I decided to do this outside of the PhoneGap lifecycle events.

My handler for the Deactivated event simply invokes the above method, storing the state in the application state dictionary:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
  var viewModelState = PhoneGapView.Browser.InvokeScript("getState") as string;
  PhoneApplicationService.Current.State[ModelKey] = viewModelState;
}

Note, to do this I have had to modify the current PhoneGap WP7 library to provide access to the underlying WebBrowser control, I have raised an issue requesting this change to the PhoenGap library.

The application now stores it state when it becomes dormant, the next step is to use this state when an application is activated from a tombstoned state. Within the Activated handler we can read this state as follows:

/// <summary>
/// Gets the state that has been retrieved from isolated storage
/// in order to re-activated after tombstoning.
/// </summary>
public string TombstoneState { get; private set; }
 
private void Application_Activated(object sender, ActivatedEventArgs e)
{
  if (!e.IsApplicationInstancePreserved)
  {
    if (PhoneApplicationService.Current.State.ContainsKey(ModelKey))
    {
      var viewModelState = PhoneApplicationService.Current.State[ModelKey] as string;
      TombstoneState = viewModelState;
    }
  }
}

Note, we check IsApplicationInstancePreserved, if this is true, we do not need to use the state that was saved during deactivation, this allows for fast-application switching.

Unfortunately as this point our UI has not been created and our JavaScript application code is not running, which is why the tombstoned state is simply stored in a public property of our application. To pick this state up, we add a new step to our JavaScript view model creation code:

// phonegap is initialised
function onDeviceReady() {
 
  // create the view model
  twitterSearchViewModel = new TwitterSearchViewModel();
 
  // ---> check for tombstoned state
  window.external.Notify("getState");
 
  // instantiate the view an bind
  $("#twitterSearchView").tmpl("").appendTo("#app");
  ko.applyBindings(twitterSearchViewModel)
}

When the PhoneGap view is created, we add a handler to the ScriptNotify event, allowing us to handle this getState notification:

// Constructor
public MainPage()
{
  InitializeComponent();
 
  phoneGapView.Browser.ScriptNotify += Browser_ScriptNotify;
}
 
 
private void Browser_ScriptNotify(object sender, NotifyEventArgs e)
{
  string commandStr = e.Value;
 
  if (commandStr == "getState" && App.Current.TombstoneState != null)
  {
    phoneGapView.Browser.InvokeScript("setState", new string[] { App.Current.TombstoneState });
  }
}

This checks for the presence of tombstone state, and if found, invokes setState back on our JavaScript view model:

// sets the view model state based on the given JSON string.
this.setState = function (stateString) {
  var state = $.parseJSON(stateString),
      that = this;
 
  this.isSearching(state.isSearching);
  this.searchTerm(state.searchTerm);
 
  this.tweets.removeAll();
  $.each(state.tweets, function () {
    that.tweets.push(this);
  });
}

Note, re-creating our view-model form JSON data is a little more involved than the opposite. I have also cheated a little here, rather than re-creating each TweetViewModel I am using the JSON representation, because this view model has no public functions (i.e. commands).

Conclusions

With the above code the PhoneGap application now successfully handles all of the WP7 lifecycle states and transitions. There are a couple of things to note if you try to run this code yourself:

  1. You can force tombstoning via the Debug properties, “Tombstone upon deactiviation while debugging”.
  2. I have fund that the WebBrowser on the emulator does not tombstone correctly, when your application resumes the WebBrowser control fails to execute any JavaScript! Fortunately on a real device it works just fine.

Now that I can tombstone a PhoneGap application, I feel that it is one step closer to be a viable solution for application development. The final thing that I still haven’t quite worked out yet is navigation and back-button support. Fortunately Knockout has a lot to offer in this area as well, but more on that later …

You can download the full sourcecode (including PhoneGap library mods) here: PhoneGapExample.zip

Regards, Colin E.

Adding Error Bars to Visiblox Silverlight Charts

October 21st, 2011

Having spent a number of years studying Physics at university, I have had the importance of error bars well and truly drummed into me! Within physics, or any experimental science, there are always going to be errors in the measurements you make. The more repeat measurements you make, the more confident you can be in the mean value, however you cannot remove the errors altogether. Error bars provide a way to represent the spread of experimental observations graphically, without them, it is hard to have any confidence in the conclusions drawn from the observations!

In this blog post I will show how to implement a custom Visiblox chart series to render error bars:

(The data in the above chart is from a page which details how to calculate the standard error from experimental results).

Creating a Custom Series

As described in my previous blog post on creating a spline series, to create a new series type, you sub-class one of the Visiblox base-classes, in this case MultiValueSeriesBase is a suitable starting point:

public class ErrorBarSeries : MultiValueSeriesBase
{ 
  protected override FrameworkElement CreatePoint(IDataPoint dataPoint)
  {
    throw new NotImplementedException();
  }
 
  protected override void RenderDataLabels()
  {
    throw new NotImplementedException();
  }
}

I don’t want data labels, so the only method I need to implement is CreatePoint, which takes the (multi-valued) point to be rendered as its only argument. The lifecycle of point creating and destruction is taken care of by the base-class.

The IDataPoint has a string indexer which is used to retrieve multiple Y values for multi-valued series. It is a good idea to define these in a single place, here we define the three y-values required for an error-bar series:

public static readonly string ErrorUp = "ErrorUp";
 
public static readonly string ErrorDown = "ErrorDown";
 
public static readonly string Value = "Value";

The CreatePoint implementation for this series creates a Path as follows:

protected override FrameworkElement CreatePoint(IDataPoint dataPoint)
{
  var lineGeometry = BuildGeometry(dataPoint);
 
  Path line = new Path();
  line.Stroke = new SolidColorBrush(Colors.Black);
  line.Fill = new SolidColorBrush(Colors.Gray);
  line.StrokeThickness = 1.0;
  line.StrokeLineJoin = PenLineJoin.Bevel;
  line.Data = lineGeometry;
  line.SetValue(ZoomCanvas.IsScaledPathProperty, true);
 
  return line;
}

The BuildGeometry method does most of the work, extracting the values from the IDataPoint, transforming them (via the axis) to the required coordinate system, then creating a suitable geometry:

/// <summary>
/// Creates the geometry for the given datapoint
/// </summary>
private PathGeometry BuildGeometry(IDataPoint dataPoint)
{
  var halfWidth = SuggestedPointWidth * WidthFactor;
 
  // obtain the data values
  var topDataValue = dataPoint[ErrorUp] as IComparable;
  var middleDataValue = dataPoint[Value] as IComparable;
  var bottomDataValue = dataPoint[ErrorDown] as IComparable;
 
  // convert to a the required render coordinates
  double topRenderPos = YAxis.GetDataValueAsRenderPositionWithoutZoom(topDataValue);
  double middleRenderPos = YAxis.GetDataValueAsRenderPositionWithoutZoom(middleDataValue);
  double bottomRenderPos = YAxis.GetDataValueAsRenderPositionWithoutZoom(bottomDataValue);
 
  double xMiddleRenderPos = XAxis.GetDataValueAsRenderPositionWithoutZoom(dataPoint.X);
  double xRightRenderPos = xMiddleRenderPos - halfWidth;
  double xLeftRenderPos = xMiddleRenderPos + halfWidth;
 
  // build a suitable gemoetry
  PathGeometry lineGeometry = new PathGeometry();
 
  PathFigure upperVerticalLine = CreateLineFigure(
    new Point(xMiddleRenderPos, middleRenderPos - halfWidth),
    new Point(xMiddleRenderPos, topRenderPos));
  lineGeometry.Figures.Add(upperVerticalLine);
 
  PathFigure lowerVerticalLine = CreateLineFigure(
    new Point(xMiddleRenderPos, bottomRenderPos),
    new Point(xMiddleRenderPos, middleRenderPos + halfWidth));
  lineGeometry.Figures.Add(lowerVerticalLine);
 
  PathFigure upperBar = CreateLineFigure(
    new Point(xLeftRenderPos, topRenderPos),
    new Point(xRightRenderPos, topRenderPos));
  lineGeometry.Figures.Add(upperBar);
 
  PathFigure lowerBar = CreateLineFigure(
    new Point(xLeftRenderPos, bottomRenderPos),
    new Point(xRightRenderPos, bottomRenderPos));
  lineGeometry.Figures.Add(lowerBar);
 
  PathFigure center = CreateLineFigure(
    new Point(xMiddleRenderPos - halfWidth, middleRenderPos),
    new Point(xMiddleRenderPos, middleRenderPos + halfWidth),
    new Point(xMiddleRenderPos + halfWidth, middleRenderPos),
    new Point(xMiddleRenderPos, middleRenderPos - halfWidth)
  );
  lineGeometry.Figures.Add(center);
 
  return lineGeometry;
}
 
/// <summary>
/// Create a line figure that connects the given points
/// </summary>
private PathFigure CreateLineFigure(params Point[] points)
{
  // add all the points (except the first)
  var pointCollection = new PointCollection();
  foreach (var point in points.Skip(1))
  {
    pointCollection.Add(point);
  }
 
  // create a figure, using the first point as the StartPoint.
  return new PathFigure()
  {
    IsClosed = true,
    StartPoint = points.First(),
    Segments = new PathSegmentCollection()
    {
      new PolyLineSegment
      {
        Points = pointCollection
      }
    }
  };
}

We can now create an instance of this series in XAML:

<vis:Chart x:Name="chart">
  <vis:Chart.Series>
    <local:ErrorBarSeries/>
  </vis:Chart.Series>
</vis:Chart>

Supplying data to the chart via MultiValuedDataPoint as follows:

public MainPage()
{
  InitializeComponent();
 
  var data = new DataSeries<double, double>();
  data.Add(CreatePoint(-195, 1.4, 0.2));
  data.Add(CreatePoint(0, 62.2, 9.3));
  data.Add(CreatePoint(20, 70.4, 6.5));
  data.Add(CreatePoint(100, 77.4, 1.9));
 
  chart.Series[0].DataSeries = data;
}
 
private MultiValuedDataPoint<double, double> CreatePoint(double x, double y, double error)
{
  var point = new MultiValuedDataPoint<double, double>(x,
    new Dictionary<object, double>()
    {
      { ErrorBarSeries.ErrorUp, y + error },
      { ErrorBarSeries.ErrorDown, y - error },
      { ErrorBarSeries.Value, y }
    });
  return point;
}

This results in the following chart:

Binding to a Multi-valued Series

In the previous example we created instances of MultiValuedDataPoint, a Visiblox type for representing multi-valued points. As an alternative, we can create model objects to represent each point, rendering them in the chart via databinding.

We first modify the code to create a collection of Measurement instances (a simple model object that implements INotifyPropertyChanged):

public MainPage()
{
  InitializeComponent();
 
  var data = new ObservableCollection<Measurement>();
  data.Add(CreateMeasurement(-195, 1.4, 0.2));
  data.Add(CreateMeasurement(0, 62.2, 9.3));
  data.Add(CreateMeasurement(20, 70.4, 6.5));
  data.Add(CreateMeasurement(100, 77.4, 1.9));
  this.DataContext = data;    
}
 
private Measurement CreateMeasurement(double x, double y, double error)
{
  return new Measurement()
    {
      XValue = x,
      YValue = y,
      YValueErrorUp = y + error,
      YValueErrorDown = y - error
    };
}

The markup for the chart is modified to use a BindableDataSeries, with bindings specified for the various component of the error bar series. Also, the ItemsSource of the BindableDataSeries is bound to the inherited DataContext:

<local:ErrorBarSeries>
  <local:ErrorBarSeries.DataSeries>
    <vis:BindableDataSeries ItemsSource="{Binding}"
                            XValueBinding="{Binding XValue}">
      <vis:BindableDataSeries.YValueBindings>
        <vis:YValueBinding YValueKey="Value" Binding="{Binding YValue}"/>
        <vis:YValueBinding YValueKey="ErrorUp" Binding="{Binding YValueErrorUp}"/>
        <vis:YValueBinding YValueKey="ErrorDown"  Binding="{Binding YValueErrorDown}"/>
      </vis:BindableDataSeries.YValueBindings>              
    </vis:BindableDataSeries>
  </local:ErrorBarSeries.DataSeries>
</local:ErrorBarSeries>

We can also display our data in a DataGrid, allowing us to manipulate the values (not that I condone manipulation of scientific data!), with the changes being reflected in the chart:

<sdk:DataGrid Grid.Row="1"
              x:Name="grid"
              ItemsSource="{Binding}"/>

This gives us the following application:

You can edit the values, with the changes reflected immediately in the chart above.

You can download the sourcecode for the above example here: VisibloxErrorBarSeries.zip

Regards, Colin E.