<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Dotnet by Example</title><link>http://dotnetbyexample.blogspot.com/</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/blogspot/dotnetbyexample" /><description>&lt;b&gt;Motto: "Talk is cheap, show me the code!" &lt;/b&gt;&lt;br&gt;
&lt;br&gt;
This blog attempts to be a collection of how-to examples in the Microsoft software stack - things that may take forever to find out, especially for the beginner. I see it as my way to return something to the Microsoft community in exchange for what I learned from it.</description><language>en</language><managingEditor>noreply@blogger.com (Joost van Schaik)</managingEditor><lastBuildDate>Thu, 23 May 2013 08:37:38 PDT</lastBuildDate><generator>Blogger</generator><atom:id xmlns:atom="http://www.w3.org/2005/Atom">tag:blogger.com,1999:blog-5295746446529817470</atom:id><openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">140</openSearch:totalResults><openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">1</openSearch:startIndex><openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/blogspot/dotnetbyexample" /><feedburner:info uri="blogspot/dotnetbyexample" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Windows Phone 8 navigation part 4–updating the tests, fixing the final issues</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/gXnPyu0gLic/windows-phone-8-navigation-part_13.html</link><category>wpnl</category><category>Unit Test</category><category>Mapping</category><category>Windows 8</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Mon, 13 May 2013 09:01:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-1978657347509252989</guid><description>&lt;p&gt;&lt;font size="4"&gt;Last time: so close, yet so far:&lt;/font&gt;&lt;/p&gt; &lt;p&gt;This series appears to have become a trilogy in four parts – at the end of the last episode everything worked, save for tombstoning, although we explicitly wrote test code for that. The the app tombstoned, partially - two things were apparently missing:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The route  &lt;li&gt;The locations to and from the route should run.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;font size="4"&gt;Making the tests fail&lt;/font&gt;&lt;/p&gt; &lt;p&gt;An important step when you have a bug in an app that passes all tests, is to make a test that &lt;em&gt;fails because of the bug&lt;/em&gt;. In that case, you have reproduced the problem, and can start on fixing the bug. Logically, the bug is fixed when the test no longer fails – and should anyone start to mess around with your code an re-introduce the bug, the test will fail again, indicating something has gone wrong before you even ship. Your tests have become a smoke detector ;-)&lt;/p&gt; &lt;p&gt;Anyway, we observe there is no selected location, nor routes or waypoints after tombstoning. When we look at the comprehensive test for RoutingViewModel written in the 2nd post of this series, we see the following Assert statement with regard to the retrieved viewmodel:&lt;/p&gt;&lt;pre&gt;Assert.IsTrue(vm.RouteCoordinates.Any());
Assert.IsTrue(vm.Maneuvers.Any());
Assert.IsTrue(retrievedVm.RouteCoordinates.Count == vm.RouteCoordinates.Count);
Assert.IsTrue(retrievedVm.FromViewModel.SearchText == "Springerstraat Amersfoort Netherlands");
Assert.IsTrue(retrievedVm.Maneuvers.Count == vm.Maneuvers.Count);&lt;/pre&gt;
&lt;p&gt;Shockingly, we learn two things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We indeed don’t test the presence of either SelectedLocation or either FromViewModel and ToViewModel. 
&lt;li&gt;We&lt;em&gt; do&lt;/em&gt; test the presence of both RouteCoordinates and Maneuvers. So our viewmodel works in that respect – so the error must have to do something with data binding.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;First, we add test code for SelectedLocation&lt;/p&gt;&lt;pre&gt;Assert.IsNotNull(retrievedVm.FromViewModel.SelectedLocation);
Assert.IsNotNull(retrievedVm.ToViewModel.SelectedLocation);&lt;/pre&gt;
&lt;p&gt;And sure enough:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_thumb.png" width="376" height="165"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Annoyingly, this does only say which test failed, but not what exactly failed in this test. You can of course follow the purist route and write a separate test method for every assert, or just be lazy like me and use the overload every Assert method has:&lt;/p&gt;&lt;pre&gt;Assert.IsNotNull(retrievedVm.FromViewModel.SelectedLocation, 
  "No FromViewModel.SelectedLocation tombstoned");
Assert.IsNotNull(retrievedVm.ToViewModel.SelectedLocation, 
 "No ToViewModel.SelectedLocation tombstoned");&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_thumb_3.png" width="373" height="164"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And there we are. A clear error message. There is no SelectedLocation after tombstoning&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Fixing the SelectedLocation bug aka serialization under the hood&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Let me introduce you to the wonderful world of serialization. Much as we move into the world of asynchronous and parallel programming, serialization is essentially a &lt;em&gt;sequential&lt;/em&gt; process. First property A is written, then property B. When something is deserialized, things are also read from storage in a particular order, i.e. the order they are written.&lt;/p&gt;
&lt;p&gt;Let’s get back to the RoutingViewModel. I’ve abbreviated the property implementation a bit, apart from the Model. There we see the following code:&lt;/p&gt;&lt;pre&gt;public ManeuverViewModel SelectedManeuver

public GeocodeViewModel ToViewModel

public GeocodeViewModel FromViewModel

public ObservableCollection&amp;lt;RouteGeometryViewModel&amp;gt; RouteCoordinates { get; set; }

public ObservableCollection&amp;lt;ManeuverViewModel&amp;gt; Maneuvers { get; set; }

private NavigationModel model;
public NavigationModel Model
{
  get { return model; }
  set
  {
    model = value;
    if (model != null)
    {
      ToViewModel = new GeocodeViewModel(model.To) { Name = "To" };
      FromViewModel = new GeocodeViewModel(model.From) { Name = "From" };
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Now let’s assume, for a moment, serialization simply reflects all public properties with both getter and setter, and writes them one by one to storage – and reads them in the same order. In no particular order – if this were a database that most probably means the order the in which records were put in. Could it be reflection works the same way? But then, deserializing would mean that first the SelectedManeuver would be deserialized, then ToViewModel and FromViewModeland, then the RouteCoordinates, then the Maneuvers, and finally the model. But smart Mr Me has implemented this clever method of initializing FromViewModel and ToViewModel upon calling of the setter. So whatever was deserialized into FromViewModel and ToViewModel&amp;nbsp; gets overwritten after Model is deserialized!&lt;/p&gt;
&lt;p&gt;So let’s make the Model property the very first property of the viewmodel, right after the constructors, run the test and see what happens…&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_4.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_thumb_4.png" width="383" height="138"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You can imagine with this kind of arcane stuff going on behind the curtains, (unit) test code can be a &lt;em&gt;really&lt;/em&gt; great tool to track and fix this kind of obscure errors – and make sure they never, ever occur suddenly again, just because someone changed the order in the way things are implemented!&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Fixing the MapShapeDrawBehavior bug&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This is a bit of odd one – apparently the developer that made the MapShapeDrawBehavior – a knucklehead who names himself “LocalJoost” ;-) -&amp;nbsp; has made an error implementing data binding – while he implemented listening to all the collection events correctly, he never apparently anticipated the initial collection should could have some values before data binding ensued. The advantage of open source is that we actually can see this. So, we either have to copy MapShapeDrawBehavior ‘s code and make a manual fix to make sure some event occurs that makes it go draw the stuff – or implement a band-aid that does not interfere with the existing code. &lt;/p&gt;
&lt;p&gt;I pulled out the band, aid, and made the following class:&lt;/p&gt;&lt;pre&gt;using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Wp7nl.Utilities
{
  public class ResettableObservableCollection&amp;lt;T&amp;gt; : ObservableCollection&amp;lt;T&amp;gt;
  {
    public ResettableObservableCollection()
    {
    }

    public ResettableObservableCollection(List&amp;lt;T&amp;gt; list)
      : base(list)
    {
    }

    public ResettableObservableCollection(IEnumerable&amp;lt;T&amp;gt; list)
      : base(list)
    {
    }

    public void ForceReset()
    {
      OnCollectionChanged(
       new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
  }
}&lt;/pre&gt;
&lt;p&gt;I changed both RouteCoordinates and Maneuvers in RoutingViewmodel into ResettableObservableCollection, added the following command to RoutingViewmodel:&lt;/p&gt;&lt;pre&gt;[DoNotSerialize]
public ICommand MapLoadedCommand
{
  get
  {
    return new RelayCommand( ()=&amp;gt;
        {
          RouteCoordinates.ForceReset();
          Maneuvers.ForceReset();
        });
  }
}&lt;/pre&gt;
&lt;p&gt;and finally, the following piece of XAML to the map:&lt;/p&gt;&lt;pre&gt;&amp;lt;i:Interaction.Triggers&amp;gt;
  &amp;lt;i:EventTrigger  EventName="Loaded"&amp;gt;
    &amp;lt;Command:EventToCommand Command="{Binding MapLoadedCommand}"/&amp;gt;
  &amp;lt;/i:EventTrigger&amp;gt;
&amp;lt;/i:Interaction.Triggers&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_5.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3updatin_9032/image_thumb_5.png" width="150" height="244"&gt;&lt;/a&gt;This will fire the command directly after the map has loaded. Data binding has already occurred then. And sure enough, even after restarting the app, everything is reloaded from storage. The behavior is tricked into believing it should draw it’s stuff. Now I only need to publish my app, and inform this LocalJoost character that his library contains bugs and if he can fix them ASAP, thank you very much.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Concluding remarks&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This series did not only show you the basics of &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8 navigation, but also how to develop geo-applications on Windows Phone 8 using unit/integration test to explore and test functionality, as well as using test as a way to hunt down and fix bugs. It also showed that if your test are incomplete, you might get bitten. And finally it showed you that, in the end, you still need to test manually to catch bugs that are caused by dunderheads making errors in their published code ;-)&lt;/p&gt;
&lt;p&gt;The final solution &lt;a href="http://www.schaikweb.net/dotnetbyexample/NavigationDemo4.zip" target="_blank"&gt;can be found here&lt;/a&gt;,&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/gXnPyu0gLic" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-05-14T09:24:22.378+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/05/windows-phone-8-navigation-part_13.html</feedburner:origLink></item><item><title>Windows Phone 8 navigation part 3–assembling the MVVMLight app</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/BPTbRDTX0ys/windows-phone-8-navigation-part.html</link><category>MVVM</category><category>wpnl</category><category>Mapping</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Fri, 10 May 2013 04:34:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-2494881555407877252</guid><description>&lt;p&gt;&lt;font size="4"&gt;Last time on, on Dotnetbyexample…&lt;/font&gt;  &lt;p&gt;In &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/windows-phone-8-navigation-part.html"&gt;the first post&lt;/a&gt; I described how to write the business logic to find a location by searching for an address by text, and in the &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/windows-phone-8-navigation-part_29.html"&gt;second post&lt;/a&gt; I described how to do some actual routing – still, only business logic and viewmodels. And we kept in mind all the results should be tombstonable, and how to make sure this all worked by using simple unit/integration tests.  &lt;p&gt;Today, it’s time for the actual app. Bear in mind this post will actually refer to a lot of earlier other posts – from even outside this series. In this post I am also going to show you that working with you designer sometimes means you need to make little tweaks to your viewmodels to make it work the way you want, or make life easier on the designer. Remember, you are the technician, the person who needs to make it finally work.  &lt;p&gt;&lt;font size="4"&gt;GUI and interaction design&lt;/font&gt;  &lt;p&gt;So, after conferring with the designer we have agreed the app should work like this: &lt;/p&gt; &lt;div id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:d0192090-9236-4a65-be30-489e14286cfe" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px"&gt;&lt;div&gt;&lt;object width="448" height="277"&gt;&lt;param name="movie" value="http://www.youtube.com/v/Yjcjg6_DpFc?hl=en&amp;amp;hd=1"&gt;&lt;/param&gt;&lt;embed src="http://www.youtube.com/v/Yjcjg6_DpFc?hl=en&amp;amp;hd=1" type="application/x-shockwave-flash" width="448" height="277"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt;&lt;div style="width:448px;clear:both;font-size:.8em"&gt;Windows Phone 8 navigate by MVVMLight&lt;/div&gt;&lt;/div&gt; &lt;p&gt;The route is displayed as a line, every maneuver as a star, and when you tap that star it should show a panel showing the maneuver description. For interested parties – this is a car route I could take to my home to my work at &lt;a href="http://www.vicrea.nl" target="_blank"&gt;Vicrea&lt;/a&gt; ;-) &lt;p&gt;Well – the moving panels are easy to solve &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/viewmodel-driven-multi-state-animations.html" target="_blank"&gt;with some View States and DataTriggers – I’ve been down that road before&lt;/a&gt;. Showing a &lt;a href="http://dotnetbyexample.blogspot.nl/2012/10/data-binding-shapes-to-new-windows.html" target="_blank"&gt;line and points on a map from the view model – been there done that&lt;/a&gt;, wrote behaviors for that and those are snugly in the &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl library&lt;/a&gt; which is, not quite coincidental, part of this solution already.  &lt;p&gt;So, we need to do the following:&amp;nbsp; &lt;ul&gt; &lt;li&gt;Define the app user interface, that is: &lt;/li&gt; &lt;ul&gt; &lt;li&gt;Two panels enabling the user to input text and select a route, e.g. a user interface for both the GeocodeViewModels in RoutingViewmodel. We’ll make a user control from that  &lt;li&gt;A panel with From/To info making showing the address from an to, and making it possible to let the From and To panel into view. This will be a user control as well  &lt;li&gt;A button firing off the RoutingViewmodel’s DoRoutingCommand  &lt;li&gt;A panel that’s shown as the user taps a maneuver. This, too, will be a user control.  &lt;li&gt;A Map &lt;/li&gt;&lt;/ul&gt; &lt;li&gt;A MainViewModel that’s acting as a kind of locator and a serialization root point, like I always do.  &lt;li&gt;Something to handle the view state. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;font size="4"&gt;Adding ViewState management&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/viewmodel-driven-multi-state-animations.html" target="_blank"&gt;Just like I did before in this post&lt;/a&gt;, I added a DisplayState enumeration in de NavigationDemo.Logic project, like this:&lt;/p&gt;&lt;pre&gt;namespace NavigationDemo.Logic.States
{
  public enum DisplayState
  {
    Normal = 0,
    SearchFrom = 1,
    SearchTo = 2,
    ShowManeuver = 3
  }
}&lt;/pre&gt;one state for every panel, and a “Normal” state for every other panel. And then I decided to take the easy way out and add the state control to the RoutingViewmodel, basically to make data binding easier. Of course I could have made a separate view model for this, but what the heck, it’s only a few lines of code anyway: &lt;pre&gt;[DoNotSerialize]
public ICommand DisplayPopupCommand
{
  get
  {
    return new RelayCommand&amp;lt;string&amp;gt;(
        p =&amp;gt;
        {
          DisplayState = (DisplayState)Enum.Parse(typeof(DisplayState), p);
        });
  }
}

private DisplayState displayState;
public DisplayState DisplayState
{
  get { return displayState; }
  set
  {
    if (displayState != value)
    {
      displayState = value;
      RaisePropertyChanged(() =&amp;gt; DisplayState);
    }
  }
}    
&lt;/pre&gt;
&lt;p&gt;It makes life easier on the designer, he does not have mess around with data context so much. The property is the actual storage for the DisplayState, and the command sets the display state to it's parameter. All described before. The final piece is a little adaption in the SelectedManeuver property, there we need to add in the setter: &lt;/p&gt;&lt;pre&gt;DisplayState = SelectedManeuver != null ? DisplayState.ShowManeuver : DisplayState.Normal;&lt;/pre&gt;directly behind the RaisePropertyChanged. This will have the panel showed automatically when a non-null value is detected after the setter has been accessed.&amp;nbsp; &lt;p&gt;&lt;font size="4"&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image_thumb.png" width="244" height="114"&gt;&lt;/a&gt;GeocodeViewModel ui&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;I tend to put user controls into a separate folder UserControls (never been one for original naming conventions anyway). The design of the GeocodeControl looks like this:&lt;/p&gt;
&lt;p&gt;And I’ve put it in XAML like this:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;UserControl.Resources&amp;gt;
  &amp;lt;DataTemplate x:Key="AddressTemplate"&amp;gt;
    &amp;lt;Grid&amp;gt;
      &amp;lt;TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Address}"&lt;br&gt;       VerticalAlignment="Top"/&amp;gt;
    &amp;lt;/Grid&amp;gt;
  &amp;lt;/DataTemplate&amp;gt;
&amp;lt;/UserControl.Resources&amp;gt;

&amp;lt;Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}"&amp;gt;
  &amp;lt;Grid Margin="12,0" &amp;gt;
    &amp;lt;!-- Definitions omitted --&amp;gt;

    &amp;lt;Button Grid.Column="2"  Style="{StaticResource &lt;font color="#ff0000"&gt;&lt;u&gt;RoundButton&lt;/u&gt;&lt;/font&gt;}" 
        Command="{Binding SearchLocationCommand, Mode=OneWay}"
        VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="72" Width="72"&lt;br&gt;        Margin="0,0,-5,0" &amp;gt;
      &amp;lt;Rectangle Fill="{StaticResource PhoneForegroundBrush}" Width="44" Height="44" &amp;gt;
        &amp;lt;Rectangle.OpacityMask&amp;gt;
          &amp;lt;ImageBrush ImageSource="&lt;font color="#ff0000"&gt;&lt;u&gt;/images/feature.search.png&lt;/u&gt;&lt;/font&gt;" Stretch="Fill"/&amp;gt;
        &amp;lt;/Rectangle.OpacityMask&amp;gt;
      &amp;lt;/Rectangle&amp;gt;
    &amp;lt;/Button&amp;gt;
    &amp;lt;TextBlock TextWrapping="Wrap" Text="Search" VerticalAlignment="Center" &lt;br&gt;               Height="27" Margin="0,23,0,22" /&amp;gt;
    &amp;lt;TextBlock TextWrapping="Wrap" Text="Found" Grid.Row="1" &lt;br&gt;       VerticalAlignment="Center" Height="27"/&amp;gt;
    &amp;lt;TextBox Grid.Column="1" TextWrapping="NoWrap" &lt;br&gt;        Text="{Binding SearchText, Mode=TwoWay}"&amp;gt;
      &amp;lt;i:Interaction.Behaviors&amp;gt;
        &amp;lt;Behaviors:TextBoxChangeModelUpdateBehavior/&amp;gt;
      &amp;lt;/i:Interaction.Behaviors&amp;gt;
    &amp;lt;/TextBox&amp;gt;
    &amp;lt;ListBox Grid.Column="1" Grid.Row="1" Margin="12" ItemsSource="{Binding MapLocations}" 
      SelectedItem="{Binding SelectedLocation,Mode=TwoWay}" 
      ItemTemplate="{StaticResource AddressTemplate}"/&amp;gt;
    &amp;lt;Button Content="Done" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" 
       Margin="0,23,0,22" Height="71" Command="{Binding &lt;font color="#ff0000"&gt;&lt;u&gt;DoneCommand&lt;/u&gt;&lt;/font&gt;}"/&amp;gt;     
  &amp;lt;/Grid&amp;gt;
&amp;lt;/Grid&amp;gt;
&lt;/pre&gt;
&lt;p&gt;There will be two instances of this user control – one to determine the “From” address, and one for the “”To” address.&lt;/p&gt;
&lt;p&gt;There are some things to note here, &lt;font color="#ff0000"&gt;&lt;u&gt;all underlined in red&lt;/u&gt;&lt;/font&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;I am using a RoundButton style to get a round button, to show an standard image feature_search.png. I pulled this ages ago from &lt;a href="http://blogs.msdn.com/b/priozersk/archive/2010/08/13/creating-round-button-for-wp7-part-1.aspx" target="_blank"&gt;this post&lt;/a&gt; by Alex Yakhnin if I am not mistaken. 
&lt;li&gt;There is no data context set, therefore, the data context – a GeocodeViewModel – should be set in the parent element. No problem. But the DoneCommand, which should dismiss the panel, is therefore also in the GeocodeViewModel, and there is no code for that. Worse, the actual state control logic is in a totally different view model – in this case the RoutingViewmodel. Two view models, having no real knowledge of each other, yet needing to get some data across – that spells m-e-s-s-e-n-g-e-r.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;font size="4"&gt;Adding some Messenger magic&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;We define a simple message “DoneMessage” that, when received by the RoutingViewmodel (that also keeps the view state) will dismiss all popups. It’s pretty easy to implement:&lt;/p&gt;&lt;pre&gt;namespace NavigationDemo.Logic.Messages
{
  public class DoneMessage{ }
}&lt;/pre&gt;
&lt;p&gt;And in the RoutingViewmodel, in the constructor, just one line:&lt;/p&gt;&lt;pre&gt;Messenger.Default.Register&amp;lt;DoneMessage&amp;gt;(this, &lt;br&gt;    msg =&amp;gt; DisplayState = DisplayState.Normal);&lt;/pre&gt;
&lt;p&gt;Well, okay, one line split in two ;). But anyway, this allows to add a DoneCommand in GeocodeViewModel simply like this: &lt;/p&gt;&lt;pre&gt;[DoNotSerialize]
public ICommand DoneCommand
{
  get
  {
    return new RelayCommand(() =&amp;gt; Messenger.Default.Send(new DoneMessage()));
  }
}&lt;/pre&gt;
&lt;p&gt;And boom – executing the DoneCommand in RoutingViewmodel will reset the DisplayState to Normal, dismissing all popups. That is, as soon as we have implemented the DataTriggers and the ViewStates ;-)&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image_thumb_3.png" width="244" height="87"&gt;&lt;/a&gt;&lt;font size="4"&gt;LocationPanel&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This is the thing used to scroll the GeocodeControls into view, looking like this&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;Grid Height="144" VerticalAlignment="Top" Background="#7F000000"&amp;gt;
  &amp;lt;Grid Margin="12,0"&amp;gt;
    &amp;lt;Grid &amp;gt;
      &amp;lt;!-- Definitions omitted --&amp;gt;
      &amp;lt;TextBlock TextWrapping="Wrap" Text="From" VerticalAlignment="Top"&lt;br&gt;         Margin="0,12,0,0" Height="27"  /&amp;gt;
      &amp;lt;TextBlock TextWrapping="Wrap" Text="To" Grid.Row="1" VerticalAlignment="Top"&lt;br&gt;         Margin="0,12,0,0" Height="27"/&amp;gt;
      
      &amp;lt;TextBlock TextWrapping="Wrap" &lt;font color="#ff0000"&gt;&lt;u&gt;Text="{Binding FromViewModel.SelectedLocation.Address&lt;/u&gt;&lt;/font&gt;, 
        Mode=TwoWay}" Grid.Column="1" VerticalAlignment="Top" Margin="0,12,0,0" /&amp;gt;
      &amp;lt;TextBlock  TextWrapping="Wrap" &lt;u&gt;&lt;font color="#ff0000"&gt;Text="{Binding ToViewModel.SelectedLocation.Address&lt;/font&gt;&lt;/u&gt;, 
        Mode=TwoWay}" Grid.Row="1" Grid.Column="1" VerticalAlignment="Top" Margin="0,12,0,0"  /&amp;gt;
        
      &amp;lt;Button Grid.Column="2"  Style="{StaticResource RoundButton}" 
          &lt;font color="#ff0000"&gt;&lt;u&gt;Command="{Binding DisplayPopupCommand, Mode=OneWay}" CommandParameter="SearchFrom"&lt;/u&gt;&lt;/font&gt;
          VerticalAlignment="Center" HorizontalAlignment="Left" Height="72" &lt;br&gt;          Width="72" Margin="0,0,-10,0" &amp;gt;
        &amp;lt;!-- Rounded button stuff omitted --&amp;gt;
      &amp;lt;/Button&amp;gt;
      &amp;lt;Button Grid.Column="2"  Grid.Row="1" Style="{StaticResource RoundButton}" 
          &lt;font color="#ff0000"&gt;&lt;u&gt;Command="{Binding DisplayPopupCommand, Mode=OneWay}" CommandParameter="SearchTo"&lt;/u&gt;&lt;/font&gt;
          VerticalAlignment="Center" HorizontalAlignment="Left" Height="72" Width="72"&lt;br&gt;           Margin="0,0,-10,0"&amp;gt;
        &amp;lt;!-- Rounded button stuff omitted --&amp;gt;
      &amp;lt;/Button&amp;gt;
    &amp;lt;/Grid&amp;gt;
  &amp;lt;/Grid&amp;gt;
&amp;lt;/Grid&amp;gt;
&lt;/pre&gt;
&lt;p&gt;for the sake of brevity I cut some things out of the XAML. Most interesting to note here, once again &lt;font color="#ff0000"&gt;&lt;u&gt;red and underlined&lt;/u&gt;&lt;/font&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The 3nd and the 4th TextBlock show the Address of the Selected location of the From and the To GeocodeViewModel 
&lt;li&gt;The buttons both call the same command, but with a parameter – this will determine which popup appears. Or actually, the viewstate which will be selected, but that amounts to the same&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image_4.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: right; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Windows-Phone-8-navigation-part-3assembl_D878/image_thumb_4.png" width="194" height="128"&gt;&lt;/a&gt;&lt;font size="4"&gt;ManeuverPopup&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This is the popup that appears from the side, as the user has tapped on a start. &lt;/p&gt;
&lt;p&gt;It’s a pretty simple piece, both how it looks and in XAML:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}" Opacity="0.9"&amp;gt;
  &amp;lt;Grid Margin="12,0" &amp;gt;
    &amp;lt;Grid.RowDefinitions&amp;gt;
      &amp;lt;RowDefinition Height="*"/&amp;gt;
      &amp;lt;RowDefinition Height="76"/&amp;gt;
    &amp;lt;/Grid.RowDefinitions&amp;gt;
    &amp;lt;Grid.ColumnDefinitions&amp;gt;
    &amp;lt;/Grid.ColumnDefinitions&amp;gt;
    &amp;lt;TextBlock Grid.Row="0" TextWrapping="Wrap" Text="{Binding Description}" 
      HorizontalAlignment="Center"/&amp;gt;
    &amp;lt;Button Content="Close" Grid.Row="1" VerticalAlignment="Center"     
      Height="71" Width="313" Command="{&lt;font color="#ff0000"&gt;Binding DoneCommand&lt;/font&gt;}" /&amp;gt;
  &amp;lt;/Grid&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;With only one thing really to note – this popup needs to be able to be dismissed to – so we can implement the exact same DoneCommand as in GeocodeViewModel and put it into ManeuverViewModel. Copy – paste – done. Of course you can also make a base class for both viewmodels and making both GeocodeViewModel ManeuverViewModel child classes of it. This won’t save you much code in this case though.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;MainViewModel&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This is kinda not very interesting – &lt;a href="http://dotnetbyexample.blogspot.nl/2011/01/tombstoning-mvvmlight-viewmodels-with.html" target="_blank"&gt;see for an explanation on usage this post&lt;/a&gt;, that’s quite old already. MainViewModel is the root for all view model, used as a starting point for data binding and tomb stoning But this is what we are going to use a binding root. How the initialization and tombstoning from App.xaml.cs is working is described in the same post, some I am not going to repeat that. This particular MainViewModel looks like this:&lt;/p&gt;&lt;pre&gt;using GalaSoft.MvvmLight;
using NavigationDemo.Logic.Models;

namespace NavigationDemo.Logic.ViewModels
{
  public class MainViewModel : ViewModelBase
  {
    public NavigationModel Model { get; set; }

    public MainViewModel()
    {
    }

    public MainViewModel(NavigationModel model)
    {
      Model = model;
    }

    private RoutingViewmodel routingViewModel;
    public RoutingViewmodel RoutingViewModel
    {
      get
      {
        if (routingViewModel == null)
        {
          routingViewModel = new RoutingViewmodel(Model);
        }
        return routingViewModel;
      }
      set
      {
        if (routingViewModel != value)
        {
          routingViewModel = value;
          RaisePropertyChanged(() =&amp;gt; RoutingViewModel);
        }
      }
    }

    private static MainViewModel instance;
    public static MainViewModel Instance
    {
      get
      {
        return instance;
      }
      set { instance = value; }
    }

    public static MainViewModel CreateNew()
    {
      if (instance == null)
      {
        instance = new MainViewModel(new NavigationModel());
      }
      return instance;
    }
  }
}&lt;/pre&gt;
&lt;p&gt;We define it as a data source in App.Xaml&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;ViewModels:MainViewModel x:Key="MainViewModelDataSource"/&amp;gt;&lt;/pre&gt;Which requires the following definition in your App.xaml header: &lt;pre style="font-size: 7pt"&gt;xmlns:ViewModels="clr-namespace:NavigationDemo.Logic.ViewModels;assembly=NavigationDemo.Logic"&lt;/pre&gt;
&lt;p&gt;&lt;font size="4"&gt;MainPage.xaml – the main gui&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Initially, this has four major parts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The header 
&lt;li&gt;The Map 
&lt;li&gt;The three routing panels (2x GeocodeControl + 1x&amp;nbsp; LocationPanel) 
&lt;li&gt;The ManeuverPopup 
&lt;li&gt;The search button.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Now the header is simple enough:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;Grid x:Name="LayoutRoot" Background="Transparent" 
  &lt;font color="#ff0000"&gt;&lt;u&gt;DataContext="{Binding Instance, Source={StaticResource MainViewModelDataSource}}"&lt;/u&gt;&lt;/font&gt;&amp;gt;
  &amp;lt;Grid.RowDefinitions&amp;gt;
    &amp;lt;RowDefinition Height="Auto"/&amp;gt;
    &amp;lt;RowDefinition Height="*"/&amp;gt;
  &amp;lt;/Grid.RowDefinitions&amp;gt;

  &amp;lt;StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"&amp;gt;
    &amp;lt;TextBlock Text="NAVIGATE BY MVVMLIGHT" 
      Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/&amp;gt;
  &amp;lt;/StackPanel&amp;gt;&lt;/pre&gt;
&lt;p&gt;The only more or less interesting part is the data binding. Then comes the map. This uses my &lt;a href="http://dotnetbyexample.blogspot.nl/2012/10/data-binding-shapes-to-new-windows.html" target="_blank"&gt;MapShapeDrawBehavior&lt;/a&gt; to bind the shapes to map:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" 
   &lt;font color="#ff0000"&gt;&lt;u&gt;DataContext="{Binding RoutingViewModel}"&lt;/u&gt;&lt;/font&gt;&amp;gt;
  &amp;lt;maps:Map Wp8nl_MapBinding:&lt;font color="#ff0000"&gt;&lt;u&gt;MapBindingHelpers.MapArea&lt;/u&gt;&lt;/font&gt;="{Binding ViewArea}"
              &lt;u&gt;&lt;font color="#ff0000"&gt;Center&lt;/font&gt;&lt;/u&gt;="{Binding MapCenter, Mode=TwoWay}"
              &lt;font color="#ff0000"&gt;&lt;u&gt;ZoomLevel&lt;/u&gt;&lt;/font&gt;="{Binding ZoomLevel, Mode=TwoWay}"&amp;gt;
    &amp;lt;i:Interaction.Behaviors&amp;gt;
      &amp;lt;MapBinding:MapShapeDrawBehavior LayerName="Route" ItemsSource="{&lt;font color="#ff0000"&gt;&lt;u&gt;Binding RouteCoordinates&lt;/u&gt;&lt;/font&gt;}" 
        PathPropertyName="Geometry"&amp;gt;
        &amp;lt;MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
          &amp;lt;MapBinding:&lt;font color="#ff0000"&gt;&lt;u&gt;MapPolylineDrawer Color="Green"&lt;/u&gt;&lt;/font&gt; Width="10"/&amp;gt;
        &amp;lt;/MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
      &amp;lt;/MapBinding:MapShapeDrawBehavior&amp;gt;
      &amp;lt;MapBinding:MapShapeDrawBehavior LayerName="Maneuvers" ItemsSource="{&lt;u&gt;&lt;font color="#ff0000"&gt;Binding Maneuvers&lt;/font&gt;&lt;/u&gt;}" 
        PathPropertyName="Location"&amp;gt;
        &amp;lt;MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
          &amp;lt;MapBinding:&lt;font color="#ff0000"&gt;&lt;u&gt;MapStarDrawer Color="Red"&lt;/u&gt;&lt;/font&gt; Arms="8" InnerRadius="25" OuterRadius="50"/&amp;gt;
        &amp;lt;/MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
        &amp;lt;MapBinding:MapShapeDrawBehavior.EventToCommandMappers&amp;gt;
          &amp;lt;MapBinding:EventToCommandMapper EventName="Tap" CommandName="&lt;font color="#ff0000"&gt;&lt;u&gt;SelectCommand&lt;/u&gt;&lt;/font&gt;"/&amp;gt;
        &amp;lt;/MapBinding:MapShapeDrawBehavior.EventToCommandMappers&amp;gt;
      &amp;lt;/MapBinding:MapShapeDrawBehavior&amp;gt;
  &amp;lt;/maps:Map&amp;gt;&lt;/pre&gt;
&lt;p&gt;Things of notice here: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The grid where the map is in (and incidentally, almost the whole user interface, has the RoutingViewModel as it’s data context. 
&lt;li&gt;Map view area is not bindable so that’s bound using a simple attached dependency property, I will include this in the coming version for the &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;&lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl library on codeplex&lt;/a&gt;&lt;/a&gt; but skip it for now. Center and ZoomLevel are simple direct property bindings 
&lt;li&gt;The actual route is a green line, bound to RouteCoordinates. TheMapShapeDrawBehavior actually expects a list of objects, so we &lt;em&gt;gave&lt;/em&gt; it a list, remember from the previous post? 
&lt;li&gt;The Maneuvers are display as red stars, by binding a MapShapeDrawBehavior to the Maneuvers list. If one is tapped, the SelectCommand on the ManeuverViewModel is fired, causing the the selected maneuver to be sent over the Messenger&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Next, are the three panels:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;UserControls:LocationsPanel VerticalAlignment="Top"/&amp;gt;
&amp;lt;UserControls:GeocodeControl &lt;font color="#ff0000"&gt;&lt;u&gt;x:Name="GeocodeFrom"&lt;/u&gt;&lt;/font&gt; VerticalAlignment="Top" 
        RenderTransformOrigin="0.5,0.5" 
        &lt;u&gt;&lt;font color="#ff0000"&gt;DataContext="{Binding FromViewModel}&lt;/font&gt;&lt;/u&gt;"&amp;gt;
  &amp;lt;UserControls:GeocodeControl.RenderTransform&amp;gt;
    &amp;lt;CompositeTransform TranslateY="-326"/&amp;gt;
  &amp;lt;/UserControls:GeocodeControl.RenderTransform&amp;gt;
&amp;lt;/UserControls:GeocodeControl&amp;gt;
&amp;lt;UserControls:GeocodeControl &lt;u&gt;&lt;font color="#ff0000"&gt;x:Name="GeocodeTo"&lt;/font&gt;&lt;/u&gt; VerticalAlignment="Top" 
       RenderTransformOrigin="0.5,0.5"
       &lt;font color="#ff0000"&gt;&lt;u&gt;DataContext="{Binding ToViewModel}&lt;/u&gt;&lt;/font&gt;"&amp;gt;
  &amp;lt;UserControls:GeocodeControl.RenderTransform&amp;gt;
    &amp;lt;CompositeTransform TranslateY="-326"/&amp;gt;
  &amp;lt;/UserControls:GeocodeControl.RenderTransform&amp;gt;
&amp;lt;/UserControls:GeocodeControl&amp;gt;
&amp;lt;UserControls:ManeuverPopup &lt;font color="#ff0000"&gt;&lt;u&gt;x:Name="maneuverPopup"&lt;/u&gt;&lt;/font&gt; VerticalAlignment="Bottom" 
     Height="151" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,72"
     &lt;font color="#ff0000"&gt;&lt;u&gt;DataContext="{Binding SelectedManeuver}&lt;/u&gt;&lt;/font&gt;"&amp;gt;
  &amp;lt;UserControls:ManeuverPopup.RenderTransform&amp;gt;
    &amp;lt;CompositeTransform TranslateX="470"/&amp;gt;
  &amp;lt;/UserControls:ManeuverPopup.RenderTransform&amp;gt;
&amp;lt;/UserControls:ManeuverPopup&amp;gt;&lt;/pre&gt;
&lt;p&gt;Actually rather straightforward. From panel binds to FromViewModel, To panel to ToViewModel, and the maneuverPopup to SelectedManeuver. &lt;/p&gt;
&lt;p&gt;The last part ain’t rocket sciece: just a simple BindableApplicationBar with one button executing the actual routing command:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;phone7Fx:BindableApplicationBar BarOpacity="0.9" &amp;gt;
  &amp;lt;phone7Fx:BindableApplicationBarIconButton Command="{Binding &lt;font color="#ff0000"&gt;&lt;u&gt;RoutingViewModel.DoRoutingCommand&lt;/u&gt;&lt;/font&gt;}"
                                             IconUri="/images/feature.search.png"
                                             Text="Route" /&amp;gt;
&amp;lt;/phone7Fx:BindableApplicationBar&amp;gt;
&lt;/pre&gt;
&lt;p&gt;The only thing to notice is that since it’s sitting outside the content panel, in the main grid, it’s data content is het MainViewModel to I have to prepend the RoutingViewModel again.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;DataTrigger Animation Magic&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;I am going to keep this simple: if you want to know how to create this, I suggest you read my article on &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/viewmodel-driven-multi-state-animations.html"&gt;ViewModel driven multi-state animations using DataTriggers and Blend on Windows Phone&lt;/a&gt;. I have created the following visual states:&lt;/p&gt;&lt;pre style="font-size: 7pt"&gt;&amp;lt;VisualStateManager.CustomVisualStateManager&amp;gt;
  &amp;lt;ei:ExtendedVisualStateManager/&amp;gt;
&amp;lt;/VisualStateManager.CustomVisualStateManager&amp;gt;
&amp;lt;VisualStateManager.VisualStateGroups&amp;gt;
  &amp;lt;VisualState x:Name="&lt;font color="#ff0000"&gt;&lt;u&gt;Normal&lt;/u&gt;&lt;/font&gt;"/&amp;gt;
  &amp;lt;VisualStateGroup x:Name="&lt;font color="#ff0000"&gt;&lt;u&gt;Search&lt;/u&gt;&lt;/font&gt;"&amp;gt;
    &amp;lt;VisualStateGroup.Transitions&amp;gt;
      &amp;lt;VisualTransition GeneratedDuration="0:0:0.5"/&amp;gt;
    &amp;lt;/VisualStateGroup.Transitions&amp;gt;
    &amp;lt;VisualState x:Name="SearchFrom"&amp;gt;
      &amp;lt;Storyboard&amp;gt;
        &amp;lt;DoubleAnimation To="0" 
          Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" 
          Storyboard.TargetName="&lt;font color="#ff0000"&gt;&lt;u&gt;GeocodeFrom&lt;/u&gt;&lt;/font&gt;"/&amp;gt;
      &amp;lt;/Storyboard&amp;gt;
    &amp;lt;/VisualState&amp;gt;
    &amp;lt;VisualState x:Name="&lt;font color="#ff0000"&gt;&lt;u&gt;SearchTo&lt;/u&gt;&lt;/font&gt;"&amp;gt;
      &amp;lt;Storyboard&amp;gt;
        &amp;lt;DoubleAnimation To="0" 
          Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" 
          Storyboard.TargetName="&lt;font style="background-color: #ff0000" color="#ffc000"&gt;&lt;/font&gt;&lt;u&gt;&lt;font color="#ff0000"&gt;GeocodeTo&lt;/font&gt;&lt;font style="background-color: #ff0000" color="#ffc000"&gt;&lt;/font&gt;&lt;/u&gt;"/&amp;gt;
      &amp;lt;/Storyboard&amp;gt;
    &amp;lt;/VisualState&amp;gt;
     &amp;lt;VisualState x:Name="&lt;font style="background-color: #ff0000"&gt;&lt;/font&gt;&lt;u&gt;&lt;font color="#ff0000"&gt;ShowManeuver&lt;/font&gt;&lt;font style="background-color: #ff0000"&gt;&lt;/font&gt;&lt;/u&gt;"&amp;gt;
      &amp;lt;Storyboard&amp;gt;
        &amp;lt;DoubleAnimation Duration="0" To="0" 
          Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" 
          Storyboard.TargetName="&lt;font color="#ff0000"&gt;maneuverPopup&lt;/font&gt;" /&amp;gt;
      &amp;lt;/Storyboard&amp;gt;
    &amp;lt;/VisualState&amp;gt;
  &amp;lt;/VisualStateGroup&amp;gt;
&amp;lt;/VisualStateManager.VisualStateGroups&amp;gt;&lt;/pre&gt;You can see “Search” moves “GeocodeFrom”&amp;nbsp; into view, “SearchTo” moves GeocodeTo into view, and “ShowManeuver”&amp;nbsp; shows the maneuverPopup. And Normal is the base state, basically moving everything back to it’s base place, i.e. out of the screen. I also created these data triggers.&lt;pre style="font-size: 7pt"&gt; &amp;lt;i:Interaction.Triggers&amp;gt;
  &amp;lt;ei:DataTrigger Binding="{Binding DisplayState}" Value="0"&amp;gt;
    &amp;lt;ei:GoToStateAction StateName="Normal" /&amp;gt;
  &amp;lt;/ei:DataTrigger&amp;gt;
  &amp;lt;ei:DataTrigger Binding="{Binding DisplayState}" Value="1"&amp;gt;
    &amp;lt;ei:GoToStateAction StateName="SearchFrom" /&amp;gt;
  &amp;lt;/ei:DataTrigger&amp;gt;
  &amp;lt;ei:DataTrigger Binding="{Binding DisplayState}" Value="2"&amp;gt;
    &amp;lt;ei:GoToStateAction StateName="SearchTo" /&amp;gt;
  &amp;lt;/ei:DataTrigger&amp;gt;
  &amp;lt;ei:DataTrigger Binding="{Binding DisplayState}" Value="3"&amp;gt;
    &amp;lt;ei:GoToStateAction StateName="ShowManeuver" /&amp;gt;
  &amp;lt;/ei:DataTrigger&amp;gt;
&amp;lt;/i:Interaction.Triggers&amp;gt;
&lt;/pre&gt;
&lt;p&gt;These are all sitting inside the contentpanel, right above the map.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;And finally… well… not really&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;If you run the app now – or download the sample solution, lo and behold – the app works as designed. That is … until you press the start button and start the app anew. You will notice the fact that although the right location is displayed, the route is not, the LocationPanel is empty again, but the search text is not. How the hell is this possible? We have written test till the cows came home! &lt;/p&gt;
&lt;p&gt;Well, I can tell you we have run in some very subtle serialization bugs. Fixing those bugs is what we are going to do in the next and last episode. Like I said in the previous episode, no amount of unit and/or integration testing is going to free you from manually testing your app – is just a tool to increase, maintain and guarantee the quality of some parts of your app.&lt;/p&gt;
&lt;p&gt;Anyway – &lt;a href="http://www.schaikweb.net/dotnetbyexample/NavigationDemo3.zip" target="_blank"&gt;the solution so far can be downloaded here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/BPTbRDTX0ys" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-05-10T13:43:39.020+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/05/windows-phone-8-navigation-part.html</feedburner:origLink></item><item><title>Windows Phone 8 navigation part 2–routing, route details,tombstoning–and testing</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/_pjW5hXQL9I/windows-phone-8-navigation-part_29.html</link><category>MVVM</category><category>wpnl</category><category>Unit Test</category><category>Mapping</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Tue, 30 Apr 2013 16:50:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-7642206347526282277</guid><description>&lt;p&gt;&lt;font size="4"&gt;What happened last time on this show&lt;/font&gt;&lt;/p&gt; &lt;p&gt;In &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/windows-phone-8-navigation-part.html" target="_blank"&gt;the previous post&lt;/a&gt; I described to how to write the business logic to find a location by searching for an address by text, how to be able to tombstone the results, and how to make sure this all worked by using simple tests. Fine, but the purpose was &lt;em&gt;routing&lt;/em&gt;, that is, actually making the app finding instructions to get from A to B. As a GIS buff, being used to complex algorithms and stuff, this is almost embarrassingly easy in &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; 8. You basically need an object of type RouteQuery, plonk in any number of waypoints (at least two, of course, being the start and the end) and a method of transport (drive or walk). And that’s basically it.&lt;/p&gt; &lt;p&gt;But we still have to honor the other two requirements – in needs to be testable &lt;em&gt;and&lt;/em&gt; serializable so we can support tombstoning&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Find the route, &lt;strike&gt;Luke&lt;/strike&gt; phone&lt;/font&gt;&lt;/p&gt; &lt;p&gt;So &lt;a href="http://www.schaikweb.net/dotnetbyexample/NavigationDemo1.zip" target="_blank"&gt;in the solution I created last time&lt;/a&gt; I add another business class that does the actual finding of the route:&lt;/p&gt;&lt;pre&gt;using System.Collections.Generic;
using System.Device.Location;
using System.Threading.Tasks;
using Microsoft.Phone.Maps.Services;
using Wp7nl.Utilities;

namespace NavigationDemo.Logic.Models
{
  public class NavigationModel
  {
    public NavigationModel()
    {
      From = new GeocodeModel();
      To = new GeocodeModel();
    }

    public async Task DoRouting()
    {
      await DoRouting(From.SelectedLocation.GeoCoordinate, 
                      To.SelectedLocation.GeoCoordinate);
    }

    public async Task DoRouting(GeoCoordinate from, GeoCoordinate to)
    {
      var wayPoints = new List&amp;lt;GeoCoordinate&amp;gt;(new[] { from, to });
      &lt;font color="#ff0000"&gt;&lt;u&gt;&lt;strong&gt;var routeQuery = new RouteQuery&lt;/strong&gt;&lt;/u&gt;&lt;/font&gt; 
        &lt;strong&gt;&lt;u&gt;&lt;font color="#ff0000"&gt;{ TravelMode = TravelMode.Driving, Waypoints = wayPoints };&lt;/font&gt;&lt;/u&gt;&lt;/strong&gt;
      &lt;font color="#ff0000"&gt;&lt;u&gt;&lt;strong&gt;FoundRoute = await routeQuery.GetRouteAsync();&lt;/strong&gt;&lt;/u&gt;&lt;/font&gt;
    }

    public Route FoundRoute { get; set; }   

    public GeocodeModel From { get; set; }

    public GeocodeModel To { get; set; }
  }
}
&lt;/pre&gt;
&lt;p&gt;This comes in the NavigationDemo.Logic project, in the Models folder, next to GeocodeModel. Here you can see what I just mentioned – the actual navigation logic is very simple. This whole model comes down to three lines (red, bold &lt;em&gt;and &lt;/em&gt;underlined). But, does this work?&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Testing the routing&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;In the unit test app I added a NavigationModelTest class. To ease testing, I created public overload method where I can directly supply the waypoints. We already know the GeocodeModel works. We have tested that before.&lt;/p&gt;&lt;pre&gt;using System;
using System.Device.Location;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using NavigationDemo.Logic.Models;
&lt;br&gt;using Wp7nl.Utilities;&lt;br&gt;
namespace NavigationDemo.Logic.Test
{
  [TestClass]
  public class NavigationModelTest
  {
    [TestMethod]
    public void TestPointRouting()
    {
      var m = new NavigationModel();

      var waitHandle = new AutoResetEvent(false);

      Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
      {
        await m.DoRouting(
            new GeoCoordinate(52.182679977268, 5.39752000942826),
            new GeoCoordinate(52.1061999723315, 5.03457002341747));
        waitHandle.Set();
      });

      waitHandle.WaitOne(TimeSpan.FromSeconds(25));

      Assert.IsTrue(m.FoundRoute.Geometry.Any());
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Route finding is async as well and needs to run on the UI thread, &lt;a href="http://dotnetbyexample.blogspot.nl/2013/03/unit-testing-async-windows-phone-8-code.html" target="_blank"&gt;hence the hoopla with the AutoResetEvent and the Dispatcher&lt;/a&gt;. Basically I ask the the RouteQuery to find some route from one place to another in the Netherlands. For those interested: it’s a road I drove for many a hackathon – from my street to the street where our &lt;a href="http://twitpic.com/mahoekst" target="_blank"&gt;former Dutch DPE Matthijs Hoekstra&lt;/a&gt; used to live before he decided to go upstream &lt;a href="http://familie.hoekstraonline.net/2013/04/15/goodbye-dpe/" target="_blank"&gt;to Seattle to join the Windows Phone team&lt;/a&gt;. I actually seem to recall I wrote this very code in his house at the last ‘kitchen table’ hackathon :-)&lt;/p&gt;
&lt;p&gt;There are two things to wonder at at this point: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Will this serialize to support tombstoning? (remember from the previous post the MapLocation that came back from GeocodeQuery did not) 
&lt;li&gt;What the hell is it that we find?&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;&lt;font size="4"&gt;Does this serialize?&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;I added a second test to NavigationModelTest&amp;nbsp; which is basically an extended version of the first.&lt;/p&gt;&lt;pre&gt;[TestMethod]
public void TestStoreNavigationModel()
{
  var m = new NavigationModel();

  var waitHandle = new AutoResetEvent(false);

  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
  {
    await m.DoRouting(
        new GeoCoordinate(52.182679977268, 5.39752000942826),
        new GeoCoordinate(52.1061999723315, 5.03457002341747));
    waitHandle.Set();
  });

  waitHandle.WaitOne(TimeSpan.FromSeconds(25));

  var h = new IsolatedStorageHelper&amp;lt;NavigationModel&amp;gt;();
  if (h.ExistsInStorage())
  {
    h.DeletedFromStorage();
  }
  h.SaveToStorage(m);

  var retrieved = h.RetrieveFromStorage();

  Assert.IsTrue(retrieved.FoundRoute.Geometry.Any());
}&lt;/pre&gt;
&lt;p&gt;And here we go again: the test fails with SilverlightSerializer complaining that “Could not construct an object of type 'Microsoft.Phone.Maps.Services.Route', it must be creatable in this scope and have a default parameterless constructor”. So we basically have the same problem we had in the previous post. The way to make this test work is to adorn FoundRoute in NavigationModel&lt;/p&gt;&lt;pre&gt;[DoNotSerialize]
public Route FoundRoute { get; set; }&lt;/pre&gt;and change the last line of test a little &lt;pre&gt;Assert.IsNotNull(retrieved);&lt;/pre&gt;
&lt;p&gt;The test now succeeds, but the route you found is now of course still not serialized. You can wonder (or gripe on twitter) why Microsoft have implemented it this way, but that won’t get your app any closer to shipping. It simply means we have to defer tombstoning of the found route to the viewmodel again, just like in the previous post.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;What DO we get back?&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Actually, quite a lot. The routing information is &lt;em&gt;very&lt;/em&gt; detailed. The main Route class has the following properties and methods:&lt;/p&gt;&lt;pre&gt;public class Route : IRoutePath
{
  public LocationRectangle BoundingBox { get; internal set; }
  public TimeSpan EstimatedDuration { get; internal set; }
  public ReadOnlyCollection&amp;lt;Device.Location.GeoCoordinate&amp;gt; Geometry &lt;br&gt;         { get; internal set; }
  public ReadOnlyCollection&amp;lt;RouteLeg&amp;gt; Legs { get; internal set; }
  public int LengthInMeters { get; internal set; }
}
&lt;/pre&gt;
&lt;p&gt;A route can exist out of multiple RouteLeg objects (if you give the RouteQuery more than two waypoints. RouteLeg is defined as follows:&lt;/p&gt;&lt;pre&gt;public class RouteLeg : IRoutePath
{
  public LocationRectangle BoundingBox { get; internal set; }
  public TimeSpan EstimatedDuration { get; internal set; }
  public ReadOnlyCollection&amp;lt;Device.Location.GeoCoordinate&amp;gt; Geometry 
        { get; internal set; }
  public int LengthInMeters { get; internal set; }
  public ReadOnlyCollection&amp;lt;RouteManeuver&amp;gt; Maneuvers 
       { get; internal set; }
}&lt;/pre&gt;
&lt;p&gt;Which makes me feel that a RouteLeg and a Route are nearly the same object and there might have been some code re-use possibilities, but I digress. A RouteLeg consists, apart from a geometry, out of various &lt;em&gt;RouteManeuvers, &lt;/em&gt;which look like this:&lt;/p&gt;&lt;pre&gt;public class RouteManeuver
{
  public RouteManeuverInstructionKind InstructionKind { get; internal set; }
  public string InstructionText { get; internal set; }
  public int LengthInMeters { get; internal set; }
  public GeoCoordinate StartGeoCoordinate { get; internal set; }
}&lt;/pre&gt;
&lt;p&gt;The InstructionText literally contains stuff like “Turn left on xyz street” and a location where this should happen. RouteManeuverInstructionKind is an enum describing the kind of instruction and really is so comprehensive it’s actually a bit hilarious, &lt;a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.maps.services.routemaneuverinstructionkind(v=vs.105).aspx" target="_blank"&gt;so go and have a look on it&lt;/a&gt;. But you can very much use this to depict what you the driver needs to do, and I am pretty sure this is what Nokia’s “Here Drive”&amp;nbsp; uses under the hood. So here we have a full fledged routing API under the hood – but there’s no way in Hades we are ever going to serialize that will all those internal sets, as we already ascertained.&lt;/p&gt;
&lt;p&gt;In real life, at this point you really need to confer with the stakeholder and the designer – what &lt;em&gt;is&lt;/em&gt; it what we are going to show and &lt;em&gt;how&lt;/em&gt; we are going to show it? Since I am both &lt;em&gt;and&lt;/em&gt; developer at this point, I decided I want to show the route on the map as a line, the maneuvers (being the point where you actually need to &lt;em&gt;do&lt;/em&gt; something) as symbols you can tap on, and having a window with the InstructionText to pop up as you do. Basically we’ll end up with a simple routing system in stead of a full fledged navigation app, but we have to start somewhere. And being the lazy *** I am, I am going to re-use the &lt;a href="http://dotnetbyexample.blogspot.nl/2012/10/data-binding-shapes-to-new-windows.html" target="_blank"&gt;map binding behavior&lt;/a&gt; I wrote last year for &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt; and Windows Phone 8. But that’s later. First the view models.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Enter the viewmodels – again&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;The first, and most simple viewmodel is for handling the maneuver we are going to show in the popup&lt;/p&gt;&lt;pre&gt;using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Maps.Controls;
using Wp7nl.Utilities;

namespace NavigationDemo.Logic.ViewModels
{
  public class ManeuverViewModel: ViewModelBase
  {
    private GeoCoordinateCollection location;
    public GeoCoordinateCollection Location
    {
      get { return location; }
      set
      {
        if (location != value)
        {
          location = value;
          RaisePropertyChanged(() =&amp;gt; Location);
        }
      }
    }

    private string description;
    public string Description
    {
      get { return description; }
      set
      {
        if (description != value)
        {
          description = value;
          RaisePropertyChanged(() =&amp;gt; Description);
        }
      }
    }

    [DoNotSerialize]
    public ICommand SelectCommand
    {
      get
      {
        return new RelayCommand(
            () =&amp;gt; Messenger.Default.Send(this),
            () =&amp;gt; true);
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;The command firing of the object itself over the Messenger is a time-tested and tried method I use – if a user selects an object from a list, let a viewmodel that has the actual &lt;em&gt;list&lt;/em&gt; of these objects as a property – I call that the ‘parent’ - handle the select. This prevents a whole lot who messing around with data contexts. Be nice to your designer ;-). Also note the geometry in this class is a GeoCoordinateCollection – although the maneuver is a point, my MapShapeDrawBehavior needs a GeoCoordinateCollection, because it does not know in advance if it needs to draw a point or a shape.&lt;/p&gt;
&lt;p&gt;The next one is a bit awkward and also direct result of the way my MapShapeDrawBehavior behavior works – it needs a &lt;em&gt;list of objects&lt;/em&gt; with a property that’s a GeoCoordinateCollection – this being the geometry. But the RouteLeg gives me a ReadOnlyCollection&amp;lt;GeoCoordinate&amp;gt; and we have only one object – one route. So I write a simple wrapper viewmodel to make sure that it has:&lt;/p&gt;&lt;pre&gt;using System.Collections.Generic;
using System.Device.Location;
using GalaSoft.MvvmLight;
using Microsoft.Phone.Maps.Controls;
using Wp7nl.Utilities;

namespace NavigationDemo.Logic.ViewModels
{
  public class RouteGeometryViewModel : ViewModelBase
  {
    public RouteGeometryViewModel()
    {
    }

    public RouteGeometryViewModel(IEnumerable&amp;lt;GeoCoordinate&amp;gt; coordinates)
    {
      Geometry = new GeoCoordinateCollection();
      Geometry.AddRange(coordinates);
    }

    private GeoCoordinateCollection geometry;
    public GeoCoordinateCollection Geometry
    {
      get { return geometry; }
      set
      {
        if (geometry != value)
        {
          geometry = value;
          RaisePropertyChanged(() =&amp;gt; Geometry);
        }
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;… and make sure the viewmodel holding this object has a list of these. &lt;/p&gt;
&lt;p&gt;And finally, the RoutingViewModel itself, that starts like this:&lt;/p&gt;&lt;pre&gt;using System.Collections.ObjectModel;
using System.Device.Location;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Maps.Controls;
using NavigationDemo.Logic.Models;
using Wp7nl.Utilities;

namespace NavigationDemo.Logic.ViewModels
{
  public class RoutingViewmodel : ViewModelBase
  {
    public RoutingViewmodel()
    {
      Maneuvers = new ObservableCollection&amp;lt;ManeuverViewModel&amp;gt;();
      RouteCoordinates = new ObservableCollection&amp;lt;RouteGeometryViewModel&amp;gt;();

      Messenger.Default.Register&amp;lt;ManeuverViewModel&amp;gt;(this, 
                                                    p =&amp;gt; SelectedManeuver = p);
    }

    public RoutingViewmodel(NavigationModel model)
      : this()
    {
      Model = model;
    }

    private ManeuverViewModel selectedManeuver;
    public ManeuverViewModel SelectedManeuver
    {
      get { return selectedManeuver; }
      set
      {
        selectedManeuver = value;
        RaisePropertyChanged(() =&amp;gt; SelectedManeuver);
      }
    }

    public ObservableCollection&amp;lt;RouteGeometryViewModel&amp;gt; RouteCoordinates &lt;br&gt;                                                        { get; set; }

    public ObservableCollection&amp;lt;ManeuverViewModel&amp;gt; Maneuvers { get; set; }
  }
}&lt;/pre&gt;
&lt;p&gt;In the default constructor sits the standard initialization of the ObservableCollection types, as well as the setup for ManeuverViewModel select interception. Further below another constructor to make initialization from code easier, and the SelectedManeuver property. Nothing special here yet. We add two viewmodels for both to and from searching:&lt;/p&gt;&lt;pre&gt;private GeocodeViewModel toViewModel;
public GeocodeViewModel ToViewModel
{
  get { return toViewModel; }
  set
  {
    if (toViewModel != value)
    {
      toViewModel = value;
      RaisePropertyChanged(() =&amp;gt; ToViewModel);
    }
  }
}

private GeocodeViewModel fromViewModel;
public GeocodeViewModel FromViewModel
{
  get { return fromViewModel; }
  set
  {
    if (fromViewModel != value)
    {
      fromViewModel = value;
      RaisePropertyChanged(() =&amp;gt; FromViewModel);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;And then the public model property as well, with some clever skullduggery here:&lt;/p&gt;&lt;pre&gt;private NavigationModel model;
public NavigationModel Model
{
  get { return model; }
  set
  {
    model = value;
    if (model != null)
    {
      ToViewModel = new GeocodeViewModel(model.To) { Name = "To" };
      FromViewModel = new GeocodeViewModel(model.From) { Name = "From" };
    }
  }
}&lt;/pre&gt;
&lt;p&gt;The “Name” property has no function whatsoever in the code, but I assure you – if you have two identical viewmodels in your app, having them easily distinguishable by a simple property that you can see in a breakpoint helps a ton!&lt;/p&gt;
&lt;p&gt;Finally, the piece that does the actual routing:&lt;/p&gt;&lt;pre&gt;public async Task DoRouting()
{
  await DoRouting(
   FromViewModel.SelectedLocation.Location,
   ToViewModel.SelectedLocation.Location);
}

public async Task DoRouting(GeoCoordinate from, GeoCoordinate to)
{
  RouteCoordinates.Clear();
  Maneuvers.Clear();
  await Model.DoRouting(from, to);
  RouteCoordinates.Add(new RouteGeometryViewModel(Model.FoundRoute.Geometry));
  ViewArea = Model.FoundRoute.BoundingBox;
  Model.FoundRoute.Legs.ForEach(r =&amp;gt;
  Maneuvers.AddRange(
    r.Maneuvers.Select(
      p =&amp;gt; new ManeuverViewModel { &lt;br&gt;            Description = p.InstructionText, &lt;br&gt;            Location = &lt;br&gt;               new GeoCoordinateCollection { p.StartGeoCoordinate }})));
}

[DoNotSerialize]
public ICommand DoRoutingCommand
{
  get
  {
    return new RelayCommand(
        async () =&amp;gt;
        {
          await DoRouting();
        });
  }
}&lt;/pre&gt;
&lt;p&gt;Once again I have a public overload with just coordinates to make testing easier. The line with all the Lambdas basically iterates over all legs of the route, gets all maneuvers per leg, and creates ManeuverViewModel types of every maneuver, using the StartGeoCoordinate of said maneuver to create location. Also note I put the route’s bounding box into a ViewArea property of the RoutingViewModel (code omitted) to enable the designer to let the map zoom to the extent of the new-found route. In the RoutingViewModel are two more properties I omitted – ZoomLevel and MapCenter, they are with ViewArea &lt;a href="http://dotnetbyexample.blogspot.nl/2012/10/introducing-new-windows-8-map-control.html" target="_blank"&gt;taken from the map binding sample I wrote last year&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Well… that’s quite some code. And now the proof of the pudding…&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Testing the RoutingViewModel&lt;/font&gt; &lt;/p&gt;
&lt;p&gt;I added a class RoutingViewModelTest and a simple test method to see if coordinates and maneuvers are duly filled when I call the DoRouting method with coordinates&lt;/p&gt;&lt;pre&gt;using System;
using System.Device.Location;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using NavigationDemo.Logic.Models;
using NavigationDemo.Logic.ViewModels;
using Wp7nl.Utilities;


namespace NavigationDemo.Logic.Test
{
  [TestClass]
  public class RoutingViewModelTest
  {
    [TestMethod]
    public void TestSimpleRoutingViewModel()
    {
      var vm = new RoutingViewmodel(new NavigationModel());

      var waitHandle = new AutoResetEvent(false);

      Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
      {
        await vm.DoRouting(
            new GeoCoordinate(52.182679977268, 5.39752000942826),
            new GeoCoordinate(52.1061999723315, 5.03457002341747));
        waitHandle.Set();
      });

      waitHandle.WaitOne(TimeSpan.FromSeconds(25));

      Assert.IsTrue(vm.RouteCoordinates.Any());
      Assert.IsTrue(vm.Maneuvers.Any());
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Which, not entirely surprising, is the case. Now if you follow the TDD pattern correctly, you should add all kinds of mocks and interfaces between these classes and also test every method separately. I decided to go more for the integration test like route – so I made a big test which basically emulates a complete routing request, tombstones it and checks the result.&lt;/p&gt;&lt;pre&gt;[TestMethod]
public void TestSearchRoutingViewModelAndTombstoning()
{
  var waitHandle = new AutoResetEvent(false);

  var vm = new RoutingViewmodel(new NavigationModel());
  vm.FromViewModel.SearchText = "Springerstraat Amersfoort Netherlands";
  vm.ToViewModel.SearchText = "Heinrich Bertestraat Utrecht";
  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
  {
    await vm.FromViewModel.SearchLocations();
    await vm.ToViewModel.SearchLocations();
    waitHandle.Set();
  });
  waitHandle.WaitOne(TimeSpan.FromSeconds(5));

  Assert.IsTrue(vm.FromViewModel.MapLocations.Any());
  Assert.IsTrue(vm.ToViewModel.MapLocations.Any());

  vm.FromViewModel.SelectedLocation = vm.FromViewModel.MapLocations[0];
  vm.ToViewModel.SelectedLocation = vm.ToViewModel.MapLocations[0];
  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
  {
    await vm.DoRouting();
    waitHandle.Set();
  });

  waitHandle.WaitOne(TimeSpan.FromSeconds(5));

  var h = new IsolatedStorageHelper&lt;routingviewmodel&gt;();
  if (h.ExistsInStorage())
  {
    h.DeletedFromStorage();
  }
  h.SaveToStorage(vm);

  var retrievedVm = h.RetrieveFromStorage();

  Assert.IsTrue(vm.RouteCoordinates.Any());
  Assert.IsTrue(vm.Maneuvers.Any());
  Assert.IsTrue(retrievedVm.RouteCoordinates.Count == vm.RouteCoordinates.Count);
  Assert.IsTrue(retrievedVm.FromViewModel.SearchText == 
    "Springerstraat Amersfoort Netherlands");
  Assert.IsTrue(retrievedVm.Maneuvers.Count == vm.Maneuvers.Count);
}&lt;/pre&gt;
&lt;p&gt;So, I first setup a complete new RoutingViewModel with NavigationModel, simulate the user input two streets and let them search locations. Then I test if there are any locations found at all. I can safely assume they are, &lt;a href="http://dotnetbyexample.blogspot.nl/2013/04/windows-phone-8-navigation-part.html" target="_blank"&gt;since the previous tests worked as well&lt;/a&gt;, but still. Then I actually let the app perform routing, ‘tombstone’ the whole viewmodel and retrieve it again.&lt;/p&gt;
&lt;p&gt;And then I do a number of tests to check if anything is found at all, and if whatever comes back from storage matches what went into it. It will not surprise you – it does. This test is far from comprehensive – you could test all the properties one by one, but at least you now can have a reasonable confidence in the basic workings of your app. What’s more – if you start &lt;em&gt;changing&lt;/em&gt; things and test start failing, you know your app will probably fail too somewhere down the line.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Conclusion (so far)&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;By using unit/integration testing we have been able to make and test a working model of the app, finding out how stuff work and tackling serialization problems head on before we actually made a user interface at all – therefore eliminating potential double work by both you and your designer. Next time we will actually start &lt;em&gt;assembling&lt;/em&gt; the app, and we will learn that no amount of unit testing will eliminate you from the fact that you still need to test your app manually ;-)&lt;/p&gt;
&lt;p&gt;Once again, before I get flamed: technically I showed you how to do &lt;em&gt;integration&lt;/em&gt; tests, not &lt;em&gt;unit&lt;/em&gt; tests, because I tested multiple classes interacting with each other, in stead of single methods and/or properties&lt;/p&gt;
&lt;p&gt;As always, a finished solution (if you can call this finished) &lt;a href="http://www.schaikweb.net/dotnetbyexample/NavigationDemo2.zip" target="_blank"&gt;is available for download here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/_pjW5hXQL9I" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-05-02T08:11:50.266+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/04/windows-phone-8-navigation-part_29.html</feedburner:origLink></item><item><title>Windows Phone 8 navigation part 1–geocoding, tombstoning–and testing</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/rCHDnHPOeVg/windows-phone-8-navigation-part.html</link><category>MVVM</category><category>wpnl</category><category>Unit Test</category><category>Mapping</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Fri, 19 Apr 2013 03:45:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-8655649466651746822</guid><description>&lt;p&gt;After &lt;a href="http://dotnetbyexample.blogspot.nl/2013/03/simple-reverse-geocoding-with-windows.html" target="_blank"&gt;my post about reverse geocoding&lt;/a&gt; I set out to make a little app to demonstrate routing in &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8. The demo app went quite out of hand, so I decided to split the post up in a few smaller posts. In the course of it I am going to build a basic navigation app that enables the user to determine two locations, find a route between those locations, and display them on a map – all using &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt;, of course. &lt;/p&gt; &lt;p&gt;And now the &lt;a href="http://blogs.msdn.com/b/bharry/archive/2013/04/04/vs-tfs-2012-2-update-2-released-today.aspx?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;2012.2 update to Visual Studio&lt;/a&gt; is released, we can finally build Windows Phone MVVM apps the way things are intended to be: by writing some unit test first, getting the basic functions right, before creating an all-out app. This makes it especially handy to test one important requirement that go for all my apps – all the models and viewmodels &lt;em&gt;must be serializabe,&lt;/em&gt; so I can &lt;a href="http://dotnetbyexample.blogspot.nl/2011/01/tombstoning-mvvmlight-viewmodels-with.html" target="_blank"&gt;tombstone using SilverlightSerializer&lt;/a&gt; like I have been doing for over two years now.&lt;/p&gt; &lt;p&gt;At this point I am not really sure how much blog posts this will take me, but I guess at least three, maybe four.&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;What is unit testing and why should I do that?&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Professional software developers are usually all in on this. What you basically do is write code that asserts that pieces of your code are behaving the way you expect them to do. I am sure everyone has had the episode that you change one little thing that &lt;em&gt;should&lt;/em&gt; be inconsequential and suddenly, at some seemingly totally unrelated place, things start going South. Unit tests call little pieces of of your code and test if the result of calling a method, setting a property or whatever gives the result you expect. If you write unit tests, and then change something, and test start failing in unrelated places – it’s like a smoke detector going off. Your code starts detecting bugs for you. Nice, eh? I also gives you the a way to mess around with all kinds of APIs getting things right before you start wasting time on a complex GUI that you can’t get to work because the underlying code cannot work the way you want. &lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;What is geocoding?&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Geocoding is what we GIS buffs say when we mean ‘finding a location on earth by it’s name”. If I put “Boston&amp;nbsp; USA” in a geocoder I expect to get a coordinate that puts me somewhere on the east coast of the United States, if I enter “Springerstraat 36 Netherlands” I expect a coordinate that shows me my own house, or somewhere nearby. Some geocoders can take info that’s not tied to an address, but things like, like ‘town hall Little Rock USA”. In general – in goes a descriptive text, out come one or more matches with coordinates.&lt;/p&gt; &lt;p&gt;Enough introduction. Let’s code.&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Setting the stage&lt;/font&gt;&lt;/p&gt; &lt;p&gt;I started out doing the following:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Create a new Windows Phone App “NavigationDemo”. Target framework 8.0  &lt;li&gt;Add a Windows Phone Class Library “NavigationDemo.Logic”  &lt;li&gt;Add a Windows Phone Unit Test app “NavigationDemo.Logic.Test”  &lt;li&gt;In NavigationDemo, create a reference to NavigationDemo.Logic  &lt;li&gt;In NavigationDemo.Logic.Test, make a reference to NavigationDemo.Logic as well.  &lt;li&gt;In both NavigationDemo and NavigationDemo.Logic.Test, select WMAppManifest.xml in Properties and enable the “ID_CAP_MAP” capbility&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Now, because I am a lazy ******* and like to re-use I did things before, bring in the following nuget packages:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;wp7nl (this will pull in MVVMLight Libraries-only version and the Windows Phone toolkit as well)  &lt;li&gt;Microsoft.Bcl.Async&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;wp7nl also has a Windows Phone 8 version (it’s name is retained for historic reasons). Install both packages in all three projects.&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;GeocodeModel – take one&lt;/font&gt;&lt;/p&gt; &lt;p&gt;In “NavigationDemo.Logic”, add a folder “GeocodeModel” and put the following class in there:&lt;/p&gt;&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Phone.Maps.Services;
using Wp7nl.Utilities;

namespace NavigationDemo.Logic.Models
{
  public class GeocodeModel
  {
    public GeocodeModel()
    {
      MapLocations = new List&amp;lt;MapLocation&amp;gt;();
      SearchLocation = new GeoCoordinate();
    }
    public string SearchText { get; set; }

    public GeoCoordinate SearchLocation { get; set; }

    public MapLocation SelectedLocation { get; set; }

    public List&amp;lt;MapLocation&amp;gt; MapLocations { get; set; }

    public async Task SearchLocations()
    {
      MapLocations.Clear();
      SelectedLocation = null;
      var geoCoder = new GeocodeQuery
      {
        SearchTerm = SearchText,
        GeoCoordinate = SearchLocation
      };
      MapLocations.AddRange(await geoCoder.GetMapLocationsAsync());
      SelectedLocation = MapLocations.FirstOrDefault();
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;To perform geocoding, we need the GeocodeQuery class. So we embed that into a class with a method to perform the actual geocoding, a search string to holds the user input, a list of MapLocation (the output of GeocodeQuery) and SelectedLocation to the user’s selection.&lt;/p&gt;
&lt;p&gt;Note there is also a SearchLocation property of type GeoCoordinate. That’s because the GeocodeQuery also needs a location to start searching from. If the programmer using my model doesn’t set it, I choose a default value. But you can imagine this being useful if someone just enters ‘Amersfoort’ for SearchText and a coordinate somewhere in the Netherlands – that way the GeocodeQuery knows that you want to have Amersfoort in the Netherlands, and not the Amersfoort in South Africa. Anyway, it’s now time for&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Writing the search test&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Add a new class GeocodeModelTest to NavigationDemo.Logic.Test and let’s write our first test:&lt;/p&gt;&lt;pre&gt;using System;
using System.Threading;
using System.Windows;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using NavigationDemo.Logic.Models;

namespace NavigationDemo.Logic.Test
{
  [TestClass]
  public class GeocodeModelTest
  {
    [TestMethod]
    public void TestFindBoston()
    {
      var m = new GeocodeModel { SearchText = "Boston USA" };
      var waitHandle = new AutoResetEvent(false);

      Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
      {
        await m.SearchLocations();
        waitHandle.Set();
       });
      waitHandle.WaitOne(TimeSpan.FromSeconds(5));

      Assert.AreEqual(m.SelectedLocation.GeoCoordinate.Latitude, 42, 1);
      Assert.AreEqual(m.SelectedLocation.GeoCoordinate.Longitude, -71, 1);
      Assert.AreEqual(m.SelectedLocation.Information.Address.City, 
         "Boston");
      Assert.AreEqual(m.SelectedLocation.Information.Address.State,
        "Massachusetts");
      Assert.AreEqual(m.SelectedLocation.Information.Address.Country, 
        "United States of America");
    }
  }
}&lt;/pre&gt;
&lt;p&gt;The GeocodeQuery runs async and needs to run on the UI thread as well. If you have no idea what I am fooling around here with the Dispatcher and the AutoResetEvent, &lt;a href="http://dotnetbyexample.blogspot.nl/2013/03/unit-testing-async-windows-phone-8-code.html" target="_blank"&gt;please read this article first&lt;/a&gt;. Anyway, this test works. Boston is indeed on the east coast of the United States and still in Massachusetts. Most reassuring. Now let’s see if SilverlightSerializer will indeed serialize this. &lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Writing the serialization test – take one&lt;/font&gt;&lt;/p&gt;The first part is basically a repeat of the first test – writing unit test sometimes involves a lot of boring copy &amp;amp; paste work – but the last part is different:&lt;pre&gt; [TestMethod]
 public void TestStoreAndRetrieveBoston()
 {
   var m = new GeocodeModel { SearchText = "Boston USA" };
   var waitHandle = new AutoResetEvent(false);

   Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
   {
     await m.SearchLocations();
     waitHandle.Set();
   });
   waitHandle.WaitOne(TimeSpan.FromSeconds(5));
   Assert.IsNotNull(m.SelectedLocation);

   // Actual test
   var h = new IsolatedStorageHelper&amp;lt;GeocodeModel&amp;gt;();
   if (h.ExistsInStorage())
   {
     h.DeletedFromStorage();
   }
   h.SaveToStorage(m);

   var retrievedModel = h.RetrieveFromStorage();
   Assert.AreEqual(retrievedModel.SelectedLocation.Information.Address.City,
	"Boston");
 }
}&lt;/pre&gt;
&lt;p&gt;Adding this test to GeocodeModelTest will reveal a major bummer – a couple of the classes that are returned by GeocodeQuery – starting with MapLocation - have private constructors and cannot be serialized. Our model cannot be serialized. The usual approach to this kind of problem is to write a kind of wrapper class that &lt;em&gt;can&lt;/em&gt; be serialized. But… using MVVMLight you are most of the time making wrapper classes &lt;em&gt;anyway – &lt;/em&gt;that’s what a ViewModel is, after all, so let’s use that.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Writing the serialization test - take two&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;First, adorn the stuff that cannot be serialized in the GeocodeModel with the [DoNotSerialize] attribute, like this:&lt;/p&gt;&lt;pre&gt;[DoNotSerialize]
public MapLocation SelectedLocation { get; set; }

[DoNotSerialize]
public List&lt;maplocation&gt; MapLocations { get; set; }&lt;/pre&gt;and the test is reduced to this: &lt;pre&gt;[TestMethod]
public void TestStoreAndRetrieveBoston()
{
  var m = new GeocodeModel { SearchText = "Boston USA" };
  // Actual test
  var h = new IsolatedStorageHelper&lt;geocodemodel&gt;();
  if (h.ExistsInStorage())
  {
    h.DeletedFromStorage();
  }
  h.SaveToStorage(m);

  var retrievedModel = h.RetrieveFromStorage();
  Assert.AreEqual(retrievedModel.SearchText, "Boston USA");
}&lt;/pre&gt;
&lt;p&gt;Hurray, this works, but the model’s results are now no longer storing stuff. MapLocations is empty, so is SelectedLocation, if they are deserialized. Bascially we are now only testing if indeed the search test is retained after storage and retrieval. Well, it is.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Enter the viewmodels&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;So far I mainly showed what does &lt;em&gt;not&lt;/em&gt; work. Now it’s time to show what does. First, we make a viewmodel around MapLocation:&lt;/p&gt;&lt;pre&gt;using System.Device.Location;
using GalaSoft.MvvmLight;
using Microsoft.Phone.Maps.Services;

namespace NavigationDemo.Logic.ViewModels
{
  public class MapLocationViewModel : ViewModelBase
  {
    public MapLocationViewModel()
    {
    }

    public MapLocationViewModel(MapLocation model)
    {
      var a = model.Information.Address;

      Address = string.Format("{0} {1} {2} {3} {4}", 
            a.Street, a.HouseNumber, a.PostalCode,
            a.City,a.Country).Trim();
      Location = model.GeoCoordinate;
    }

    private string address;
    public string Address
    {
      get { return address; }
      set
      {
        if (address != value)
        {
          address = value;
          RaisePropertyChanged(() =&amp;gt; Address);
        }
      }
    }

    private GeoCoordinate location;
    public GeoCoordinate Location
    {
      get { return location; }
      set
      {
        if (location != value)
        {
          location = value;
          RaisePropertyChanged(() =&amp;gt; Location);
        }
      }
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;That takes care of the MapLocation not being serializable. Once it is initialized, it does no longer need the model anymore. Which is a good thing, since it cannot be serialized ;-). Next is the GeocodeViewModel itself:&lt;/p&gt;&lt;pre&gt;using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using NavigationDemo.Logic.Models;
using Wp7nl.Utilities;
using System.Linq;

namespace NavigationDemo.Logic.ViewModels
{
  public class GeocodeViewModel : ViewModelBase
  {
    public GeocodeViewModel()
    {
      MapLocations = new ObservableCollection&amp;lt;MapLocationViewModel&amp;gt;();
    }

    public string Name { get; set; }

    public GeocodeViewModel( GeocodeModel model) : this()
    {
      Model = model;
    }

    public GeocodeModel Model{get;set;}

    public ObservableCollection&amp;lt;MapLocationViewModel&amp;gt; MapLocations { get; set; }

    [DoNotSerialize]
    public string SearchText
    {
      get { return Model.SearchText; }
      set
      {
        if (Model.SearchText != value)
        {
          Model.SearchText = value;
          RaisePropertyChanged(() =&amp;gt; SearchText);
        }
      }
    }

    private MapLocationViewModel selectedLocation;
    public MapLocationViewModel SelectedLocation
    {
      get { return selectedLocation; }
      set
      {
        if (selectedLocation != value)
        {
          selectedLocation = value;
          RaisePropertyChanged(() =&amp;gt; SelectedLocation);
        }
      }
    }
    
    public async Task SearchLocations()
    {
      MapLocations.Clear();
      SelectedLocation = null;
      await Model.SearchLocations();
      MapLocations.AddRange(Model.MapLocations.Select( 
        p=&amp;gt; new MapLocationViewModel(p)));
      SelectedLocation = MapLocations.FirstOrDefault();
    }
    
    [DoNotSerialize]
    public ICommand SearchLocationCommand
    {
      get
      {
        return new RelayCommand(async () =&amp;gt; await SearchLocation());
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Notice that the only attribute that &lt;em&gt;is&lt;/em&gt; serialized by the model, is now marked [DoNotSerialize]. This is really important – since the model may not be around yet when deserializing takes place, it would result in a null reference. If you pass things to the model, let the model serialize it. If you don’t let the viewmodel take care of it.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Writing the search test for the viewmodel&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;So since we are now no longer testing the model but the viewmodel, I added a new class “GeocodeViewModeTest” to, well, test the viewmodel.&lt;/p&gt;&lt;pre&gt;using System;
using System.Threading;
using System.Windows;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using NavigationDemo.Logic.Models;
using NavigationDemo.Logic.ViewModels;
using Wp7nl.Utilities;&lt;br&gt;
namespace NavigationDemo.Logic.Test
{
  [TestClass]
  public class GeocodeViewModelTest
  {
    [TestMethod]
    public void TestFindBostonWithViewModel()
    {
      var vm = new GeocodeViewModel(
        new GeocodeModel { SearchText = "Boston USA" });
      var waitHandle = new AutoResetEvent(false);

      Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
        {
          await vm.SearchLocations();
          waitHandle.Set();
      });
      waitHandle.WaitOne(TimeSpan.FromSeconds(5));
      Assert.AreEqual(vm.SelectedLocation.Address, 
         "Boston United States of America");
      Assert.AreEqual(vm.SelectedLocation.Location.Latitude, 42, 1);
      Assert.AreEqual(vm.SelectedLocation.Location.Longitude, -71, 1);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Lo and behold, this test succeeds as well. Now the second test is actually a lot more interesting:&lt;/p&gt;&lt;pre&gt;[TestMethod]
public void TestStoreAndRetrieveBostonWithViewModel()
{
  var vm = new GeocodeViewModel(
    new GeocodeModel { SearchText = "Boston USA" });
  var waitHandle = new AutoResetEvent(false);

  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
  {
    await vm.SearchLocations();
    waitHandle.Set();
  });
  waitHandle.WaitOne(TimeSpan.FromSeconds(5));
  Assert.IsNotNull(vm.SelectedLocation);

  var h = new IsolatedStorageHelper&amp;lt;GeocodeViewModel&amp;gt;();
  if (h.ExistsInStorage())
  {
    h.DeletedFromStorage();
  }
  h.SaveToStorage(vm);

  var retrievedViewModel = h.RetrieveFromStorage();
  Assert.AreEqual(retrievedViewModel.SelectedLocation.Address,
    "Boston United States of America");
  Assert.AreEqual(
    retrievedViewModel.SelectedLocation.Location.Latitude, 42, 1);
  Assert.AreEqual(
    retrievedViewModel.SelectedLocation.Location.Longitude, -71, 1);
}&lt;/pre&gt;
&lt;p&gt;And indeed, after retrieving the viewmodel from storage, the same asserts are fired and the test passes. Success: we can now find location &lt;em&gt;and&lt;/em&gt; tombstone&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Conclusion&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;I showed you some basic geocoding – how to find a location using a text input. I hope I have showed you also that unit tests are not only a way to assure some basic code quality and behavior, but are also a way to determine ahead if things are going to work the way you envisioned. Unit test make scaffolding and proof-of-concept approach of development a lot easier – you need a lot less starting up an app, clicking the right things and then finding breakpoint-by-breakpoint what goes wrong. Quite early in my development stage I ran into the fact that some things were not serializable. Imagine finding that out when the whole app was already mostly done, and then somewhere deep down something goes wrong with the tombstoning. Not fun.&lt;/p&gt;
&lt;p&gt;Complete code – that is, complete for such an incomplete app – &lt;a href="http://www.schaikweb.net/dotnetbyexample/NavigationDemo1.zip" target="_blank"&gt;can be found here&lt;/a&gt;. Next time, we will do some actual navigation.&lt;/p&gt;
&lt;p&gt;To prevent flames from Test Driven Design (TDD) purists: a variant of unit tests are integration test. Technically a unit test tests only tiny things that have no relation to another, like one object, method or property. Integration tests test the workings of larger pieces of code. So technically I am mostly writing integration tests. There, I’ve said it.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/rCHDnHPOeVg" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-04-26T10:00:52.031+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/04/windows-phone-8-navigation-part.html</feedburner:origLink></item><item><title>ViewModel driven multi-state animations using DataTriggers and Blend on Windows Phone</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/Yz09gGrKP-I/viewmodel-driven-multi-state-animations.html</link><category>wpnl</category><category>XAML</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><category>Blend</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Tue, 09 Apr 2013 23:32:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-2911306483147661452</guid><description>&lt;p&gt;Long long time ago I wrote how to &lt;a href="http://dotnetbyexample.blogspot.nl/2011/01/viewmodel-driven-animations-using.html" target="_blank"&gt;drive animations from your ViewModel using DataStateBehavior&lt;/a&gt;, and I explicitly stated this was the only way to do it, since (quoting myself), “Windows Phone 7 does not support &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx"&gt;DataTriggers&lt;/a&gt;”. That was then, and this is now. The drawback of DataStateBehavior is that you basically can only do on/off animations, which makes more complex multi-state animations impossible. There was another behavior that could do that, but I could not find that anymore and I could not quite remember the name. And then I suddenly stumbled upon the Microsoft.Expression.Interactions assembly – and in its Microsoft.Expression.Interactions.Core namespace there is indeed a DataTrigger. And that seems to have been present in the 7.1 framework as well. *Cough*.&lt;/p&gt; &lt;p&gt;So in this blog post I am going to demonstrate how to animate a few ‘popup windows’ via a single Visual State block and a ViewModel, using DataTriggers. I am going to show this using Visual Studio 2012, &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt; and mostly Blend. It’s time to give this unsung hero some love again, so I am going to follow the tutorial-style again.&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 51px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb.png" width="365" height="103"&gt;&lt;/a&gt;Setting the stage&lt;/font&gt;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Open Visual Studio, create a “&lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; app”, and target 8.0 (it should work in 7.1 as well BTW)  &lt;li&gt;Click Tools/Library Package Manager/Manage NuGet Packages for Solution.  &lt;li&gt;Search for MvvmLightLibs, select “MVVM Light Libraries only”  &lt;li&gt;Click “Install”, “Ok” and “I Accept” &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;font size="4"&gt;Building the ViewModel&lt;/font&gt;&lt;/p&gt; &lt;p&gt;The ViewModel actually consist out of two files – an enumeration describing the states and the actual ViewModel itself. First, create a folder “ViewModel” in your solution, and the create the enumeration like this:&lt;/p&gt;&lt;pre&gt;namespace DataTriggerAnimation.ViewModel
{
  public enum DisplayState
  {
    Normal = 0,
    ShowPopupHello = 1,
    ShowPopupBye = 2,
  }
}

&lt;/pre&gt;
&lt;p&gt;And then the ViewModel like this:&lt;/p&gt;&lt;pre&gt;using System;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace DataTriggerAnimation.ViewModel
{
  public class DisplayViewModel : ViewModelBase
  {
    private DisplayState displayState;
    public DisplayState DisplayState
    {
      get { return displayState; }
      set
      {
        if (displayState != value)
        {
          displayState = value;
          RaisePropertyChanged(() =&amp;gt; DisplayState);
        }
      }
    }

    public ICommand DisplayPopupCommand
    {
      get
      {
        return new RelayCommand&amp;lt;string&amp;gt;(
            (p) =&amp;gt;
              {
                DisplayState = (DisplayState)Enum.Parse(typeof(DisplayState), p);
              });
      }
    }

    public ICommand CloseCommand
    {
      get
      {
        return new RelayCommand(() 
           =&amp;gt; DisplayState = DisplayState.Normal);
      }
    }
  }
}

&lt;/pre&gt;
&lt;p&gt;The important thing to note is that the command “DisplayPopupCommand” requires a parameter to determine the popup that must be displayed. The CloseCommand is equivalent to a DisplayPopupCommand with parameter “Normal”, and is just there for making the designer’s life easier.&lt;/p&gt;
&lt;p&gt;… and that’s all the coding we are going to do. Build your application and close Visual Studio. The rest, just like my last animation post is done in Blend! &lt;em&gt;All&lt;/em&gt; of it.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Creating the first panel&lt;/font&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_3.png" width="128" height="135"&gt;&lt;/a&gt;Drag a grid on the empty rectangle “ContentPanel”. Like all GUI objects, these can be found on the Assets tab on the left top. 
&lt;li&gt;Click on the “Grid” in the “Objects on Timeline” pane left, and rename it to “Panel1” 
&lt;li&gt;Right-click on the “Panel1” grid, hit ‘Reset Layout/All” 
&lt;li&gt;Go to the right-hand pane, select “Properties” and expand the “Layout” pane if it’s collapsed. 
&lt;li&gt;Then click “Top” for Vertical Alignment. 
&lt;li&gt;Then enter “150” for height&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Then proceed to add a text:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_4.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_4.png" width="130" height="133"&gt;&lt;/a&gt;Drag a TextBlock on the “Panel1” grid. You can do this by either dragging it on the design surface on top of “Panel1”, or on the “Objects and Timeline” pane (also on top of “Panel1”) 
&lt;li&gt;Change the text from “TextBlock” to “Hello this is popup one” 
&lt;li&gt;Do Reset Layout/All on this text as well 
&lt;li&gt;In the Layout Pane, select Horizontal Alignment “Center” and Vertical Alignment “Top”&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And finally add a button:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_5.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_5.png" width="129" height="124"&gt;&lt;/a&gt;Drag a button on Panel1 
&lt;li&gt;Do Reset Layout/All on this button as well 
&lt;li&gt;Change the caption to “Done” 
&lt;li&gt;In the Layout Pane, select Horizontal Alignment “Center” and Vertical Alignment “Bottom”&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And then finally do something that seems like pretty bonkers, but trust me: it will all become clear in the end:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_6.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_6.png" width="131" height="144"&gt;&lt;/a&gt;Select Panel1 in the Objects and Timeline panel. 
&lt;li&gt;Go to the Properties pane on the right hand side, and find the “Transform” pane. It’s usually collapsed. Expand it first. 
&lt;li&gt;Select Center Point tab - the 2nd tab from the right under “Rendertransform” (with the dot on in) 
&lt;li&gt;For both X and Y type “0.5”. This sets the transformation point dead in the middle of the panel 
&lt;li&gt;Then also select the Global offset tab – that’s the 2nd tab from the right under “Projection” (with the up and left pointing arrow on it) 
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_7.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 0px 0px 0px 2px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_7.png" width="198" height="198"&gt;&lt;/a&gt;Enter “500” for X. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Your design surface now should look like showed on the right. The panel is sitting well right of the phone. Bonkers, I said it. ;-). &lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Creating the second panel&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Going to be a bit lazy here. I don’t want to to the whole sequence again&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Select Panel 1 in “Objects and Timeline” 
&lt;li&gt;Hit CTRL-C, CTRL-V. This will result in a Panel1_Copy below Panel 1 
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_8.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_8.png" width="244" height="121"&gt;&lt;/a&gt;Rename that to “Panel2” 
&lt;li&gt;Go to the Properties tab again on the right, and enter “160” for top margin. This should result in Panel2 appearing &lt;em&gt;under&lt;/em&gt; Panel1 
&lt;li&gt;Then, for an encore, go to the Transform panel again and change “500” for X Projection to -500&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;The second panel should jump to the left and &lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_9.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 0px 35px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_9.png" width="240" height="182"&gt;&lt;/a&gt;resulting design surface should now look like this:&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Creating the popup buttons&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;At this time I am going to assume you now understand the layout panel, so I am not going to make screenshots of every button you need to click and number you need to enter in the layout panels ;-)&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Drag a StackPanel on the design surface, near the bottom of the screen. 
&lt;li&gt;Do Reset Layout/All, 
&lt;li&gt;Select Vertical Alignment Bottom, and enter a height of 220. 
&lt;li&gt;Proceed to drag three buttons on top of the StackPanel. These should appear under each other, taking the full width of the screen. 
&lt;li&gt;Change the captions of the buttons to (from top to bottom) “Popup 1”, “Popup 2” and “Done”. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;The final design surface, including the objects tree, should look like this:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_10.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_10.png" width="628" height="383"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Defining the Visual States&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;We have three visual states:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;None of the popups are displayed 
&lt;li&gt;Popup 1 is displayed 
&lt;li&gt;Popup 2 is displayed&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;To create these, proceed as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_11.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_11.png" width="244" height="112"&gt;&lt;/a&gt;At the top left, click the “States” Tab. 
&lt;li&gt;Click the “Add state Group” Button 
&lt;li&gt;Rename “VisualStateGroup” to "PopupGroup” 
&lt;li&gt;Enter “0.5” for “Default Transition”. This indicates any state transitions will be automatically animated over a 0.5 second time period.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Next steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_12.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_12.png" width="244" height="116"&gt;&lt;/a&gt;Click the “Add state” Button 
&lt;li&gt;Rename the state “VisualState” to “Normal” 
&lt;li&gt;Add two more states, “ShowPopupHello” and “ShowPopupBye” 
&lt;li&gt;Click the red dot before “ShowPopupBye”.&amp;nbsp; The red color disappears. The main design surface should now have a caption “ShowPopupBye state recording is off”&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Now the next things are tricky, so pay close attention and make sure you do this exactly right.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Select “Panel1” in “Objects and Timeline” 
&lt;li&gt;Click state “ShowPopupHello”. The main design surface should now have a caption “ShowHelloPopupstate recording is on” and have a red border. 
&lt;li&gt;Go to the Transform panel again, select under projection the Global offset (2nd tab from the right) again and change 500 back to 0. Panel 1 should now appear in the phone screen 
&lt;li&gt;Now select state “ShowPopupBye”. Panel 1 disappears again 
&lt;li&gt;Select Panel2 
&lt;li&gt;Change its global offset to 0 as well. Now panel 2 appears in the phone screen 
&lt;li&gt;Select State “Normal” 
&lt;li&gt;Select the red dot before “Normal” to turn state recording off. Both panels now should be outside of the phone screen again. 
&lt;li&gt;Select “Base” on top of the State panel.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;font size="4"&gt;Bringing in the ViewModel&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Before we are going to connect the Visual States to the ViewModel’s actions, let’s first bring it in. That’s pretty easy. &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_13.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_13.png" width="168" height="165"&gt;&lt;/a&gt;Go top right and select the data tab. 
&lt;li&gt;Select the “Create data source” button all to the right and select “Create object data source” 
&lt;li&gt;On about the 8th line you should see “DisplayViewModel”. Select that 
&lt;li&gt;Enter “DisplayViewModelDataSource” in the “Data source name” box 
&lt;li&gt;Hit OK. 
&lt;li&gt;Net result should be as displayed to the right.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;font size="4"&gt;Setting up initial data binding&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;This is so ridiculously easy in Blend it always makes me happy when I get to this state.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Drag “DisplayViewModel” from the data tab on top of the LayoutRoot panel in the Objects and Timeline panel 
&lt;li&gt;Drag “CloseCommand” on top of all three “Done” buttons. You can do that either on the design surface or on the Objects and Timeline panel, whatever you like. 
&lt;li&gt;Proceed to drag “PopupCommand” on top of both the “Popup 1” and “Popup 2” button. 
&lt;li&gt;Now select the “Popup 1” button, and select the “Properties” tab again. 
&lt;li&gt;On top there’s a “Search properties” box. The developers of Blend soon recognized the number of things you can set it &lt;em&gt;so&lt;/em&gt; big you can easily loose track. Enter “Command” in that search box to limit the number of properties it shows. 
&lt;li&gt;The Properties box now should only show “Command” and “CommandParameter”. Enter value “ShowPopupHello” for “CommandParameter” 
&lt;li&gt;Now select the “Popup 2” button, and enter “ShowPopupBye” for “CommandParameter” 
&lt;li&gt;Clear the text “Command” from “Search Properties” so you can see all the properties again.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Programming by dragging stuff on top of each other. Ain’t life fun sometimes?&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;&lt;a title="By Mac m 13 (Own work) [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0-2.5-2.0-1.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons" href="http://commons.wikimedia.org/wiki/File%3AFurioso_dragon-13-.jpg"&gt;&lt;img style="float: right; margin: 0px 34px 0px 0px; display: inline" alt="Furioso dragon-13-" align="right" src="http://upload.wikimedia.org/wikipedia/commons/6/63/Furioso_dragon-13-.jpg" width="182" height="220"&gt;&lt;/a&gt;Enter the dragon: datatriggers for putting it all together&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;And now for the &lt;em&gt;really&lt;/em&gt; scary part – the datatriggers. Just kidding of course – just more dragging stuff and filling in some fields. The odd thing is – from the Blend perspective, data triggers are hardly visible. We are using &lt;em&gt;GotoStateActions&lt;/em&gt;. Finish the app by following these final steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Drag a GotoStateAction from Assets box on top of ContentPanel. If you can’t find it: type “goto” in the search box of the Asset panel. It will popup in the list to the right of the panel 
&lt;li&gt;Under Properties, Click on the “New” button next to “TriggerType” and select “DataTrigger” in the box that pops up. 
&lt;li&gt;Behind “Binding”, click the barrel like icon. A dialog pops up with the properties of your DisplayViewModel. Select “DisplayState” and hit OK 
&lt;li&gt;Enter “0” for value 
&lt;li&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_15.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/ViewModel-driven-multi-state-animations-_796F/image_thumb_15.png" width="142" height="169"&gt;&lt;/a&gt;For StateName, select “Normal” 
&lt;li&gt;Drag another GotoStateAction from Assets box on top of ContentPanel. Make this a DataTrigger to, select the same property to bind to, but 
&lt;ul&gt;
&lt;li&gt;Enter “1” for “Value” 
&lt;li&gt;Select “ShowPopupHello” for StateName&lt;/li&gt;&lt;/ul&gt;
&lt;li&gt;And finally, a third GotoStateAction with 2 as value and “ShowPopupBye” for StateName.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And that’s all. If you run your application (you should be able to hit F5 from Blend) you will get a simple app that scrolls Popup 1 from the left in half a second when you hit “Popup 1”, and scroll it back when you hit on of the done buttons. If you hit the “Popup 2” button when Popup 1 is visible, it will scroll the second popup into the screen while simultaneously scrolling the first on &lt;em&gt;out&lt;/em&gt; of the screen.&lt;/p&gt;
&lt;p&gt;The data triggers look like this in XAML:&lt;/p&gt;&lt;pre&gt;&amp;lt;i:Interaction.Triggers&amp;gt;
  &amp;lt;ec:DataTrigger Binding="{Binding DisplayState}" Value="0"&amp;gt;
    &amp;lt;ec:GoToStateAction StateName="Normal"/&amp;gt;
  &amp;lt;/ec:DataTrigger&amp;gt;
  &amp;lt;ec:DataTrigger Binding="{Binding DisplayState}" Value="1"&amp;gt;
    &amp;lt;ec:GoToStateAction StateName="ShowPopupHello"/&amp;gt;
  &amp;lt;/ec:DataTrigger&amp;gt;
  &amp;lt;ec:DataTrigger Binding="{Binding DisplayState}" Value="2"&amp;gt;
    &amp;lt;ec:GoToStateAction StateName="ShowPopupBye"/&amp;gt;
  &amp;lt;/ec:DataTrigger&amp;gt;
&amp;lt;/i:Interaction.Triggers&amp;gt;&lt;/pre&gt;
&lt;p&gt;&lt;font size="4"&gt;Some things to note&lt;/font&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We hardly did program anything at all, and what’s more – we did not even make animations or storyboards. By simply setting the default transition to 0.5 seconds and indicating where we want stuff to be once a state is reached, the Windows Phone framework automatically &lt;em&gt;infers and creates &lt;/em&gt;an animation when changing state, moving the GUI elements from one place to another in half a second (in stead of flashing them from one place to another). 
&lt;li&gt;In the &lt;em&gt;Command&lt;/em&gt; I was able to use &lt;em&gt;names&lt;/em&gt; as defined in the enumeration because I did an Enum.Parse in the ViewModel, in the data triggers I had to use the real &lt;em&gt;value&lt;/em&gt; (0,1,2) to be able to compare. Something that can be fixed using a converter, but I did not want to complicate things. 
&lt;li&gt;The fact that the visual state names have the same name as the enumeration values, does not bear any significance. I could have named them Huey, Dewey, and Louie for all I cared. Only the CommandParameter values need to be the same as the Enumeration &lt;em&gt;string&lt;/em&gt;, and the DataTriggers need to have the same &lt;em&gt;numeric&lt;/em&gt; value.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;That’s it. Although the Visual Studio 2012 designer is light years ahead of the 2010 designer, Blend still rocks when defining a lot of stuff in XAML. Have fun making beautifully animated apps with this. &lt;/p&gt;
&lt;p&gt;If you don’t feel like following all these steps yourself, find, as usual, &lt;a href="http://www.schaikweb.net/dotnetbyexample/DataTriggerAnimation.zip" target="_blank"&gt;the completed solution here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/Yz09gGrKP-I" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-04-22T08:54:30.741+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/04/viewmodel-driven-multi-state-animations.html</feedburner:origLink></item><item><title>Enabling basic OpenLayers pinch zooming for Internet Explorer 10 touch events</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/1PzIoY9m6mw/enabling-basic-openlayers-pinch-zooming.html</link><category>OpenLayers</category><category>Javascript</category><category>touch</category><category>Mapping</category><category>html</category><category>css</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 27 Mar 2013 10:43:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-7437229720049471878</guid><description>&lt;p&gt;A phenomenon described by the term &lt;a href="http://www.bing.com/search?q=webkit+monoculture" target="_blank"&gt;‘webkit monoculture’&lt;/a&gt; is causing quite some concern in the web development community. A lot of web developers are basically coding for webkit and webkit only, or more specifically Safari on IOS. HTML5 and standards are great, but certain parts of the web development stack are moving back to a ‘works on my environment’ status &lt;a href="http://www.ie6countdown.com/" target="_blank"&gt;that we just were getting rid of&lt;/a&gt;. This phenomenon rears it’s ugly head itself on all kind of places, including in the &lt;a href="http://www.openlayers.org/" target="_blank"&gt;OpenLayers&lt;/a&gt; toolkit that I am using for my work at &lt;a href="http://www.vicrea.nl" target="_blank"&gt;Vicrea&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;For those not familiar with OpenLayers: think Google Maps, but then with real GIS functionality, without commercial licensing, without ads in the map, and without all kind of legal strings attached. Pure open source client side web GIS. With the advent of touch devices its community added some basic touch functionality to it, like pinch zoom. That works very smooth, provided – you guessed it – you work on a web kit based browser. Microsoft, in all its wisdom, has chose to implement touch events in a completely different way. As to why this is, and what exactly is standard or not – that is not exactly my concern here. I am making a web GIS that is not supported my Windows 8 touch devices and &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8. That, of course, is unacceptable to me ;-)&lt;/p&gt; &lt;p&gt;So I created a little OpenLayers style control that adds pinch zoom to Internet Explorer 10. It’s pure JavaScript and a little primitive – it’s basically zooming in on the map center, and not on the point between your fingers, but it’s working pretty well IMHO.&lt;/p&gt; &lt;p&gt;It also works pretty &lt;em&gt;simple&lt;/em&gt;: upon the activate command, it hooks itself onto two events of the map’s layerContainerDiv – MSPointerDown and MSGestureChanged. The first one is fired at the first touch point going down, the second one when MSGesture recognizes an MSGestureChanged. Important is also setting the map’s fractionalZoom property to true.&lt;/p&gt;&lt;pre&gt;OpenLayersWindowsPinchZoom = OpenLayers.Class(OpenLayers.Control,
  {
    autoActivate: true,

    gesture: null,

    defaultHandlerOptions: {},

    initialize: function (options)
    {
      this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
      OpenLayers.Control.prototype.initialize.apply(this, options);
    },

    activate: function ()
    {
      if (OpenLayers.Control.prototype.activate.apply(this, arguments))
      {
        if (window.navigator.msPointerEnabled)
        {
          this.map.fractionalZoom = true;

          this.gesture = new MSGesture();
          this.gesture.target = this.map.layerContainerDiv;
          var self = this;

          this.gesture.target.addEventListener("MSPointerDown", function (evt)
          {
            self.gesture.addPointer(evt.pointerId);
          });

          this.gesture.target.addEventListener("MSGestureChange", function (evt)
          {
            // Make scale result smaller to prevent high zoom speeds.
            if (evt.scale !== 1)
            {
              var scale = 1;
              if (evt.scale &amp;gt; 1)
              {
                scale = (evt.scale - 1) / 4 + 1;
              }
              else
              {
                scale = 1 - ((1 - evt.scale) / 4);
              }
              // map.zoomTo is buggy as hell so I use this convoluted way to 
              // calculate a new zoom area
              var resolution = self.map.getResolutionForZoom(self.map.zoom * scale);
              var bounds = self.map.calculateBounds(self.map.getCenter(), resolution);
              self.map.zoomToExtent(bounds);
            }
          });
        }
        return true;
      }
      else
      {
        return false;
      }
    },

    CLASS_NAME: "OpenLayersWindowsTouch"
  }
);
&lt;/pre&gt;
&lt;p&gt;The MSGestureChanged event has a scale, which is a number either bigger (zoom in) or smaller (zoom out) than 1. After that it’s simply calling some standard map functions to calculate the new display area and fire away. The most logical one to use would be map.ZoomTo, but that completely messes up the map tile layout after a few times and this workaround via the resolution calculation prevents that. I assume there is a bug in the zoomTo code.&lt;/p&gt;
&lt;p&gt;There is another detail – to prevent Internet Explorer to handle the zoom events itself, you have to mark the div in which the map will come with css style:&lt;/p&gt;&lt;pre&gt;-ms-touch-action: none&lt;/pre&gt;
&lt;p&gt;I did that inline for the sake of simplicity ;-)&lt;/p&gt;&lt;pre&gt;&amp;lt;div id="map2" class="smallmap" style="-ms-touch-action: none"&amp;gt;&amp;lt;/div&amp;gt;&lt;/pre&gt;
&lt;p&gt;As for creating the map with the control enabled: this is a normal map with just the standard controls:&lt;/p&gt;&lt;pre&gt;map1 = new OpenLayers.Map('map1', 
	 {controls: [new OpenLayers.Control.Navigation(), 
                       new OpenLayers.Control.PanZoomBar()], 
	  numZoomLevels: 15});&lt;/pre&gt;while the second one sports my new control as well:&lt;pre&gt;map2 = new OpenLayers.Map('map2', 
	 {controls: [new OpenLayers.Control.Navigation(), 
		  new OpenLayers.Control.PanZoomBar(),
		  &lt;font color="#ff0000"&gt;&lt;u&gt;new OpenLayersWindowsPinchZoom()&lt;/u&gt;&lt;/font&gt;], 
	  numZoomLevels: 15});&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Enabling-basic-OpenLayers-pinch-zooming-_DF02/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 7px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="left" src="http://www.schaikweb.net/dotnetbyexample/Enabling-basic-OpenLayers-pinch-zooming-_DF02/image_thumb.png" width="260" height="305"&gt;&lt;/a&gt;And that’s all there is to it. For the OpenLayers purists: yes, I am aware that I don’t implement destroy and potentially create memory leaks. I just wanted to kick off IE10 support. I hope the ‘real’ OpenLayers developers do better and now start supporting IE10 by themselves ;-)&lt;/p&gt;
&lt;p&gt;I have made a little live demo site which looks like showed on the left. &lt;a href="http://www.schaikweb.net/dotnetbyexample/ie10olpinchzoom/demowinpinch.html" target="_blank"&gt;You can watch it live here&lt;/a&gt; and download a zip file containing &lt;a href="http://www.schaikweb.net/dotnetbyexample/ie10olpinchzoom/OpenLayersWindowsPinchZoom.zip" target="_blank"&gt;all the necessary file in one go here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The control has been tested successfully on a Nokia Lumia Windows Phone 8, a Microsoft RT and a Microsoft Surface Pro. &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/1PzIoY9m6mw" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-03-27T19:35:28.640+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/03/enabling-basic-openlayers-pinch-zooming.html</feedburner:origLink></item><item><title>Unit testing async Windows Phone 8 code on the UI thread with VS 2012.2 CTP4</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/hcUs1Ta39xc/unit-testing-async-windows-phone-8-code.html</link><category>wpnl</category><category>Unit Test</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Thu, 21 Mar 2013 12:38:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-5106540278545062181</guid><description>&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image_thumb.png" width="468" height="341"&gt;&lt;/a&gt;This may be the most cryptic acronym-laden title I ever used for a blog post, but it quite exactly describes what I was trying to do yesterday. &lt;/p&gt; &lt;p&gt;The &lt;a href="http://blogs.msdn.com/b/visualstudioalm/archive/2013/03/04/march-ctp-of-visual-studio-update-2.aspx" target="_blank"&gt;Visual Studio 2012 CTP4&lt;/a&gt; makes it possible to write real &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8 unit tests that run in the Visual Studio Unit Test runner (in stead of only on the emulator). So when I wanted to investigate the Routing API that is new in Windows Phone 8, I decided not to write an application outright, but start out with unit test.&lt;/p&gt; &lt;p&gt;I set up a new solution with two projects, as I usually do: one with the actual app - and one class library with the view models, models and other logic in it that isnot directly related to the user interface. And then I added a Windows Phone 8 Unit Test App. &lt;/p&gt; &lt;p&gt;First things first: when I want to test routing, I first need to give the user an option to select a location to go to. I decided to use the Geocoding API. I decided the view model should contain the following:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;A string property SearchText to be filled by the user  &lt;li&gt;An ObservableCollection of MapLocation called MapLocations to be filled by the Geocoder, intended to be bound to a list control of some kind to enable the user to select on of the founds locations.  &lt;li&gt;A MapLocation property SelectedLocation to hold the MapLocation selected by the user  &lt;li&gt;A little method to actually perform the geocoding  &lt;li&gt;A command wrapping this method.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;My good and very smart friend - and fellow Phone development MVP - &lt;a href="http://www.twitter.com/qmatteoq" target="_blank"&gt;Matteo Pagani&lt;/a&gt; has already covered some ground in this direction by &lt;a href="http://wp.qmatteoq.com/unit-testing-in-windows-phone-8-asynchronous-operations-and-mocking/" target="_blank"&gt;writing this article&lt;/a&gt; and inspired by it I decided to pull in the Microsoft.Bcl.Async library as well so I could use async/await, on the premises that you can never have too much beta software in your project ;-)&lt;/p&gt; &lt;p&gt;The method I wanted to test was pretty simple:&lt;/p&gt;&lt;pre&gt;public async Task SearchLocation()
{
  MapLocations.Clear();
  SelectedLocation = null;
  var geoCoder = new GeocodeQuery { &lt;br&gt;    SearchTerm = SearchText, 
    GeoCoordinate = new GeoCoordinate() };
  MapLocations.AddRange(await geoCoder.GetMapLocationsAsync());
}&lt;/pre&gt;
&lt;p&gt;And so was the test method – I let it search for the street I live in.&lt;/p&gt;&lt;pre&gt;[TestMethod]
public async Task TestLocationWrong1()
{
  var testVm = new GeocodeViewModel
    {SearchText = "Springerstraat Amersfoort Netherlands"};
  await testVm.SearchLocation();
  Assert.IsTrue(testVm.MapLocations.Any());
}&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image_thumb_3.png" width="157" height="195"&gt;&lt;/a&gt;I ran the test…. and was quite surprised by the result. “Invalid cross thread access"??? I don’t even &lt;em&gt;have&lt;/em&gt; a UI. Very interesting. Apparently the GeocodeQuery needs to be run on the UI thread. As to why this is, I have no idea. Some people (hi Morten ;-) ) say that if you have to unit test on the UI thread, you are doing it wrong. That may be the case, but it seems I have little choice here and&amp;nbsp; I still want to test my view model.&lt;/p&gt;
&lt;p&gt;According to &lt;a href="http://blogs.msdn.com/b/visualstudioalm/archive/2013/01/30/first-ctp-for-visual-studio-update-2.aspx" target="_blank"&gt;this page&lt;/a&gt; there is a UITestMethodAttribute for Windows Store applications to solve this kind of problems – but not for Windows Phone 8 (yet) so obviously I had to pull in the Dispatcher. Since calling stuff from the Dispatcher runs asynchronously as well take 2 didn’t work of course…&lt;/p&gt;&lt;pre&gt;[TestMethod]
public void TestLocationWrong2()
{
  var testVm = new GeocodeViewModel 
  { SearchText = "Springerstraat Amersfoort Netherlands" };
  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt; await testVm.SearchLocation());
  Assert.IsTrue(testVm.MapLocations.Any());
}&lt;/pre&gt;
&lt;p&gt;…for the simple reason that the although testVM.SearchLocation is now fired on the UI thread, the Assert is not, and it is executed directly after the BeginInvoke is called and MapLocations still is empty when the Assert is evaluated.&lt;/p&gt;
&lt;p&gt;I don’t know if there’s a smarter way to do this, but I used an AutoResetEvent to solve it. I used that to block the test thread until the UI thread is done, like this:&lt;/p&gt;&lt;pre&gt;[TestMethod]
public void TestLocationSearchHasResult()
{
  var waitHandle = new &lt;font color="#ff0000"&gt;AutoResetEvent(false)&lt;/font&gt;;
  var testVm = new GeocodeViewModel { SearchText = "Springerstraat Amersfoort Netherlands" };
  Deployment.Current.Dispatcher.BeginInvoke(async () =&amp;gt;
    {
      await testVm.SearchLocation();
      &lt;font color="#ff0000"&gt;waitHandle.Set();&lt;/font&gt;
    });
  &lt;font color="#ff0000"&gt;waitHandle.WaitOne(TimeSpan.FromSeconds(5));&lt;/font&gt;
  Assert.IsTrue(testVm.MapLocations.Any());
}&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image_4.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 10px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="left" src="http://www.schaikweb.net/dotnetbyexample/Unit-testing-async-Windows-Phone-8-code-_1129E/image_thumb_4.png" width="204" height="119"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The test thread waits until waitHandle.Set() is called – or five seconds, whatever happens first – and &lt;em&gt;then&lt;/em&gt; it performs the Assert. And that works.&lt;/p&gt;
&lt;p&gt;As usual, you can &lt;a href="http://schaikweb.net/dotnetbyexample/NavigationTest.zip" target="_blank"&gt;download a demo solution here&lt;/a&gt;. It was actually meant to be a solution demoing the Route API, as stated earlier, but I thought this subject deserved a blog post on its own.&lt;/p&gt;
&lt;p&gt;As stated, this project requires installation of the &lt;a href="http://blogs.msdn.com/b/visualstudioalm/archive/2013/03/04/march-ctp-of-visual-studio-update-2.aspx" target="_blank"&gt;Visual Studio 2012 CTP4&lt;/a&gt;. This has a GoLive license, but it’s still preview software. Install it on your own risk.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;: Pedro Lamas, a Windows Phone Development specialist working for Nokia, &lt;a href="http://www.pedrolamas.com/2013/03/25/windows-phone-8-unit-testing-in-the-ui-thread-with-vs-2012-2-ctp4/" target="_blank"&gt;has posted about his port of UITestMethodAttribute to Windows Phone&lt;/a&gt;. That runs the &lt;em&gt;whole&lt;/em&gt; test on the UI thread in stead of only the the mandatory part. This brute-force method may not be desirable for all cases, but it sure is pretty easy to use. &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/hcUs1Ta39xc" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-03-26T13:04:11.142+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">4</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/03/unit-testing-async-windows-phone-8-code.html</feedburner:origLink></item><item><title>Simple reverse geocoding with Windows Phone 8 and MVVMLight</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/e7pUVJujwX0/simple-reverse-geocoding-with-windows.html</link><category>MVVM</category><category>behavior</category><category>wpnl</category><category>Mapping</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 13 Mar 2013 08:07:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-4457715978674132878</guid><description>&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Simple-reverse-geocoding-with-Windows-Ph_CC75/screenshot.png"&gt;&lt;img title="screenshot" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; margin: 0px 0px 12px 4px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="screenshot" align="right" src="http://www.schaikweb.net/dotnetbyexample/Simple-reverse-geocoding-with-Windows-Ph_CC75/screenshot_thumb.png" width="197" height="336"&gt;&lt;/a&gt;Having worked in Geographical Information Systems over 20 years, I can tell you rightfully the new &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; 8 mapping and location abilities are more than enough to make a map maniac like me getting twinkly eyes. It has capabilities that are unheard of even just a couple of years ago – and I don’t need a big workstation, I don’t even need a PC - it’s running on my phone. The world in my pocket – in the most literal sense possible.&lt;/p&gt; &lt;p&gt;Two popular applications of GIS are &lt;em&gt;geocoding&lt;/em&gt; and &lt;em&gt;reverse geocoding&lt;/em&gt;. Geocoding enables you to find the position of earth for a descriptive text – say an address, city, building name, or any other phrase indicating a place on Earth. This is usually rather straightforward. &lt;em&gt;Reverse&lt;/em&gt; geocoding is exactly the opposite – it’s the “what’s here?” question – given a location, &lt;em&gt;what do I&lt;/em&gt;&amp;nbsp;&lt;em&gt;find here? &lt;/em&gt;Incidentally, answering questions like this is how I make a living at &lt;a href="http://www.vicrea.nl" target="_blank"&gt;Vicrea&lt;/a&gt;. &lt;/p&gt; &lt;p&gt;Windows Phone 8 makes reverse geocoding almost embarrassingly easy. Even when using &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt;. So I made a simple app that show the address(es) found at the location where you tap on the map.&lt;/p&gt; &lt;p&gt;We start off with a simple model with two properties:&lt;/p&gt;&lt;pre&gt;using System.Collections.ObjectModel;
using System.Device.Location;
using System.Linq;
using GalaSoft.MvvmLight;
using Microsoft.Phone.Maps.Services;

namespace TapReverseGeocode.Logic.ViewModels
{
  public class MapViewModel : ViewModelBase
  {
    public MapViewModel()
    {
      Addresses = new ObservableCollection&amp;lt;string&amp;gt;();
    }

    private GeoCoordinate tapCoordinate;
    public GeoCoordinate TapCoordinate
    {
      get { return tapCoordinate; }
      set
      {
        tapCoordinate = value;
        RaisePropertyChanged(() =&amp;gt; TapCoordinate);
        StartReverseGeoCoding();
      }
    }

    public ObservableCollection&amp;lt;string&amp;gt; Addresses { get; set; }
  }
}&lt;/pre&gt;
&lt;p&gt;The ObservableCollection “Addresses” will hold the results, and as usual when binding to ObservableCollection you must make sure it is initialized before anything else – the constructor is a good place for that. The designer can bind this to some kind of GUI element that displays the result. &lt;/p&gt;
&lt;p&gt;The TapCoordinate property is a GeoCoordinate and that fires off the actual reverse geocoding – and I have omitted the usual “&lt;strong&gt;if (viewModelPropertyName != value)&lt;/strong&gt;” check on purpose. Even when the user taps the same location twice, I want to have the reverse geocoding code to fire every time.&lt;/p&gt;
&lt;p&gt;The code that starts the reverse geocoding itself ain’t quite rocket science:&lt;/p&gt;&lt;pre&gt;private void StartReverseGeoCoding()
{
  var reverseGeocode = new ReverseGeocodeQuery();
  reverseGeocode.GeoCoordinate = 
    new GeoCoordinate(TapCoordinate.Latitude, TapCoordinate.Longitude);
  reverseGeocode.QueryCompleted += ReverseGeocodeQueryCompleted;
  reverseGeocode.QueryAsync();
}&lt;/pre&gt;
&lt;p&gt;To prevent race conditions I make a new GeoCoordinate from the one provided by the user, set up a call back, and fire off the async query.&lt;/p&gt;
&lt;p&gt;The final piece is this simple callback that processes the result of the reverse geocoding.&lt;/p&gt;&lt;pre&gt;private void ReverseGeocodeQueryCompleted(object sender, 
  QueryCompletedEventArgs&amp;lt;System.Collections.Generic.IList&amp;lt;MapLocation&amp;gt;&amp;gt; e)
{
  var reverseGeocode = sender as ReverseGeocodeQuery;
  if (reverseGeocode != null)
  {
    reverseGeocode.QueryCompleted -= ReverseGeocodeQueryCompleted;
  }
  Addresses.Clear();
  if (!e.Cancelled)
  {
    foreach (var adress in e.Result.Select(adrInfo =&amp;gt; adrInfo.Information.Address))
    {
      Addresses.Add(string.Format("{0} {1} {2} {3} {4}", 
        adress.Street, adress.HouseNumber, adress.PostalCode,
        adress.City,adress.Country).Trim());
    }
  }
}&lt;/pre&gt;
&lt;p&gt;It clears up the callback, clears the Addresses list, and then processes the parts of the result into a single string per address. Like any good reverse geocoding service Microsoft have implemented this to return a &lt;em&gt;set&lt;/em&gt; of results – there may be more addresses on one location, for instance in a large apartment building – although I never got more than one result back per location when I tested this in the Netherlands.&lt;/p&gt;
&lt;p&gt;This a complete reverse geocoding viewmodel that basically does not care where the GeoCoordinate comes from, or the result goes to. So this is very versatile. There isn’t any GUI, and yet we already have a working app&lt;/p&gt;
&lt;p&gt;The initial XAML for binding this stuff – after setting the datacontext to this viewmodel – looks pretty simple:&lt;/p&gt;&lt;pre&gt;&amp;lt;Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"&amp;gt;
  &amp;lt;maps:Map/&amp;gt;
  &amp;lt;Grid Height="58" VerticalAlignment="Top" Background="#7F000000"&amp;gt;
    &amp;lt;phone:LongListSelector ItemsSource="{Binding Addresses}" 
      HorizontalContentAlignment="Left" Margin="12,0"/&amp;gt;
  &amp;lt;/Grid&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;… and then we run into a challenge. Two actually. The last tapped location &lt;em&gt;is not a property we can bind to&lt;/em&gt;, and that the location is a &lt;em&gt;Point&lt;/em&gt; – a &lt;em&gt;screen location&lt;/em&gt;, not a GeoCoordinate in real world coordinates. &lt;/p&gt;
&lt;p&gt;This can be solved by using an Attached Dependency Property (I think), by some Code Behind or my trademark way - by creating a simple behavior. After all, I don’t want to bother designers with code and I like the easy reusability of a behavior:&lt;/p&gt;&lt;pre&gt;using System.Device.Location;
using System.Windows;
using Microsoft.Phone.Maps.Controls;
using Wp7nl.Behaviors;

namespace Wp8nl.Behaviors
{
  public class TapToCoordinateBehavior : SafeBehavior&amp;lt;Map&amp;gt;
  {
    protected override void OnSetup()
    {
      AssociatedObject.Tap += AssociatedObjectTap;
    }

    void AssociatedObjectTap(object sender, 
      System.Windows.Input.GestureEventArgs e)
    {
      var tapPosition = e.GetPosition((UIElement)sender);
      TappedCoordinate = 
        AssociatedObject.ConvertViewportPointToGeoCoordinate(tapPosition);
    }

    protected override void OnCleanup()
    {
      AssociatedObject.Tap -= AssociatedObjectTap;
    }

 // GeoCoordinate TappedCoordinate dependency property omitted

   }
}&lt;/pre&gt;
&lt;p&gt;This behavior is implemented as a &lt;a href="http://dotnetbyexample.blogspot.com/2011/11/safe-event-detachment-base-class-for.html"&gt;SafeBehavior&lt;/a&gt; child class, to prevent memory leaks. It’s actually pretty simple – it traps the ‘Tap’ event, determines the location, converts it to a GeoCoordinate and puts it into the TappedCoordinate Dependency Property. Which, in turn, can be bound to the view model. The designer can simply drag this behavior on top of the map and set up the data binding. Don’t you love Blend? XAML take 2:&lt;/p&gt;&lt;pre&gt;&amp;lt;Grid x:Name="ContentPanel" Grid.Row="1" 
   Margin="12,0,12,0"&amp;gt;
  &amp;lt;maps:Map&amp;gt;
    &amp;lt;i:Interaction.Behaviors&amp;gt;
      &lt;font color="#ff0000"&gt;&lt;em&gt;&amp;lt;Behaviors:TapToCoordinateBehavior 
          TappedCoordinate="{Binding TapCoordinate, Mode=TwoWay}"/&amp;gt;
    &amp;lt;/i:Interaction.Behaviors&amp;gt;&lt;/em&gt;&lt;/font&gt;
  &amp;lt;/maps:Map&amp;gt;
  &amp;lt;Grid Height="58" VerticalAlignment="Top" Background="#7F000000"&amp;gt;
    &amp;lt;phone:LongListSelector ItemsSource="{Binding Addresses}" 
           HorizontalContentAlignment="Left" Margin="12,0"/&amp;gt;
  &amp;lt;/Grid&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;And that’s all there is to it. Reverse geocoding is Windows Phone 8 is insanely easy.&lt;/p&gt;
&lt;p&gt;Full source code, as usual, &lt;a href="http://www.schaikweb.net/dotnetbyexample/TapReverseGeocode.zip" target="_blank"&gt;can be downloaded here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/e7pUVJujwX0" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-03-13T16:07:17.233+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">4</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/03/simple-reverse-geocoding-with-windows.html</feedburner:origLink></item><item><title>Surface RT versus Surface Pro versus the competition for REAL dummies</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/VeSfS5PGb8E/surface-rt-versus-surface-pro-versus.html</link><category>rant</category><category>Off-topic</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Fri, 08 Mar 2013 07:39:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-8528460898873011684</guid><description>&lt;p&gt;About every pundit who is somewhat interested in Microsoft either by love or abject hate has written about this already – and still I am going to do my take. Why? Because I am one the few people on this planet who actually was crazy enough to purchase both a Surface RT &lt;em&gt;and&lt;/em&gt; a Surface Pro and therefore am entitled to my rant – and because I still get comments like “I think Surface Pro is too expensive for a tablet and has too little battery life for it”, which indicates people still completely don’t get it. With ‘tablet’ almost invariantly people mean “iPad”, by the way.&lt;/p&gt; &lt;p&gt;The very short version of this post is this ‘infographic’&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/pro2.png"&gt;&lt;img title="pro2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="pro2" src="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/pro2_thumb.png" width="287" height="145"&gt;&lt;/a&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/RT2.png"&gt;&lt;img title="RT2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="RT2" src="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/RT2_thumb.png" width="303" height="148"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;I used a mathematical symbol &lt;font size="3"&gt;≈ &lt;/font&gt;which means ‘is equivalent to’. That is something entirely different than “equals to”. Very important distinction. Keep that in mind. I will use a lot of ‘equivalents’ in this &lt;strike&gt;blog post&lt;/strike&gt; rant.&lt;/p&gt; &lt;p&gt;When you think of a Surface RT – think of something that moves in the same space as an iPad. Long battery life, relatively cheap (don’t get me started on Apple pricing), light, ideal for use on your lap or in your hand, good content consumption device. Plus some extras. But let’s not confuse the picture alr&lt;a href="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/image_thumb.png" width="183" height="122"&gt;&lt;/a&gt;eady.&lt;/p&gt; &lt;p&gt;When you think of a Surface Pro – think of an &lt;strong&gt;Ultrabook&lt;/strong&gt;. Yes, a &lt;em&gt;real computer&lt;/em&gt;. A real powerhouse too, ultra portable, and it runs the full Monty – I mean Windows 8 - but that comes at a price. It’s heavier, more expensive, burns more battery, and it gets hotter too. &lt;em&gt;Of&lt;/em&gt; &lt;em&gt;course it does&lt;/em&gt;. Look, it’s like saying “My wife has this cute Japanese car that does over 50 miles to the gallon when she’s doing 70 on the interstate but this other car burns much more fuel and generates a lot of exhaust” and then the car &lt;em&gt;you&lt;/em&gt; use…&lt;br&gt;&lt;br&gt;…is the car equivalent of something like this:&lt;a href="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 9px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="left" src="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/image_thumb_3.png" width="244" height="164"&gt;&lt;/a&gt;&lt;br&gt;Dude, I have some bad news for you. If there’s indeed the equivalent of an F22 Raptor sitting in your driveway when you just want to do some cruising, you might have paid some more attention to the brochure or might have asked some more questions at the dealer clerk before getting out the ole’ VISA card. This machine can carry more and heavier load than your wife’s car – and it can take it there very much faster. This machine is made for serious business. As is Surface Pro. Only with less pyrotechnics.&lt;/p&gt; &lt;p&gt;Now I will admit Microsoft has made life a little bit more complicated than my simple images and broad statements do justice. That’s because of a very a simple reason: the current state of affairs in electronics, as well as the radical design approach the Surface hardware engineering team took, made it possible that under the “Surface” flag now reside two very similar looking – but very dissimilar devices. It’s like the F22 and your wife’s Japanese car nearly look the same, have the same controls,&lt;em&gt; and even share accessories&lt;/em&gt; – but one will be a very good car, the other will take off at supersonic speed and be halfway Some Place Where Bad People Live (and – admittedly – a place where those Bad People won’t probably be for very much longer) before your wife has even made it to the &lt;em&gt;onramp&lt;/em&gt; of the interstate. Incidently, your wife may be in for a hell of surprise when one day she just wants to take the kids to school and takes the wrong key set ;-).&lt;/p&gt; &lt;p&gt;The funny thing is – radical as it’s design may be, Surface Pro is ‘just a PC’. As I showed in the ‘infographic’ above, it’s actually ‘just an Ultrabook’, in the same way an F22 is ‘just a jet airplane’. Surface Pro is the &lt;em&gt;n&lt;/em&gt;th generation descendant of all the PC’s in the world, and it’s odd that it took a &lt;em&gt;software company&lt;/em&gt; to let it see the light. Yet, the smaller, cheaper Surface RT is actually a much more remarkable and innovative design – it runs on total different hardware, that has an extremely long battery life, but still it runs Windows 8. Like I said, RT is more like a tablet. But, to make things more complicated, in a smart move to make their ‘tablet’ offering more attractive and not just another me-too, Microsoft have made it possible to attach a keyboard to Surface RT &lt;em&gt;and ships you a fully licensed Home version of Office&lt;/em&gt;. You get the crown ‘desktop jewels’ for free. Office in a very portable box. So in stead of only a consumption device, Surface RT is also a &lt;em&gt;content creation &lt;/em&gt;device. You can make Word documents, Excel sheets, PowerPoint presentations just like on any other PC. Using a traditional desktop program. You can even attach a mouse to it using it’s USB port. So your tablet can act like a PC to an extent. And here my infographic breaks down, and my F22 versus the wife’s car analogy as well. It’s like your wife’s car has this extra set of controls that can be used to fly short distances at limited height as well - wouldn’t she want have &lt;em&gt;that &lt;/em&gt;to overcome traffic jams and red lights ;). &lt;/p&gt; &lt;p&gt;So a more accurate way to position RT next to the &lt;em&gt;competition&lt;/em&gt; is like this:&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/RT3.png"&gt;&lt;img title="RT3" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="RT3" src="http://www.schaikweb.net/dotnetbyexample/7207b1802ad0_1206D/RT3_thumb.png" width="657" height="151"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;There is this other funny side effect too – because Surface RT runs on different hardware, the ‘foundation’ of it’s Windows needed to be changed too. You can hardly see that on the outside, but it has profound effects, one of them being that Windows RT – the Windows version that runs on Surface RT - is completely impervious to viruses. It’s like trying infect a fish with the human common cold – DNA does not match, the organs that are needed for infection are simply not there.&lt;/p&gt; &lt;p&gt;So it comes down to this:&lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;div align="justify"&gt;Surface Pro is a PC – it may look like a tablet and it can be used as a tablet, but it’s not its primary intended use. It’s a bit heavy for that and has this other characteristics that doesn’t make it the ideal tablet. Just like an F22 can be used on the highway – but it’s better in the air. You are doing development? Heavy gaming? Heavy duty photo or movie editing? This is the machine for you.&lt;/div&gt; &lt;li&gt; &lt;div&gt;Surface RT is primary a tablet but can also be used for some PC (Office) tasks that used to require a full PC. It’s like a car that can fly a little, but it cannot carry deadly loads with it. You are doing office, mail and some content/web browsing, casual games, maybe a bit of movie watching? A lot of it on the go, removed from any outlet?&amp;nbsp; Try this one.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;And of course, you can also try any other kind of device, running either Windows RT or Windows Pro (i.e. being equivalent to Surface RT and Surface Pro) to find out what suits your need. I give you only one golden rule – &lt;em&gt;whatever &lt;/em&gt;you buy, Surface or no Surface, RT of Pro – &lt;em&gt;make sure it has a touch screen. &lt;/em&gt;With touch Windows 8 &lt;em&gt;really&lt;/em&gt; shines.&lt;/p&gt; &lt;p&gt;PS: In case anyone wonders whether or not I am happy with my choice for Surface Pro as a portable development machine – let me just quote my fellow MVP Rob Miles on that one: “HELL YEAH!”&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/VeSfS5PGb8E" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-03-12T21:28:15.970+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/03/surface-rt-versus-surface-pro-versus.html</feedburner:origLink></item><item><title>Publishing games in the Brazilian Windows Phone store</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/jZNfP-dyIFk/publishing-games-in-brazilian-windows.html</link><category>Windows Phone 7</category><category>Windows Phone 8</category><category>Marketplace</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Sat, 02 Mar 2013 09:03:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-638353780436127204</guid><description>&lt;p&gt;Brazil, a strong developing economy, is the largest country is South America, and has the biggest population of South America as well. From a game developer’s standpoint, it’s unfortunately also one of the ‘restricted’ countries. In short, this means you cannot submit a game – any game - to the Brazilian &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; store without it being rated first. Since most developers outside of Brazil think this is a complicated and expensive procedure, and don’t speak Portuguese anyway – they tend to uncheck the Brazilian store and thereby leaving the Brazilians stranded, and denying themselves the opportunity to branch out in South America.&lt;/p&gt; &lt;p&gt;Now this is no longer necessary. A Brazilian guy named &lt;a href="https://twitter.com/GuilhermeManso" target="_blank"&gt;Guilherme S. Manso&lt;/a&gt; contacted me on twitter about a month ago claiming he made a write-up describing how to get your game rated for the Brazilian store. This got me about half-way, and the rest was explained to me in a Skype session by my fellow Phone Development MVP &lt;a href="http://www.twitter.com/RodoCarmo" target="_blank"&gt;Rodolpho Marques Do Carmo&lt;/a&gt;. With Guilherme’s permission I reworked both explanations to one blog post, making it easy for every game developer to enter the Brazilian store. And the procedure is free, too.&lt;/p&gt; &lt;p&gt;&lt;font size="2"&gt;&lt;font color="#333333" size="4"&gt;If the game already has an ESRB or PEGI game rating&lt;/font&gt; &lt;br&gt;&lt;/font&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="right" src="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_thumb.png" width="365" height="228"&gt;&lt;/a&gt;Recently, the government of Brazil started accepting the indicative international PEGI and ESRB ratings as a prerequisite for a “national auto rating”. That is, if a game has been rated by any of these institutions, all you need to do is to select one of the age groups from the DJCTQ (the Brazilian government rating) and attach the document that proves that the game has the PEGI or ESRB rating when you submit the game in the Windows Phone Development center. You must choose an age range that matches as closely as possible to the age received by indicative classification PEGI or ESRB. L is for all ages, the others show the age groups – 10 years, 12 and so on. If you already have a rating like this you probably know all about rating and probably don’t need this blog post anyway. I did not follow this track – my game had no rating at all.  &lt;p&gt;&lt;font color="#333333" size="4"&gt;If you don’t have any rating yet and want a Brazilian specific rating &lt;br&gt;&lt;/font&gt;First of all, you will need &lt;a href="http://www.schaikweb.net/dotnetbyexample/brazil/gameratingform.doc" target="_blank"&gt;this document&lt;/a&gt;. It’s mostly English so it should be intelligible for almost everyone able to read this blog post ;-). It’s a Word document, and it mostly contains check boxes. I ticked check boxes by right-clicking them, selecting “Properties” and then clicking “Selected” under “default value”. You have to fill in some other stuff and then you have to hand-sign it. It’s rather straightforward. You can then print the result, sign it and scan it, or – as I did - sign it with the a pen on a tablet and save the result as PDF. The word document as I used it – minus my signature – &lt;a href="http://www.schaikweb.net/dotnetbyexample/brazil/Catchembirds_ratingrequest.doc" target="_blank"&gt;can be seen here&lt;/a&gt; and used as an example.  &lt;p&gt;Second, you will need to write a synopsis of the game – and provide game itself. I did this the easy way and combined these points: I made another Word document that described the game, provided a global store link to the game, a link to the game in the USA store, and I made a video of the game play that I made available for download. &lt;a href="http://www.schaikweb.net/dotnetbyexample/brazil/Catchembirds_synopsis.docx" target="_blank"&gt;The document I used can be found here&lt;/a&gt;. They have a lot of games to process, so make the work of the raters as easy as possible. Another tip: make sure there is a trial version of the game available. If the game needs to be bought first, it will take much longer to get certified.  &lt;p&gt;Third – optionally – you will need to provide a bill of rights for the game. This is only necessary when the Rating Requester Name is different from the Publisher Name (or when it’s not clear that it comes from the same producer). It is a simple statement signed by hand as well, saying that you are the copyright owner of the game or that the holder is aware that you are asking for the classification. Since that did not apply to me, I have no example of that.&lt;/p&gt; &lt;p&gt;&lt;font size="2"&gt;&lt;font size="4"&gt;E-mailing the rating request&lt;/font&gt;&lt;br&gt;&lt;/font&gt;You will need to e-mail the rating request document (the thing with all the checkboxes), the synopsis and optionally the bill of rights to &lt;a href="mailto:classificacaoindicativa@mj.gov.br"&gt;&lt;strong&gt;&lt;em&gt;classificacaoindicativa@mj.gov.br&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;.&lt;br&gt;The title of the mail needs to be: "&lt;i&gt;Jogo para Classificação - &amp;lt;your game name&amp;gt;&lt;/i&gt;" (this is the only part that needs to be Portuguese). &lt;br&gt;I simply e-mailed:&lt;br&gt;"&lt;em&gt;Dear Sir, Madam,&lt;br&gt;I hereby request certification of my game Catch’em birds for release in Brazil according to the attached documentation.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;Highest regards&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;Joost van Schaik&lt;br&gt;Amersfoort&lt;br&gt;The Netherlands&lt;/em&gt;”&lt;/p&gt; &lt;p&gt;&lt;font size="2"&gt;&lt;font size="4"&gt;Obtaining&lt;/font&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image1.png"&gt;&lt;font size="4"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 9px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" align="left" src="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image1_thumb.png" width="200" height="133"&gt;&lt;/font&gt;&lt;/a&gt;&lt;font size="4"&gt; the game certificate&lt;/font&gt;&lt;br&gt;&lt;/font&gt;Here things get a little odd: certification will take about ten days, but you will not be informed about the progress or the result. You will need to go &lt;a href="http://pesquisa.in.gov.br/imprensa/core/start.action" target="_blank"&gt;to this page&lt;/a&gt; regularly to check if your app has passed certification. It shows itself like showed to the left. You simply enter the name or part of the name of your game, click ‘consulta’, and with any luck it will show a result. There is a catch: it will only displayed on this page for a pretty short time. If you miss it, you will get this page, which basically means ‘not found’&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_3.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_thumb_3.png" width="451" height="179"&gt;&lt;/a&gt;&lt;br&gt;But, if you hit the grey bar at the left bottom that says “&lt;strong&gt;Abrir/Fechar Pesquisa&lt;/strong&gt;” you get an &lt;em&gt;extended&lt;/em&gt; search form that allows you to enter dates and stuff:&lt;a href="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_4.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_thumb_4.png" width="493" height="272"&gt;&lt;/a&gt;&lt;br&gt;So here I ask the ‘find everything (todos) that contains the word ‘birds’ and was approved between January 1st and February 28th 2013 and &lt;em&gt;now &lt;/em&gt;if you hit ‘consulta’…&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_5.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://www.schaikweb.net/dotnetbyexample/1166b77d2b24_9701/image_thumb_5.png" width="638" height="313"&gt;&lt;/a&gt;&lt;br&gt;Bingo! Click the blue header (in my case “Diário Oficial da União - Seção 1 - Edição nr 38 de 26/02/2013 Pag. 27”) and this will download a file called “&lt;a href="http://www.schaikweb.net/dotnetbyexample/brazil/INPDFViewer.pdf" target="_blank"&gt;INPDFViewer.pdf&lt;/a&gt;”. That’s basically a page of a Brazilian law book saying your game is permitted for the given classification. There’s a bunch of games on that page, but near the end of the page it says:&lt;br&gt;&lt;font size="1"&gt;Título: CATCH`EM BIRDS (Holanda - 2012) &lt;br&gt;Titular dos Direitos Autorais: JOOST VAN SCHAIK&lt;br&gt;Distribuidor(es): JOOST VAN SCHAIK (MICROSOFT`S WINDOWS PHONE STORE)&lt;br&gt;Classificação Pretendida: Livre&lt;br&gt;Categoria: Ação &lt;br&gt;Plataforma: Telefone Celular/Smartphone &lt;br&gt;Tipo de Análise: Sinopse e Vídeo &lt;br&gt;Classificação: Livre &lt;br&gt;Processo: 08017.004064/2013-35 &lt;br&gt;Requerente: JOOST VAN SCHAIK&lt;/font&gt;&lt;/p&gt; &lt;p&gt;And that’s it. Now you can tick the ‘Brazil’ checkbox in the Windows Phone dev center, select a category according to your classification, and upload the INPDFViewer.pdf as proof. I have tried this procedure to the end, &lt;a href="http://www.windowsphone.com/pt-br/store/app/catch-em-birds/48fd8097-f07e-e011-986b-78e7d1fa76f8" target="_blank"&gt;and my game is now in the Brazilian store&lt;/a&gt;. And so, my friends, can be yours. The road to Brazil is now wide open for game developers, thanks to Guilherme and Rodolpho, so &lt;a href="http://www.youtube.com/watch?v=VbXNmIvWa1c" target="_blank"&gt;let’s go to Brazil&lt;/a&gt;!&lt;/p&gt; &lt;p&gt;BTW, I haven’t tried this but I assume publishing Windows 8 Store apps can be done following the same procedure.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/jZNfP-dyIFk" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-03-08T10:23:33.696+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/03/publishing-games-in-brazilian-windows.html</feedburner:origLink></item><item><title>A KnockOut.js binding helper for a JQuery Mobile Slider</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/Fv-wFR2zeik/a-knockoutjs-binding-helper-for-jquery.html</link><category>Javascript</category><category>jquery</category><category>knockout</category><category>html</category><category>jquery mobile</category><category>DataBinding</category><category>dat</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 06 Feb 2013 23:59:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-3466209564189349924</guid><description>&lt;p&gt;For those who have missed it – besides all the things I do on &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; and &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt; I actually have a job, and in that job I am currently doing a lot of HTML5/Javascript development – now focusing on a Single Page App using (amongst others) &lt;a href="http://knockoutjs.com/" target="_blank"&gt;Knockout.js&lt;/a&gt; and &lt;a href="http://jquerymobile.com/" target="_blank"&gt;JQuery Mobile&lt;/a&gt;. For those who don’t know: Knockout is a great tool that makes data binding possible in a web environment, making the way I think about making applications – using MVVM – possible in an HTML/Javascript&amp;nbsp; environment as well. If you use &lt;a href="http://amplifyjs.com/" target="_blank"&gt;Amplify.js&lt;/a&gt; you even have messaging. Oh goody!&lt;/p&gt; &lt;p&gt;Now don’t get me wrong – I am not forsaking XAML and C# (like some others *ahem*), but I tried to find a way to bind a JQuery Mobile slider to Knockout.js. That’s not supported out of the box, so you have to make or find a customer ‘binding helper’ and I found &lt;em&gt;so&lt;/em&gt; much examples that were plainly wrong or incomplete that I had to blog mine, which is complete &lt;em&gt;and actually works:&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;ko.bindingHandlers.jQuerySliderValue = {
  // Initialize slider
  init: function (element, valueAccessor)
  {
    var val = valueAccessor()();
    var el = $(element);
    el.slider({ value: val });

    el.bind("change", function (event, ui)
    {
      var value = valueAccessor()();
      if (value !== el.val)
      {
        valueAccessor()(&lt;font color="#ff0000"&gt;parseInt(el.val())&lt;/font&gt;);
      }
    });
  },

  //handle the model value changing
  update: function (element, valueAccessor)
  {
    var el = $(element);

    var value = ko.utils.unwrapObservable(valueAccessor()());
    if (value !== el.val())
    {
      el.val(value);
      el.slider("refresh");
    }
  }
};&lt;/pre&gt;
&lt;p&gt;You can use this in HTML like this:&lt;/p&gt;&lt;pre&gt;&amp;lt;input type="range" name="slider-1" id="slider-1" 
  min="0" max="5"
  data-bind="jQuerySliderValue: locationDataIndex" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Now I haven’t all conjured this up out of thin air, there are plenty of samples on, for instance, stackoverflow. Actually my most important addition to the samples out there is the red parseInt piece. All samples seem to fail to take into account that a) data binding can happen both way and b) a Jquery mobile slider &lt;em&gt;apparently returns a string value&lt;/em&gt;.&amp;nbsp; This leads to some interesting results if you try to manipulate the return value in your javascript view model by adding 1 to it. What you think happens is:&lt;/p&gt;
&lt;p&gt; 0+1=1 , 1+1=2 etc. &lt;/p&gt;
&lt;p&gt;But like I said, used this way a range return a string, so you get &lt;/p&gt;
&lt;p&gt;“0” + 1 = “01” , “01” +1 = “011”. &lt;/p&gt;
&lt;p&gt;And an interesting out of range error. The really gotcha is that it seems to go well the first time, the error only occurs the second time. It seems to make no sense at all. Sure, I could have used input type="number" data-type="range", maybe that would have helped as well, but that ain’t in the samples either. Either way, this fixes it for all cases.&lt;/p&gt;
&lt;p&gt;So, this is a very old type of blog post, not so much written from the desire to teach and share but borne from sheer annoyance about the incompleteness and incorrectness of what’s out there – the feeling that actually fuelled the creation of this blog ;-)&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/Fv-wFR2zeik" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-02-07T08:59:59.089+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/02/a-knockoutjs-binding-helper-for-jquery.html</feedburner:origLink></item><item><title>An MVVM-friendly ‘tap-to-connect’ NFC socket network helper for Windows Phone 8</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/6BLdWEH7Gus/am-mvvm-friendly-tap-to-connect-nfc.html</link><category>MVVM</category><category>wpnl</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>Bluetooth</category><category>NFC</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Mon, 14 Jan 2013 12:25:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-5070521052577576591</guid><description>&lt;p&gt;For my &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; 8 game “&lt;a title="Pull the Rope" href="http://windowsphone.com/s?appid=4aaf1cc1-4393-4d81-98b7-d438d7e83fac&amp;amp;amp;ocid=aff-n-we-loc--ITPRO40939&amp;amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Pull the Rope&lt;/a&gt;” I wrote a utility class to make pairing phones and obtaining a&amp;nbsp; two-way communication channel a little bit easier. I already dabbled into this while developing the game, but now I feel it’s time to show a more comprehensive solution.&lt;/p&gt; &lt;p&gt;I re-use the NavigationEventArgsExtensions and the NavigationMessage from my previous article “&lt;a href="http://dotnetbyexample.blogspot.be/2012/12/handling-windows-phone-8-nfc-startup.html" target="_blank"&gt;Handling Windows Phone 8 NFC startup events using the MVVMLight&lt;/a&gt;” without describing them further – I suggest you read this article as a preface to this one if you haven’t done so before. The utility class I describe in this article handles the pairing via tap-to-connect and provides – when that’s done – a method for sending a message and an event for receiving a message. I have peppered the code with debug statements, so can you nicely see in your output windows what’s exactly happening inside of the class when you are debugging on the phone.&lt;/p&gt; &lt;p&gt;Messages are sent and received as strings, therefore the message argument class is not very complex either:&lt;/p&gt;&lt;pre&gt;using System;

namespace Wp7nl.Devices
{
  public class ReceivedMessageEventArgs : EventArgs
  {
    public string Message { get; set; }
  }
}&lt;/pre&gt;The start of the TtcSocketHelper (‘Tap-To-Connect’) class, as I have called it, is as follows: &lt;pre&gt;using System;
using System.Diagnostics;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Messaging;
using Windows.Foundation;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;

namespace Wp7nl.Devices
{
  public class TtcSocketHelper
  {
    public TtcSocketHelper()
    {
      Messenger.Default.Register&amp;lt;NavigationMessage&amp;gt;(this, 
        ProcessNavigationMessage);
    }

    public virtual void Start()
    {
      PeerFinder.TriggeredConnectionStateChanged += 
         PeerFinderTriggeredConnectionStateChanged;

      PeerFinder.AllowBluetooth = true;
      PeerFinder.Start();
    }

    private void ProcessNavigationMessage(NavigationMessage message)
    {
      Debug.WriteLine("TtsHelper.ProcessNavigationMessage " + 
        message.NavigationEvent.Uri);

      if (message.IsStartedByNfcRequest)
      {
        Start();
      }
    }
  }
}&lt;/pre&gt;The constructor subscribes this helper class to a message that will need to be fired when the application navigates to it's main page. If it detects the app is started by an NfcRequest - i.e. a tap-to-connect, the PeerFinder is immediately started to allow for the further build-up of the connection. I already described this technique in &lt;a href="http://dotnetbyexample.blogspot.be/2012/12/handling-windows-phone-8-nfc-startup.html" target="_blank"&gt;the article I already mentioned.&lt;/a&gt; The method Start can also be called by an the application, for instance the press of a “connect” button. Note that I only allow Bluetooth connections – this is because this class comes from my game, which does not need the highest possible speed, but the &lt;em&gt;lowest possible latency&lt;/em&gt;. Ironically Wi-Fi seems to have a little more latency than Bluetooth. 
&lt;p&gt;The next part is the handling of the connection process itself:&lt;/p&gt;&lt;pre&gt;private void PeerFinderTriggeredConnectionStateChanged(object sender, 
             TriggeredConnectionStateChangedEventArgs args)
{
  switch (args.State)
  {
    case TriggeredConnectState.Completed:
      FireConnectionStatusChanged(args);
      socket = args.Socket;
      StartListeningForMessages();
      PeerFinder.Stop();
      break;
    default:
      FireConnectionStatusChanged(args);
      break;
  }
}

private void FireConnectionStatusChanged(TriggeredConnectionStateChangedEventArgs args)
{
  Debug.WriteLine("TtsHelper: " + args);
  if (ConnectionStatusChanged != null)
  {
    ConnectionStatusChanged(this, args );
  }
}

public event TypedEventHandler&amp;lt;object, 
             TriggeredConnectionStateChangedEventArgs&amp;gt; ConnectionStatusChanged;

private StreamSocket socket;&lt;/pre&gt;
&lt;p&gt;This is kind of nicked from the &lt;a href="http://code.msdn.microsoft.com/wpapps/Bluetooth-app-to-app-sample-890f8303?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Bluetooth app to app sample at MSDN&lt;/a&gt;, although I made it a bit simpler: only on TriggeredConnectState.Completed I need to do something, i.e. obtain a socket. For the rest of the events, I just pass them to the outside world in case it’s interested.&lt;/p&gt;
&lt;p&gt;Next is the part that initiates and performs the actual listening for messages, once the socket is obtained:&lt;/p&gt;&lt;pre&gt;private async void StartListeningForMessages()
{
  if( socket != null )
  {
    if (!listening)
    {
      listening = true;
      while (listening)
      {
        var message = await GetMessage();
        if (listening)
        {
          if (message != null &amp;amp;&amp;amp; MessageReceived != null)
          {
            MessageReceived(this, 
               new ReceivedMessageEventArgs {Message = message});
          }
        }
      }
    }
  }
}

private async Task&amp;lt;string&amp;gt; GetMessage()
{
  try
  {
    if (dataReader == null) dataReader = new DataReader(socket.InputStream);
    await dataReader.LoadAsync(4);
    var messageLen = (uint)dataReader.ReadInt32();

    await dataReader.LoadAsync(messageLen);
    var message = dataReader.ReadString(messageLen);
    Debug.WriteLine("Message received: " + message);

    return message;
  }
  catch (Exception ex)
  {
    Debug.WriteLine("GetMessage: " + ex.Message);
  }
  return null;
}

public event TypedEventHandler&amp;lt;object, ReceivedMessageEventArgs&amp;gt; MessageReceived;

private DataReader dataReader;

private bool listening;
&lt;/pre&gt;
&lt;p&gt;The StartListeningForMessages basically enters an endless loop – endless that is, until the “listening” is set to “false” - waiting for GetMessage to return something. The GetMessage is almost 100% nicked from the &lt;a href="http://code.msdn.microsoft.com/wpapps/Bluetooth-app-to-app-sample-890f8303?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Bluetooth app to app sample at MSDN&lt;/a&gt;. the first four bytes are supposed to contain the message length, the rest is payload, hence the two read actions.&lt;/p&gt;
&lt;p&gt;Then of course we need a method to actually &lt;em&gt;send&lt;/em&gt; messages:&lt;/p&gt;&lt;pre&gt;private readonly object lockObject = new object();

public async void SendMessage(string message)
{
  Debug.WriteLine("Send message:" + message);
  if (socket != null)
  {
    try
    {
      lock (lockObject)
      {
        {
          if (dataWriter == null)
          {
            dataWriter = new DataWriter(socket.OutputStream);
          }

          dataWriter.WriteInt32(message.Length);
          dataWriter.StoreAsync();

          dataWriter.WriteString(message);
          dataWriter.StoreAsync();
        }
      }
    }
    catch (Exception ex)
    {
      Debug.WriteLine("SendMessage: " + ex.Message);
    }
  }
}
private readonly object lockObject = new object();

private DataWriter dataWriter;
&lt;/pre&gt;
&lt;p&gt;which comes almost directly from my earlier article “&lt;a href="http://dotnetbyexample.blogspot.be/2012/12/preventing-high-speed-socket.html"&gt;Preventing high speed socket communication on Windows Phone 8 going south when using async/await&lt;/a&gt;” &lt;/p&gt;
&lt;p&gt;And finally we have this brilliant method, which basically resets the TtcSocketHelper class back to its initial status.&lt;/p&gt;&lt;pre&gt;public void Reset()
{
  PeerFinder.Stop();
  if (dataReader != null)
  {
    try
    {
      listening = false;
      if (dataReader != null)
      {
        dataReader.Dispose();
        dataReader = null;
      }
      if (dataWriter != null)
      {
        dataWriter.Dispose();
        dataWriter = null;
      }
      if (socket != null)
      {
        socket.Dispose();
        socket = null;
      }
    }
    catch (Exception ex)
    {
    }
  }
}&lt;/pre&gt;
&lt;p&gt;To use this class:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Make sure you app does &lt;a href="http://dotnetbyexample.blogspot.be/2012/12/handling-windows-phone-8-nfc-startup.html" target="_blank"&gt;fire a NavigationMessage as described here&lt;/a&gt; 
&lt;li&gt;Make a new TtcSocketHelper. 
&lt;li&gt;Subscribe to its ConnectionStatusChanged event 
&lt;li&gt;Subscribe to its MessageReceived event 
&lt;li&gt;Call Start 
&lt;li&gt;Wait until a TriggeredConnectState.Completed comes by 
&lt;li&gt;Call SendMessage – and see them appear in the method subscribed to MessageReceived on the other phone.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Oh, and don’t forget to set ID_CAP_PROXIMITY in your WMAppManifest.Xaml.right?&lt;/p&gt;
&lt;p&gt;The source code – and a working demo of this component – can be found in the &lt;a href="http://www.schaikweb.net/dotnetbyexample/TtcDemo.zip" target="_blank"&gt;demo solution right here&lt;/a&gt;. It’s a very simple chat-application built upon TtcSocketHelper. Of course this is all &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt; based, and I start off with the basic viewmodel and its properties:&lt;/p&gt;&lt;pre&gt;using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Windows.Networking.Proximity;
using Wp7nl.Devices;

namespace TtcDemo.Viewmodels
{
  public class NfcConnectViewModel : ViewModelBase
  {
    private TtcSocketHelper ttcSocketHelper;

    public ObservableCollection&amp;lt;string&amp;gt; ConnectMessages { get; private set; }
    public ObservableCollection&amp;lt;string&amp;gt; ReceivedMessages { get; private set; }

    private bool canInitiateConnect;
    public bool CanInitiateConnect
    {
      get { return canInitiateConnect; }
      set
      {
        if (canInitiateConnect != value)
        {
          canInitiateConnect = value;
          RaisePropertyChanged(() =&amp;gt; CanInitiateConnect);
        }
      }
    }

    private bool isConnecting;
    public bool IsConnecting
    {
      get { return isConnecting; }
      set
      {
        if (isConnecting != value)
        {
          isConnecting = value;
          RaisePropertyChanged(() =&amp;gt; IsConnecting);
        }
      }
    }

    private bool canSend;
    public bool CanSend
    {
      get { return canSend; }
      set
      {
        if (canSend != value)
        {
          canSend = value;
          RaisePropertyChanged(() =&amp;gt; CanSend);
        }
      }
    }
    
    private string message;
    public string Message
    {
      get { return message; }
      set
      {
        if (message != value)
        {
          message = value;
          RaisePropertyChanged(() =&amp;gt; Message);
        }
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;We have a TtcSocketHelper itself, and two ObservableCollections of strings. ConnectMessages serves is to report the connection progress, and ReceivedMessages hold the messages received by your ‘opponent’ once the connection is established. Then we have three booleans, that basically turn on or off certain parts of the user interface depending on the state:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Initially, IsConnecting is true and CanSend is false. That should show a part of the user interface to show ConnectMessages. 
&lt;li&gt;If the app is started by the user, CanInitiateConnect is true as well, so the user can click on some “connect” button as well. If the apps is started by an NFC request, the process of creating a connection is initiated by someone else and the user should &lt;em&gt;not&lt;/em&gt; be able to press a “connect” button to prevent the whole process from being south. I my mind I call the instance of the app that has been started by the user “master”, the instance started by the NFC request “slave”. 
&lt;li&gt;If the connection has been successfully established, IsConnecting should become false and CanSend true, disabling the controls handling the connection setup, and enabling the controls doing the actual chatting stuff.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And yeah, I know, usually CanSend != IsConnecting so I could replace this with one boolean. But that makes the designer’s job harder, as I will show further on. &lt;/p&gt;
&lt;p&gt;Finally we have the Message property, which is where the message the user wants to send. We’ll come to that later. The viewmodel is initialized via a method “Init”, now called in the constructor:&lt;/p&gt;&lt;pre&gt;public NfcConnectViewModel()
{
  Init();
}

private void Init()
{
  Messenger.Default.Register&amp;lt;NavigationMessage&amp;gt;(this, ProcessNavigationMessage);

  if (ConnectMessages == null)
  {
    ConnectMessages = new ObservableCollection&amp;lt;string&amp;gt;();
  }

  if (ReceivedMessages == null)
  {
    ReceivedMessages = new ObservableCollection&amp;lt;string&amp;gt;();
  }

  if (!IsInDesignMode)
  {
    if (ttcSocketHelper == null)
    {
      ttcSocketHelper = new TtcSocketHelper();
      ttcSocketHelper.ConnectionStatusChanged += ConnectionStatusChanged;
      ttcSocketHelper.MessageReceived += TtsHelperMessageReceived;
    }
    else
    {
      CanSend = true;          
    }
  }
  IsConnecting = true;
}&lt;/pre&gt;
&lt;p&gt;It doesn’t really do that much – apart from initializing the ObservableCollections, creating an instance of TtcSocketHelper and subscribing to its events, and setting the initial status. There are two things to note here – one, in design mode both CanSend and IsConnecting are true so &lt;em&gt;all&lt;/em&gt; the parts of the GUI are enabled. This is to remain friends with the designer, who can now shut on or off both the connection part of the GUI &lt;em&gt;and&lt;/em&gt; the messaging part when he/she chooses &lt;em&gt;using Blend&lt;/em&gt;, making the design process a lot easier - in stead of having to muck around in your code – or worse, by coming to complain to you.&lt;/p&gt;
&lt;p&gt;The second thing to note is that this viewmodel &lt;em&gt;also&lt;/em&gt; subscribes to NavigationMessage (just as TtcSocketHelper itself) . This is because the viewmodel likes to know as well if it’s in a master or slave app:&lt;/p&gt;&lt;pre&gt;private void ProcessNavigationMessage(NavigationMessage message)
{
  CanInitiateConnect = !message.IsStartedByNfcRequest;
}&lt;/pre&gt;
&lt;p&gt;so it can enable or disable the connect button. The handling of the connection messages is done by ConnectionStatusChanged:&lt;/p&gt;&lt;pre&gt;private void ConnectionStatusChanged(object sender,
  TriggeredConnectionStateChangedEventArgs e)
{
  Deployment.Current.Dispatcher.BeginInvoke(() =&amp;gt;
    ConnectMessages.Add(GetMessageForStatus(e.State)));
    
  if (e.State == TriggeredConnectState.Completed)
  {
    Deployment.Current.Dispatcher.BeginInvoke(() =&amp;gt;
    {
      IsConnecting = false;
      CanSend = true;
    });
  }
}

private static string GetMessageForStatus(TriggeredConnectState state)
{
  switch (state)
  {
    case TriggeredConnectState.Listening:
      return "Listening....";

    case TriggeredConnectState.PeerFound:
      return "Opponent found";

    case TriggeredConnectState.Connecting:
      return "Opponent found";

    case TriggeredConnectState.Completed:
      return "Connection succesfull!";

    case TriggeredConnectState.Canceled:
      return "Connection canceled";

    default: //TriggeredConnectState.Failed:    
      return "Connection failed";
  }
}&lt;/pre&gt;
&lt;p&gt;That first adds a message to ConnectMessages using a little helper method GetMessageForStatus (I’d suggest loading this from a resource if you do this in a real app) . After that, if it detects a TriggeredConnectState.Completed message coming by, switches from connect mode to chat mode, so to speak. Since all these events are raised outside of the UI thread, say hello to your old friend &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(v=VS.95).aspx" target="_blank"&gt;Dispatcher&lt;/a&gt; to prevent cross-thread access exceptions. Oh, and then of course there’s the little matter of enabling the user actually starting the whole connection process:&lt;/p&gt;&lt;pre&gt;public ICommand StartCommmand
{
  get
  {
    return new RelayCommand(
        () =&amp;gt;
        {
          ConnectMessages.Add("Connect started...");
          CanSend = false;
          CanInitiateConnect = false;
          ttcSocketHelper.Start();
        });
  }
}&lt;/pre&gt;
&lt;p&gt;It adds a message to ConnectMessage (to show “see, I am really doing something!”), disables the connect button (as to prevent an annoying Windows Phone certification tester crashing your program) and then it starts the helper. All this is only needed to handle the build-up of the connection. All that actually handles the &lt;em&gt;chatting&lt;/em&gt; is merely this:&lt;/p&gt;&lt;pre&gt;public ICommand SendComand
{
  get
  {
    return new RelayCommand(
      () =&amp;gt;
      {
        ttcSocketHelper.SendMessage(Message);
        Message = string.Empty;
      }
   );
  }
}

private void TtsHelperMessageReceived(object sender,
                                      ReceivedMessageEventArgs e)
{
  Deployment.Current.Dispatcher.BeginInvoke(() =&amp;gt;
    ReceivedMessages.Add(e.Message));
}&lt;/pre&gt;
&lt;p&gt;As you can see it’s only a command that relays the message to the TtcSocketHelper and then clears the field, and a simple method listening for messages and adding received message contents to ReceivedMessages, once again with the aid of the Dispatcher.&lt;/p&gt;
&lt;p&gt;Since this article is already way longer than I planned, I limit myself to the part of the XAML that is actually interesting:&lt;/p&gt;&lt;pre style="font-size: 9pt"&gt;&amp;lt;!-- Connect panel--&amp;gt;
&lt;font color="#ff0000"&gt;&lt;u&gt;&amp;lt;&lt;/u&gt;&lt;u&gt;Grid x:Name="ConnectGrid" Margin="0,0,0,76" Grid.RowSpan="2"&lt;/u&gt;&lt;/font&gt;&lt;font color="#ff0000"&gt; 
   &lt;u&gt;Visibility="{Binding IsConnecting, Converter={StaticResource VisibilityConverter}}"&amp;gt;&lt;/u&gt;&lt;/font&gt;
  &amp;lt;Grid.RowDefinitions&amp;gt;
    &amp;lt;RowDefinition Height="425*"/&amp;gt;
    &amp;lt;RowDefinition Height="106*"/&amp;gt;
  &amp;lt;/Grid.RowDefinitions&amp;gt;
  &lt;u&gt;&lt;font color="#ff0000"&gt;&amp;lt;Button Content="Connect" HorizontalAlignment="Center" VerticalAlignment="Top"&lt;/font&gt;&lt;/u&gt;
     &lt;font color="#ff0000"&gt;&lt;u&gt;IsEnabled="{Binding CanInitiateConnect}" Command="{Binding StartCommmand}"&lt;/u&gt;&lt;/font&gt; 
     Grid.Row="1"/&amp;gt;
  &amp;lt;ListBox ItemsSource="{Binding ConnectMessages}" Background="#FF091630"/&amp;gt;
&amp;lt;/Grid&amp;gt;

&amp;lt;!-- Message panel--&amp;gt;
&lt;font color="#ff0000"&gt;&lt;u&gt;&amp;lt;Grid x:Name="MessageGrid"&lt;/u&gt;&lt;/font&gt; 
      &lt;u&gt;&lt;font color="#ff0000"&gt;Visibility="{Binding CanSend, Converter={StaticResource VisibilityConverter}}" &amp;gt;&lt;/font&gt;&lt;/u&gt;
  &amp;lt;Grid.RowDefinitions&amp;gt;
    &amp;lt;RowDefinition Height="110*"/&amp;gt;
    &amp;lt;RowDefinition Height="100*"/&amp;gt;
    &amp;lt;RowDefinition Height="412*"/&amp;gt;
  &amp;lt;/Grid.RowDefinitions&amp;gt;
  &amp;lt;TextBox Height="72" Margin="0,10,0,0" TextWrapping="Wrap" VerticalAlignment="Center" 
    Text="{Binding Message, Mode=TwoWay}"/&amp;gt;
  &amp;lt;Button Content="send message" Grid.Row="1" Command="{Binding SendComand, Mode=OneWay}"/&amp;gt;
  &amp;lt;ListBox Grid.Row="2" ItemsSource="{Binding ReceivedMessages}" 
           Background="#FF091630" Margin="12,0"/&amp;gt;
&amp;lt;/Grid&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://lh4.ggpht.com/-vAmoGGlav9M/UPasOq1jolI/AAAAAAAAKDQ/PvMejiVgwg0/s1600-h/wp_ss_20130116_0002%25255B1%25255D%25255B5%25255D.png"&gt;&lt;img title="wp_ss_20130116_0002[1]" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="wp_ss_20130116_0002[1]" align="right" src="http://lh4.ggpht.com/-NrlxRNIHvtg/UPasPqi3L7I/AAAAAAAAKDU/bnA-7NGwG6s/wp_ss_20130116_0002%25255B1%25255D_thumb%25255B1%25255D.png?imgmax=800" width="148" height="244"&gt;&lt;/a&gt;&lt;a href="http://lh5.ggpht.com/-j4YhdP7me38/UPasQq7IhyI/AAAAAAAAKDc/dh8LaFCyAKM/s1600-h/wp_ss_20130116_0001%25255B1%25255D%25255B2%25255D.png"&gt;&lt;img title="wp_ss_20130116_0001[1]" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="wp_ss_20130116_0001[1]" align="right" src="http://lh6.ggpht.com/-XVzd0aSZ45c/UPasRd4mKwI/AAAAAAAAKDo/lpS128x0yy0/wp_ss_20130116_0001%25255B1%25255D_thumb.png?imgmax=800" width="148" height="244"&gt;&lt;/a&gt;You can see ConnectGrid whose visibility is controlled by IsConnecting, and a MessageGrid whose visibility is controlled by CanSend. Then there is the Connect button that is enabled or disabled by CanInitiateConnect. The two faces of the application look like as showed on the right. On the left image you see the app just after connect has been initiated by the ‘master’ the right shows the app after having received a message from the first phone and the user of the second phone responding.&lt;/p&gt;
&lt;p&gt;I will add the classes described in this article to the wp8-specific version of&amp;nbsp; my &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl CodePlex library&lt;/a&gt; soon. In the mean time, you can find them in the Wp7nl.Contrib project of &lt;a href="http://www.schaikweb.net/dotnetbyexample/TtcDemo.zip" target="_blank"&gt;the demo solution&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For the record, there’s also a ResetCommand in the viewmodel that makes it possible to reset the whole connection process, but that’s currently not bound to a button of sorts. I leave that as exercise for the reader ;-)&lt;/p&gt;
&lt;p&gt;A final word: I am aware of the fact that I could also have used the Visual State Manager to turn pieces of the GUI on and off (and animate that, too) but I did not want to add even more complexity to this article.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/6BLdWEH7Gus" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-01-16T19:47:43.935+01:00</atom:updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-NrlxRNIHvtg/UPasPqi3L7I/AAAAAAAAKDU/bnA-7NGwG6s/s72-c/wp_ss_20130116_0002%25255B1%25255D_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/01/am-mvvm-friendly-tap-to-connect-nfc.html</feedburner:origLink></item><item><title>Playing sounds on Windows Phone using the MVVMLight Messenger</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/IQbSGot65eE/playing-sounds-on-windows-phone-using.html</link><category>MVVM</category><category>behavior</category><category>wpnl</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Sun, 13 Jan 2013 05:01:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-6946200399595947555</guid><description>&lt;p&gt;In my never-ending quest to preach the gospel of MVVM in general and &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt; in particular as the way to make a structured &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; application I show a little part of my my newest Windows Phone app, “&lt;a href="http://windowsphone.com/s?appid=4aaf1cc1-4393-4d81-98b7-d438d7e83fac&amp;amp;amp;ocid=aff-n-we-loc--ITPRO40939&amp;amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Pull the Rope&lt;/a&gt;”. It’s a basically a rope pulling contest played on two phones. I think it’s quite fun to play but I am pretty sure it’s even more hilarious to watch &lt;em&gt;other&lt;/em&gt; people play it, swiping like maniacs on their phones.&lt;/p&gt; &lt;p&gt;The first version did not even have sounds – I decided to go the “ship early ship often” route this time – so some days ago I submitted a version that does some supportive sound. Of course my game is MVVMLight based and for adding the game sound I pulled a tried-and-tested (at least, by me) out of the hat – the Messenger-Behavior combo.Using the Messenger requires of course a message, so I started off with that:&lt;/p&gt;&lt;pre&gt;namespace Wp7nl.Audio
{
  public class PlaySoundEffectMessage
  {
    public PlaySoundEffectMessage(string soundName, bool start = true)
    {
      SoundName = soundName;
      Start = start;
    }

    public string SoundName { get; private set; }

    public bool Start { get; private set; }
  }
}&lt;/pre&gt;
&lt;p&gt;So this message has only two options – an identifier for the sound that must be started, and a boolean that indicates whether the sound should be started (default) or stopped (this for sounds that are played in a loop).&lt;/p&gt;
&lt;p&gt;Then the behavior itself. As usual, I start off with a couple of Dependency Properties, to support data binding:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;SoundFileLocation (string) – the location of the sound file to play 
&lt;li&gt;SoundName (string) – the sound identifier; if PlaySoundEffectMessage.SoundName has the same value a this property, the behavior will take action. 
&lt;li&gt;Repeat (bool) – indicates if the sound should be played in a loop or not.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;I hope you will forgive me for not including the Dependency Properties’ code in the this article as it is pretty much run of the mill and takes a lot of space. &lt;/p&gt;
&lt;p&gt;The core of the behavior itself is actually pretty simple. It’s meant to be used in conjunction with a MediaElement. First, the setup. I created this as a &lt;a href="http://dotnetbyexample.blogspot.nl/2011/11/safe-event-detachment-base-class-for.html" target="_blank"&gt;SafeBehavior&lt;/a&gt; to make setup and teardown a little less complex:&lt;/p&gt;&lt;pre&gt;using System;
using System.Windows;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Messaging;
using Wp7nl.Behaviors;

namespace Wp7nl.Audio
{
  public class PlaySoundEffectBehavior : SafeBehavior&amp;lt;MediaElement&amp;gt;
  {
    protected override void OnSetup()
    {
      Messenger.Default.Register&amp;lt;PlaySoundEffectMessage&amp;gt;(
        this, DoPlaySoundFile);
      AssociatedObject.IsHitTestVisible = false;
      AssociatedObject.AutoPlay = false;
      var soundUri = new Uri(SoundFileLocation, UriKind.Relative);
      AssociatedObject.Source = soundUri;
      AssociatedObject.Position = TimeSpan.FromSeconds(0);
      SetRepeat(Repeat);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;So basically this behavior subscribes to the message type we just defined. Then it goes on initializing the MediaElement – disabling hit test and autoplay, actually setting the sound file URI, initializing it to the beginning and initializing repeat (or not). &lt;/p&gt;
&lt;p&gt;The method DoPlaySoundFile, which kinda does all the work, isn’t quite rocket science either:&lt;/p&gt;&lt;pre&gt;private void DoPlaySoundFile(PlaySoundEffectMessage message)
{
  if (SoundName == message.SoundName)
  {
    if (message.Start)
    {
      AssociatedObject.Position = TimeSpan.FromSeconds(0);
      AssociatedObject.Play();
    }
    else
    {
      AssociatedObject.Stop();
    }
  }
}&lt;/pre&gt;
&lt;p&gt;If a message is incepted with the same sound name as has been set to the behavior in the XAML, then either start or stop the sound. &lt;/p&gt;
&lt;p&gt;The rest of the behavior is basically some odds and ends:&lt;/p&gt;&lt;pre&gt;private void SetRepeat(bool repeat)
{
  if (AssociatedObject != null)
  {
    if (repeat)
    {
      AssociatedObject.MediaEnded += AssociatedObjectMediaEnded;
    }
    else
    {
      AssociatedObject.MediaEnded -= AssociatedObjectMediaEnded;
    }
  }
}

private void AssociatedObjectMediaEnded(object sender, RoutedEventArgs e)
{
  AssociatedObject.Position = TimeSpan.FromSeconds(0);
  AssociatedObject.Play();
}

protected override void OnCleanup()
{
  Messenger.Default.Unregister(this);
  AssociatedObject.MediaEnded -= AssociatedObjectMediaEnded;
}&lt;/pre&gt;
&lt;p&gt;The first method, SetRepeat, enables or disables repeat. As a MediaElement does not support the endless &lt;a href="http://lh4.ggpht.com/-YwvKM25HeNU/UPKwHqPbszI/AAAAAAAAKC4/-rzR1Bw5oAs/s1600-h/SoundMvvm%25255B3%25255D.png"&gt;&lt;img title="SoundMvvm" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="SoundMvvm" align="right" src="http://lh4.ggpht.com/-SVDn9rkqf88/UPKwIUZIQVI/AAAAAAAAKC8/8T2YCYocE7U/SoundMvvm_thumb%25255B1%25255D.png?imgmax=800" width="109" height="185"&gt;&lt;/a&gt;loop by itself, repeat as such is implemented by subscribing the method AssociatedObjectMediaEnded to the MediaEnded event of the MediaElement – that does nothing more than kicking off the sound again. If repeat has to be turned off, the AssociatedObjectMediaEnded is unsubscribed again and the sound automatically ends.&lt;/p&gt;
&lt;p&gt;Finally, the last method is called when the behavior is deactivated. It removes the messenger subscription and a possible repeat event subscription.&lt;/p&gt;
&lt;p&gt;So how would you go about and use such a behavior? To demonstrate it’s working, I have created &lt;a href="http://www.schaikweb.net/dotnetbyexample/soundmvvm.zip" target="_blank"&gt;a small sample solution&lt;/a&gt; with the very exiting *cough* user interface showed to the right. What this app does is, as you click on the go button, is fire off the PlaySoundCommand command in the following, admittedly somewhat contrived view model:&lt;/p&gt;&lt;pre&gt;using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Wp7nl.Audio;

namespace SoundMvvm.Viewmodels
{
  public class SoundViewModel : ViewModelBase
  {
    public ICommand PlaySoundCommand
    {
      get
      {
        return new RelayCommand(
          () =&amp;gt;
            {
              var t = new DispatcherTimer {Interval =  
                      TimeSpan.FromSeconds(4)};
              t.Tick += TimerTick;
              t.Start();
            });
      }
    }

    private void TimerTick(object sender, EventArgs e)
    {
      tickNumber++;
      switch (tickNumber)
      {
        case 1:
          Messenger.Default.Send(new PlaySoundEffectMessage("Sad trombone"));
          break;
        case 2:
          Messenger.Default.Send(new PlaySoundEffectMessage("Ping"));
          break;
        case 3:
          Deployment.Current.Dispatcher.BeginInvoke(() =&amp;gt; 
            Messenger.Default.Send(new PlaySoundEffectMessage("Ping", false)));
          var t = sender as DispatcherTimer;
          t.Stop();
          t.Tick -= TimerTick;
          break;
      }
    }

    private int tickNumber;
  }
}&lt;/pre&gt;
&lt;p&gt;This initializes and starts a DispatcherTimer that will fire every four seconds. So the first four seconds after you click the button absolutely &lt;em&gt;nothing&lt;/em&gt; will happen – I wanted to simulate the situation in which an event in the view model, not necessarily directly kicks off the sound. At the first tick – after four seconds – the view model fires a message making the behavior start the “Sad trombone” sound, which runs about four seconds. Then it fires off the “Ping” message, which causes the “Ping” sound to be started and repeated by the behavior. After another four seconds (good for about three ‘pings’) it’s killed again by the second “Ping” message. And then this little app has done all it could. Cue sad trombone indeed ;-)&lt;/p&gt;
&lt;p&gt;As to the XAML to make this all work, I’ve outlined in red (and underline for the color blind readers) the interesting parts:&lt;/p&gt;&lt;pre style="font-size: 9pt"&gt;&amp;lt;phone:PhoneApplicationPage
    x:Class="SoundMvvm.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:audio="clr-namespace:Wp7nl.Audio;assembly=Wp7nl.MvvmLight"
    xmlns:viewmodels="clr-namespace:SoundMvvm.Viewmodels"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" &amp;gt;

  &amp;lt;phone:PhoneApplicationPage.Resources&amp;gt;
    &amp;lt;viewmodels:SoundViewModel x:Key="SoundViewModel" /&amp;gt;
  &amp;lt;/phone:PhoneApplicationPage.Resources&amp;gt;
  &amp;lt;Grid x:Name="LayoutRoot" Background="Transparent" &lt;br&gt;                            &lt;font color="#ff0000"&gt;&lt;u&gt;DataContext="{StaticResource SoundViewModel}&lt;/u&gt;"&lt;/font&gt;&amp;gt;
    &amp;lt;Grid.RowDefinitions&amp;gt;
      &amp;lt;RowDefinition Height="Auto"/&amp;gt;
      &amp;lt;RowDefinition Height="*"/&amp;gt;
    &amp;lt;/Grid.RowDefinitions&amp;gt;

    &amp;lt;StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"&amp;gt;
      &amp;lt;TextBlock Text="DEMO MVVM SOUNDS" &lt;br&gt;                 Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/&amp;gt;
      &amp;lt;TextBlock Text="play sounds" Margin="9,-7,0,0" 
                     Style="{StaticResource PhoneTextTitle1Style}"/&amp;gt;
    &amp;lt;/StackPanel&amp;gt;

    &amp;lt;Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"&amp;gt;
      &amp;lt;Button Content="go!" Margin="0,31,0,0" VerticalAlignment="Top" 
              Width="128" Height="80" &lt;font color="#ff0000"&gt;&lt;u&gt;Command="{Binding PlaySoundCommand}"&lt;/u&gt;&lt;/font&gt;/&amp;gt;
    &amp;lt;/Grid&amp;gt;

    &amp;lt;MediaElement&amp;gt;
      &amp;lt;i:Interaction.Behaviors&amp;gt;
        &lt;font color="#ff0000"&gt;&lt;u&gt;&amp;lt;audio:PlaySoundEffectBehavior SoundName="Sad trombone"&lt;/u&gt;
               &lt;u&gt;SoundFileLocation="/Sound/Sad_Trombone-Joe_Lamb-665429450.mp3"/&amp;gt;&lt;/u&gt;&lt;/font&gt;
      &amp;lt;/i:Interaction.Behaviors&amp;gt;
    &amp;lt;/MediaElement&amp;gt;
    &amp;lt;MediaElement&amp;gt;
      &amp;lt;i:Interaction.Behaviors&amp;gt;
        &lt;u&gt;&lt;font color="#ff0000"&gt;&amp;lt;audio:PlaySoundEffectBehavior Repeat="True" SoundName="Ping"&lt;/font&gt;&lt;/u&gt; 
               &lt;u&gt;&lt;font color="#ff0000"&gt;SoundFileLocation="/Sound/Elevator-Ding-SoundBible.com-685385892.mp3"/&amp;gt;&lt;/font&gt;&lt;/u&gt;
      &amp;lt;/i:Interaction.Behaviors&amp;gt;
    &amp;lt;/MediaElement&amp;gt;
  &amp;lt;/Grid&amp;gt;
&amp;lt;/phone:PhoneApplicationPage&amp;gt;&lt;/pre&gt;
&lt;p&gt;On top we have the DataContext set to our viewmodel, which, by using it this way, is automatically instantiated. The “go!” button is bound to the PlaySoundCommand, and then you see near the bottom the two MediaElement objects which each a PlaySoundEffectBehavior. The first one plays the “Sad trombone" once as the message is received, the second repeatedly (Repeat=”True”) the “ping” sound until it receives a message with “Start” the to “false” indicating it should shut up.&lt;/p&gt;
&lt;p&gt;In the sample solution you will find two projects: SoundMvvm (the app itself) and Wpnl.Contrib, which both the behavior and the message class. As you probably understand from this setup, both classes will be soon in the &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl CodePlex library&lt;/a&gt;.For the record, this is a Windows Phone 8 app, but I think this should work on Windows Phone 7 as well, although on 7 I would still go for the XNA SoundEffect class. The technique used for this behavior comes from my &lt;a href="http://apps.microsoft.com/webpdp/app/catchem-birds/8417a0bf-e19d-4364-8116-e2dc79ffe39d" target="_blank"&gt;Catch’em Birds for Windows 8 app&lt;/a&gt; by the way, where you don’t have XNA at all.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/IQbSGot65eE" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-01-13T14:01:23.414+01:00</atom:updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-SVDn9rkqf88/UPKwIUZIQVI/AAAAAAAAKC8/8T2YCYocE7U/s72-c/SoundMvvm_thumb%25255B1%25255D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2013/01/playing-sounds-on-windows-phone-using.html</feedburner:origLink></item><item><title>Handling Windows Phone 8 NFC startup events using the MVVMLight Messenger</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/SbzDi69WpzI/handling-windows-phone-8-nfc-startup.html</link><category>MVVM</category><category>wpnl</category><category>MVVM Light</category><category>wpdev</category><category>Windows Phone 8</category><category>NFC</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 26 Dec 2012 07:49:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-4750936549221110658</guid><description>&lt;p&gt;&lt;a href="http://lh3.ggpht.com/-DVoWlgNW6co/UNscaHmnlMI/AAAAAAAAKCY/LMZK7CMcEz4/s1600-h/wp_ss_20121226_0002%25255B2%25255D.png"&gt;&lt;img title="wp_ss_20121226_0002" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="wp_ss_20121226_0002" align="right" src="http://lh4.ggpht.com/-tJ-SVIn8D8s/UNscbRrDjPI/AAAAAAAAKCc/hZVmz-OS7Zg/wp_ss_20121226_0002_thumb.png?imgmax=800" width="148" height="244"&gt;&lt;/a&gt;As regular readers of this blog know, I am currently playing around with &lt;a href="http://nl.wikipedia.org/wiki/Near_field_communication" target="_blank"&gt;NFC&lt;/a&gt; on &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8. I peeked a little in the &lt;a title="Bluetooth app to app sample at MSDN" href="http://code.msdn.microsoft.com/wpapps/Bluetooth-app-to-app-sample-890f8303?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Bluetooth app to app sample at MSDN&lt;/a&gt; to understand how to find a ‘peer’. A peer is defined as the same app, installed on a different phone. So basically you go around installing the app on two phones, start it on phone 1, make sure it calls &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.proximity.peerfinder.start.aspx?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;PeerFinder.Start()&lt;/a&gt;, tap the phones together and presto - the popup as displayed in the image on the right appears. If you check ‘open app’ – or whatever it shows in the language you have selected – the app is started on the second phone as well.&lt;/p&gt; &lt;p&gt;You can distinguish between an app being started by itself, or with the “open app” button by overriding the OnNavigatedTo method from the app’s main startup page. If the app is all started up by itself, the NavigationEventArgs.Uri just contains the name of the main page, for instance “MainPage.xaml”. But if it is started by an NFC event, the Uri ends with the following rather funny long string:&lt;/p&gt;&lt;pre&gt;ms_nfp_launchargs=Windows.Networking.Proximity.PeerFinder:StreamSocket&lt;/pre&gt;
&lt;p&gt;Annoyingly, the OnNavigatedTo event is only available inside the page’s code. If you want to handle this the MVVM way, you want this to be taken care of by a view model or a model, not by the page’s code behind. &lt;/p&gt;
&lt;p&gt;I have gone the following route. First, I define a little extension method that easily helps me to determine if the app was initiated by the user or by an NFC event:&lt;/p&gt;&lt;pre style="font-size: 9pt"&gt;using System.Windows.Navigation;

namespace Wp7nl.Devices
{
  public static class NavigationEventArgsExtensions
  {
    public static bool IsStartedByNfcRequest(this NavigationEventArgs e)
    {
      var isStartedByNfcRequest = false;
      if (e.Uri != null)
      {
        isStartedByNfcRequest = 
          e.Uri.ToString()
          .Contains("ms_nfp_launchargs=Windows.Networking.Proximity.PeerFinder:StreamSocket");
      }
      return isStartedByNfcRequest;
    }
  }
}&lt;/pre&gt;
&lt;p&gt;And as I don’t like to pass bare events around, I make a little wrapper class to use as a message:&lt;/p&gt;&lt;pre style="font-size: 9pt"&gt;using System.Windows.Navigation;
using Wp7nl.Devices;

namespace PullTheRope.Logic.Messages
{
  public class NavigationMessage
  {
    public NavigationEventArgs NavigationEvent { get; set; }

    public bool IsStartedByNfcRequest
    {
      get 
      { 
        return NavigationEvent != null &amp;amp;&amp;amp; NavigationEvent.IsStartedByNfcRequest();
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;And it contains a convenient shortcut method as well. Then the only thing you have to do is indeed override the OnNavigatedTo method, like this:&lt;/p&gt;&lt;pre style="font-size: 9pt"&gt;protected override void OnNavigatedTo(NavigationEventArgs e)
{
  base.OnNavigatedTo(e);
  Messenger.Default.Send(new NavigationMessage {NavigationEvent = e});
}&lt;/pre&gt;
&lt;p&gt;This is the only ‘breaking’ of the purist's MVVM approach – but as the event is nowhere else available, it’s also the only way to get it done. Sometimes you have to take the pragmatic approach. Anyway, somewhere in your model or view model you define which method should be called when the message is received&lt;/p&gt;&lt;pre&gt;Messenger.Default.Register&amp;lt;NavigationMessage&amp;gt;(this, ProcessNavigationMessage);&lt;/pre&gt;
&lt;p&gt;a method to trap it&lt;/p&gt;&lt;pre&gt;private void ProcessNavigationMessage(NavigationMessage message)
{
  // whatever – we are back in MVVM territory
}&lt;/pre&gt;
&lt;p&gt;and I trust you can take it from there ;-) .&lt;/p&gt;
&lt;p&gt;Be aware the events generated are generated outside the GUI thread, so if you try to data bind properties changed from the event method, you might run into cross thread access errors. Deployment.Current.Dispatcher.BeginInvoke is your friend, then.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/SbzDi69WpzI" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-01-11T22:21:38.566+01:00</atom:updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-tJ-SVIn8D8s/UNscbRrDjPI/AAAAAAAAKCc/hZVmz-OS7Zg/s72-c/wp_ss_20121226_0002_thumb.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/12/handling-windows-phone-8-nfc-startup.html</feedburner:origLink></item><item><title>On blogging, sharing and commenting</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/GJX4uzUGZWU/on-blogging-sharing-and-commenting.html</link><category>Off-topic</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Mon, 17 Dec 2012 11:06:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-1776461328517318696</guid><description>&lt;p&gt;This is not about code, but about something a fellow developer and blogger told me, which made me quite sad. It’s a kind of personal rant, so feel free to skip it if you are looking for code.&lt;/p&gt; &lt;p&gt;In 2007, after a frustrating search on the internet for a complete and working code sample for whatever it was, I was quite pissed off. And I decided “well if apparently people are too lazy or too much ‘look at me’ superior to post complete and working samples, I&lt;em&gt; &lt;/em&gt;will start doing so myself”. I also could have gone to the blogs I visited posting comments like “you moron, this code is incomplete and/or wrong” or “why don’t you stop coding/blogging the cr*p you post is useless”. While technically I would have been right, I don’t think it would have helped me solve my problems. Starting blogging myself did not help me solve that problems either, but at least I had a place where I could dump my own solutions for later reference. Very handy. Apparently other people liked it too. &lt;/p&gt; &lt;p&gt;I was lucky enough to post a few good articles, and a few very dumb ones too, but those were met with “hey, that’s obsolete”, “hey, this is a better solution” or “I think you are missing a few steps” – with links and information. I either did take the articles down, or reworked them with the new information. I was lucky enough not to get lambasted, flamed or receive abusive comments or mails – no, my baby steps were encouraged by a few people – mostly MVPs by the way – who kind of nudged me along the rocky path of the beginning blogger.&lt;/p&gt; &lt;p&gt;That encouragement made me go on, becoming confident enough so that when the occasional abusive comment arrived, I was able to ignore the wording of the comment and fix the error, or challenge the commenter: “so if &lt;em&gt;you&lt;/em&gt; are such a know-it-all, why don’t &lt;em&gt;you &lt;/em&gt;blog about it - why do &lt;em&gt;you&lt;/em&gt; leave me stumbling in the dark making stupid avoidable errors?”.&lt;/p&gt; &lt;p&gt;I recently talked to the beginning blogger I mentioned before, who was severely flamed in the beginning of his ‘career’, and he almost quit blogging of that. The wording I use in the second paragraph are more or less quotes of what he received. &lt;/p&gt; &lt;p&gt;This is really very counterproductive behavior. If you are someone who likes to demonstrate his/her knowledge on someone else’s blog by making demeaning remarks – realize what you are effectively doing is extinguishing enthusiasm that may have grown into the creation of a vast information resource. You are killing creativity, stomping out the sharing flame, making one of the very few willing to take time to share knowledge retreat into his/her shell, maybe never to come back again. &lt;/p&gt; &lt;p&gt;The very short version:&lt;/p&gt; &lt;h3&gt;&lt;/h3&gt; &lt;p&gt;&lt;font size="4"&gt;Flaming other people’s blog has never led to more examples and information. If you want more and better examples: stimulate and encourage where you can, correct if you feel you must, and try to behave like a civilized human being.&lt;/font&gt;&lt;/p&gt; &lt;p&gt;And above all, start blogging yourself. Don’t be a prick – share. Use your knowledge to improve people, not to tear them down. That’s community. That’s how it works. &lt;/p&gt; &lt;p&gt;Thank you.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/GJX4uzUGZWU" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-12-18T09:44:48.767+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/12/on-blogging-sharing-and-commenting.html</feedburner:origLink></item><item><title>Preventing high speed socket communication on Windows Phone 8 going south when using async/await</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/oDS5UBrrMNw/preventing-high-speed-socket.html</link><category>sockets</category><category>wpdev</category><category>Windows Phone 8</category><category>Bluetooth</category><category>NFC</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Sun, 16 Dec 2012 11:15:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-9112032571609545586</guid><description>&lt;p&gt;Currently I am working on a &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; 8 action game in which you can fight a kind of duel. This involves pairing the phones via NFC and then obtaining a socket trough which the phones can exchange game information. Liking to steal from examples myself (why do you think I name my blog this way, eh?) I stole code from the &lt;a href="http://code.msdn.microsoft.com/wpapps/Bluetooth-app-to-app-sample-890f8303?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Bluetooth app to app sample at MSDN&lt;/a&gt;. Now this is a great sample but it has one kind of problem for me. &lt;/p&gt; &lt;p&gt;I’ll skip the pairing, the obtaining of the socket and the definition of the data reader – that’s all documented in the MSDN sample. The method to send a message to the opponent was, in condensed form:&lt;/p&gt;&lt;pre&gt;public async void SendMessage(string message)
{
  if (dataWriter == null)
  {
    dataWriter = new DataWriter(socket.OutputStream);
  }

  dataWriter.WriteInt32(message.Length);
  await dataWriter.StoreAsync();

  dataWriter.WriteString(message);
  await dataWriter.StoreAsync();
}&lt;/pre&gt;
&lt;p&gt;while at the same time both opponenents where listening using a simple method like&lt;/p&gt;&lt;pre&gt;public async Task&lt;string&gt; GetMessage()
{
  if (dataReader == null) dataReader = new DataReader(socket.InputStream);
  await dataReader.LoadAsync(4);
  var messageLen = (uint)dataReader.ReadInt32();
  Debug.WriteLine(messageLen);

  await dataReader.LoadAsync(messageLen);
  var message = dataReader.ReadString(messageLen);
  Debug.WriteLine(message);
  return message;
}&lt;/pre&gt;
&lt;p&gt;From the debug statements in this code you can see things weren’t exactly working as planned. Now the way this is &lt;em&gt;supposed&lt;/em&gt; to work is as follows: as the opponent sends a message using SendMessage, the other phone is receiving a message via the socket in GetMessage. The first four bytes contain an unsigned integer containing the length of the rest of the message – which is supposed to be a string. 
&lt;p&gt;I noticed that while things went off to a good start, sooner or later one of the two phones would stop receiving messages or both games crashed simultaneously. I got all kind of null value errors, index out of range and whatnot. When I started debugging, I found out that while the app on phone 1 said it sent a 3-character string, the receiving app on phone 2 sometimes got a huge number for the message length, that obviously wasn’t sent, it read past the end of the stream – crash. 
&lt;p&gt;The MSDN sample works fine, as long as it is used for the purpose it was written, i.e. sending out (chat) messages at a kind of sedate pace – not for sending a lot of events per second to keep a game in sync. The essence of a stream is that &lt;em&gt;it’s a stream indeed – things have to be written and read in the right order&lt;/em&gt;. For what happened of course was a race condition between two or more events in a short timeframe. The first event wrote the message length, the second event as well, then possibly a third, before the first one came to writing the actual &lt;em&gt;message, &lt;/em&gt;and whatever arrived on the other phone was a garbled jumble of bytes that did exactly reflect what happened on the sending phone, but wasn’t the orderly message length – message payload stream the other phone expected. 
&lt;p&gt;The way I solved it – in a ‘there-I-fixed-it’ kind of way – was to use a lock on the write code so at least stuff went in the stream in the order the other phone was expecting it:&lt;/p&gt;&lt;pre&gt;public async void SendMessage(string message)
{
  lock (this)
  {
    if (dataWriter == null)
    {
      dataWriter = new DataWriter(socket.OutputStream);
    }

    dataWriter.WriteInt32(message.Length);
    dataWriter.StoreAsync();

    dataWriter.WriteString(message);
    dataWriter.StoreAsync();
  }
}&lt;/pre&gt;
&lt;p&gt;Note you have to remove the “await” before the StoreAsync methods as those are not allowed within a lock. This method makes sure one message – and the whole message – is written on the stream and nothing comes in between. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt; – the first version of this posting contained a small error – which has been graciously pointed out to me by a few readers (see comments section). Also, I’ve been pointed to an &lt;a href="http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx" target="_blank"&gt;article by Scott Hanselman&lt;/a&gt; about a similar subject. I’ve tried using the &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx" target="_blank"&gt;AsyncLock by Stephen Toub&lt;/a&gt; he describes but found out that although it works very good and my game does become a bit more fluid, the lag in getting messages across is a lot higher. Net effect: while the game runs more smoothly on both phones, the game state actually gets out of sync very fast, making the game unplayable. Apparently the AsyncLock approach doesn’t work for high speed continuous message exchange, so for now I’ll stick to the approach I described above.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/oDS5UBrrMNw" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-12-18T09:42:07.459+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">5</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/12/preventing-high-speed-socket.html</feedburner:origLink></item><item><title>Passing event arguments to the WinRT EventToCommandBehavior</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/fRIz50SffZo/passing-eventargs-to-winrt.html</link><category>MVVM</category><category>behavior</category><category>XAML</category><category>Win8nl</category><category>WinRt</category><category>Windows 8</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Tue, 20 Nov 2012 09:00:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-6538955592077262268</guid><description>&lt;p&gt;This week my fellow MVP &lt;a href="http://www.twitter.com/@scottisafool" target="_blank"&gt;Scott Lovegrove&lt;/a&gt; contacted me and asked if and how he could pass the result of an event to my WinRT &lt;a href="http://dotnetbyexample.blogspot.nl/2012/07/a-winrt-behavior-to-mimic-eventtocommand.html" target="_blank"&gt;EventToCommandBehavior&lt;/a&gt; and/or &lt;a href="http://dotnetbyexample.blogspot.nl/2012/11/a-winrt-behavior-to-mimic.html" target="_blank"&gt;EventToBoundCommandBehavior&lt;/a&gt;. I replied this was currently not supported, but that would not be hard to make. He acknowledged that, and asked if he could mail some code. Since I am not very possessive of ‘my’ libraries, and am a lazy as any programmer should be, I responded with giving him developer access to &lt;a href="http://win8nl.codeplex.com/" target="_blank"&gt;Win8nl&lt;/a&gt;. He actually took up the challenge, and submitted the code. &lt;/p&gt; &lt;p&gt;Both EventToCommandBehavior and EventToBoundCommandBehavior now sport an extra property:&lt;/p&gt;&lt;pre&gt;public bool PassEventArgsToCommand { get; set; }&lt;/pre&gt;
&lt;p&gt;If you set this property to true and don’t use the CommandParameter property, the method firing the command will actually pass the captured event to the model. How this works, is pretty simple to see in EventToBoundCommandBehavior:&lt;/p&gt;&lt;pre&gt;private void FireCommand(RoutedEventArgs routedEventArgs)
{
  if (Command != null &amp;amp;&amp;amp; Command.CanExecute(CommandParameter))
  {
&lt;font color="#ff0000"&gt;    if (PassEventArgsToCommand &amp;amp;&amp;amp; CommandParameter == null)
    {
      Command.Execute(routedEventArgs);
    }
    else
    {&lt;/font&gt;
      Command.Execute(CommandParameter);
&lt;font color="#ff0000"&gt;    }&lt;/font&gt;
  }
}&lt;/pre&gt;
&lt;p&gt;Red shows the additions. Usage of course is pretty simple:&lt;/p&gt;&lt;pre&gt;&amp;lt;TextBlock Text="TextBlock" FontSize="48"&amp;gt;
  &amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
    &amp;lt;Behaviors:EventToBoundCommandBehavior Event="Tapped" 
      Command="{Binding TestCommand}" 
      &lt;font color="#ff0000"&gt;PassEventArgsToCommand="true"&lt;/font&gt;/&amp;gt;
  &amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;
&amp;lt;/TextBlock&amp;gt;&lt;/pre&gt;
&lt;p&gt;And then you have to define a command TestCommand like this in your model:&lt;/p&gt;&lt;pre&gt;public ICommand TestCommand
{
  get
  {
    return new RelayCommand&amp;lt;TappedRoutedEventArgs&amp;gt;(
      (p) =&amp;gt;
        {
           Debug.WriteLine(p.PointerDeviceType);
        });
  }
}&lt;/pre&gt;
&lt;p&gt;This will write '”Mouse”, “Touch” or “Pen” in your output window, depending on what you use to tap. Of course this is not a very useful application of this technique, but it proves the point. If you don’t use PassEventArgsToCommand both behaviors will work as before.&lt;/p&gt;
&lt;p&gt;Now as an architect I am not too fond of this technique, because it introduces user-interface related objects into the view model – I get a bit restless when I see something like “using Windows.UI.Xaml.Input” on top of a view model class. Be careful when you use this. On the other hand, a holier-than-thou attitude ain’t gonna help getting &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Window 8&lt;/a&gt; apps shipped and so if this will help people, I am more than fine with that.;-)&lt;/p&gt;
&lt;p&gt;Scott tells me this code is derived from &lt;a href="http://www.twitter.com/lbugnion" target="_blank"&gt;Laurent Bugnion&lt;/a&gt;’s original code – I did not check, but I am going to take his word for it. At the time of this writing it’s part of Win8nl 1.0.6 and already available as Nuget package. Now I only have the problem that not every line of code comes from the Netherlands, so maybe I should indeed rename this package to Win8eu ;-) &lt;/p&gt;
&lt;p&gt;As (almost) always, &lt;a href="http://www.schaikweb.net/dotnetbyexample/EventArg.zip" target="_blank"&gt;a demo solution can be found here&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/fRIz50SffZo" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-11-20T21:58:41.172+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/11/passing-eventargs-to-winrt.html</feedburner:origLink></item><item><title>Reactive Extensions in Windows Phone 8 and the 2001 submission error</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/MYqb2PZcLDA/reactive-extensions-in-windows-phone-8.html</link><category>wpdev</category><category>Windows Phone 8</category><category>Reactive</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Sat, 17 Nov 2012 04:39:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-2030716937111263252</guid><description>&lt;p&gt;You can read the whole story if you like reading, but this whole blog post comes down to one piece of advice:&lt;/p&gt; &lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;font size="2"&gt;If you value your sanity, do not, under any circumstances, pull in Reactive Extensions from NuGet into a Windows Phone 8 application. Use the built-in Microsoft.Phone.Reactive.dll instead.&lt;/font&gt;&lt;/em&gt;&lt;/strong&gt;&amp;nbsp; &lt;p&gt;Those who follow me on twitter may have seen a few tweets pass by over problems I had with the &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; 8 version of my app &lt;a href="http://windowsphone.com/s?appid=8b5f61a1-3ffa-df11-9264-00237de2db9e&amp;amp;ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Map Mania&lt;/a&gt;. The submission went OK the first time, but the test team found two bugs – bugs that were also there in previous versions, but apparently they have ramped up the quality bar again. I can only applaud that, even if I got bitten by it myself, because the test report was comprehensive and showed someone actually understood or had read into some issues that may arise when using &lt;a href="http://en.wikipedia.org/wiki/Web_Map_Service" target="_blank"&gt;WMS services&lt;/a&gt; – and by doing so, succeeded in crashing my app. &lt;/p&gt; &lt;p&gt;Anyway, I fixed the app, resubmitted, and then the trouble started. Although the Store Test kit showed no errors, and submission went fine showing only validated XAP’s – after a few minutes I got an e-mail from the Windows Phone dev center:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;strong&gt;Windows Phone Dev Center app submission&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;We weren't able to process the app submission for Map Mania. &lt;/strong&gt; &lt;p&gt;&lt;strong&gt;Unfortunately, something happened with your Windows Phone app submission. Check the status of the submission in your app list at &lt;/strong&gt;&lt;a href="https://dev.windowsphone.com/applicationlist"&gt;&lt;strong&gt;https://dev.windowsphone.com/applicationlist&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;. If the problem persists, contact support for assistance.&lt;/strong&gt; &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;When I looked at the submission it said I had a “2001 error” &lt;a href="http://msdn.microsoft.com/library/windowsphone/help/jj206735(v=vs.105).aspx" target="_blank"&gt;with a helpful link&lt;/a&gt;, that leads you to a table in which it says:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;strong&gt;There are duplicate files in AppManifest.xaml. Remove one of the files and then try again.&lt;/strong&gt;  &lt;p&gt;&lt;strong&gt;If rebuilding your XAP doesn't solve this problem, you may have to manually remove any duplicate files from the AppManifest.xaml in your XAP file. To rebuild your app, see &lt;/strong&gt;&lt;a href="http://msdn.microsoft.com/library/windowsphone/help/jj206735%28v=vs.105%29.aspx#BKMK_AppSubErr_ReBuildProject"&gt;&lt;strong&gt;Rebuilding your project in Visual Studio&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;. &lt;/strong&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;My friends, I have rebuilt the app till my fingers bled, cleaned the solution, then removed all the binaries manually, to no avail. Then I opened up the XAP to look for duplicate assemblies – there weren’t any duplicates; I scanned the AppManifest.xaml till I saw cross-eyed and didn’t find any duplicate entries there either - and after the 10th or so submit followed by automatic mail error within five minutes I gave up and indeed contacted Support.  &lt;p&gt;I won’t go into full detail, but I think it’s fair to say this problem wasn’t easy to solve and Support struggled as much with it as I did. Quite some mails went back and forth, and the 9 hour time zone difference didn’t exactly work favorably for a quick resolve. It wasn’t until our &lt;a href="www.twitter.com/mahoekst" target="_blank"&gt;Dutch DPE Matthijs Hoekstra&lt;/a&gt;, who I think now owe not only my sanity but possibly also my soul ;-), queried his sources and got back that a post-processing error apparently was being caused by System.Reactive.Core.dll and I was recommended to use Microsoft.Phone.Reactive.dll instead if possible.  &lt;p&gt;I finally had a possible smoking gun - my &lt;em&gt;own&lt;/em&gt; port of the #&lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl library&lt;/a&gt; pulls in Reactive extensions &lt;em&gt;from Nuget&lt;/em&gt;. So I removed the dependency from the library package, made a new local build, installed that into the app, compiled, uploaded and submitted, waiting for the inevitable dreaded 2001 error mail to pop up. Over an hour later, the only mail I got was from &lt;a href="http://outlook.com/"&gt;outlook.com&lt;/a&gt; reminding me of a birthday and the app status at the moment of this writing says “Status: In signing stage". Hallelujah!  &lt;p&gt;Now I don’t understand why submission went OK the first time and not the second time around. But I am very glad the issue is resolved. &lt;u&gt;If you use my library, please remove the references it makes to the external reactive stuff manually&lt;/u&gt; or wait for me to publish the version that will do without. It will be out soon, I can tell you that.&lt;/p&gt; &lt;p&gt;&lt;em&gt;Update: #wp7nl was updated within a few hours of this post. If you use the Windows Phone 8 version, &lt;u&gt;please update to 3.0.1&lt;/u&gt;. Should you experience problems with missing assemblies, make a manual reference to Microsoft.Phone.Reactive.dll to the projects that use wp7nl.&lt;u&gt; And please remove any reference to Rx* should they linger along&lt;/u&gt;. &lt;/em&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/MYqb2PZcLDA" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-11-19T08:15:27.668+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/11/reactive-extensions-in-windows-phone-8.html</feedburner:origLink></item><item><title>A WinRT behavior to mimic EventToCommand (take 2)</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/yVPTkmCiC9w/a-winrt-behavior-to-mimic.html</link><category>MVVM</category><category>behavior</category><category>XAML</category><category>Win8nl</category><category>WinRt</category><category>Windows 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 14 Nov 2012 01:13:00 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-8017519964283843716</guid><description>&lt;p&gt;(Updated with sample code January 19 2013)&lt;/p&gt; &lt;p&gt;Some time ago I posted a &lt;a href="http://dotnetbyexample.blogspot.nl/2012/07/a-winrt-behavior-to-mimic-eventtocommand.html" target="_blank"&gt;WinRT behavior to mimic EventToCommand&lt;/a&gt;. This behavior cunningly looked for the command name in the DataContext, but it occurred to me (and some blog post commenters as well) that it actually might be more logical skip all that skullduggery and let the developer &lt;em&gt;bind&lt;/em&gt; to a command in stead of letting her/him provide its name as string and then go look for it.&lt;/p&gt; &lt;p&gt;Anyway, not wanting to break compatibility I added a &lt;em&gt;new&lt;/em&gt; behavior to my &lt;a href="http://win8nl.codeplex.com/" target="_blank"&gt;win8nl library on CodePlex&lt;/a&gt;, very originally called EventTo&lt;em&gt;Bound&lt;/em&gt;CommandBehavior.&lt;/p&gt; &lt;p&gt;It’s working is very similar to the original EventToCommandBehavior. There are two notable differences:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The Command property is now no longer of type string but ICommand  &lt;li&gt;The FireCommand method is now very simple:&lt;/li&gt;&lt;/ul&gt;&lt;pre&gt;private void FireCommand()
{
  if (Command != null &amp;amp;&amp;amp; Command.CanExecute(CommandParameter))
  {
    Command.Execute(CommandParameter);
  }
}&lt;/pre&gt;
&lt;p&gt;Which goes to show that you can be &lt;em&gt;too&lt;/em&gt; clever.&lt;/p&gt;
&lt;p&gt;If you want to replace the original behavior for the new one – say, you used it like this&lt;/p&gt;&lt;pre&gt;&amp;lt;TextBlock Text="TextBlock" FontSize="48"&amp;gt;
  &amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
    &amp;lt;Behaviors:EventToCommandBehavior Event="Tapped" 
      Command="TestCommand" 
      CommandParameter="{Binding TestProperty, Mode=TwoWay}"/&amp;gt;
  &amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;
&amp;lt;/TextBlock&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Just go to the places marked red/underlined:&lt;/p&gt;&lt;pre&gt;&amp;lt;TextBlock Text="TextBlock" FontSize="48"&amp;gt;
  &amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
    &amp;lt;Behaviors:EventTo&lt;font color="#ff0000"&gt;&lt;u&gt;Bound&lt;/u&gt;&lt;/font&gt;CommandBehavior Event="Tapped" 
      Command="&lt;font color="#ff0000"&gt;&lt;u&gt;{Binding TestCommand}&lt;/u&gt;&lt;/font&gt;" 
      CommandParameter="{Binding TestProperty, Mode=TwoWay}"/&amp;gt;
  &amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;
&amp;lt;/TextBlock&amp;gt;&lt;/pre&gt;
&lt;p&gt;Those who want to see the full source code of the new (and largely simplified) behavior can do so at &lt;a title="http://win8nl.codeplex.com/SourceControl/changeset/view/20896#395786" href="http://win8nl.codeplex.com/SourceControl/changeset/view/20896#395786"&gt;http://win8nl.codeplex.com/SourceControl/changeset/view/20896#395786&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;: I’ve added some more sample code as a lot of people seem to struggle with the correct use of this behavior. Lots of time I get program problems like this: “I have a list in my view model and a command yet my command is not fired when then I tap the item”. The view model usually contains these properties:&lt;/p&gt;&lt;pre&gt;public ObservableCollection&lt;phone&gt; Phones { get; set; }

public ICommand TappedCommand
{
  // code omitted
}&lt;/pre&gt;
&lt;p&gt;and the XAML is like this:&lt;/p&gt;&lt;pre&gt;&amp;lt;Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" 
  DataContext="{StaticResource DemoViewModel}"&amp;gt;

 &lt;font color="#ff0000"&gt; &amp;lt;GridView ItemsSource="{Binding Phones}" SelectionMode="None" 
     IsTapEnabled="True"&amp;gt;
&lt;font color="#0000ff"&gt;    &amp;lt;GridView.ItemTemplate&amp;gt;
      &amp;lt;DataTemplate&amp;gt;
        &amp;lt;Grid Width="350"&amp;gt;
          &amp;lt;Grid.ColumnDefinitions&amp;gt;
            &amp;lt;ColumnDefinition/&amp;gt;
            &amp;lt;ColumnDefinition/&amp;gt;
          &amp;lt;/Grid.ColumnDefinitions&amp;gt;
          &amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
            &amp;lt;Behaviors:EventToBoundCommandBehavior 
              Command="{Binding TappedCommand}" 
              CommandParameter="{Binding}" Event="Tapped" /&amp;gt;
          &amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;

          &amp;lt;TextBlock Text="{Binding Brand}"/&amp;gt;
          &amp;lt;TextBlock Text="{Binding Type}" Grid.Column="1"/&amp;gt;
        &amp;lt;/Grid&amp;gt;
      &amp;lt;/DataTemplate&amp;gt;
    &amp;lt;/GridView.ItemTemplate&amp;gt;&lt;/font&gt;
  &amp;lt;/GridView&amp;gt;
&lt;/font&gt;&amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;I this case, the programmer has lost track of what’s the exact data context. Happens all the time, even to me. I’ve used colors to depict the data context changes.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In the black code, DemoViewModel is the data context 
&lt;li&gt;In the red code, the ObserservableCollection Phones is the data context 
&lt;li&gt;In the blue code, a single Phone is the context.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;So what this code tries to do is to call a command TappedCommand &lt;em&gt;on class&lt;/em&gt; &lt;em&gt;Phone in stead of DemoViewModel.&lt;/em&gt;So either the command needs to be in “Phone”, or the behavior’s binding must be updated like this:&lt;/p&gt;&lt;pre&gt;&amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
  &amp;lt;Behaviors:EventToBoundCommandBehavior 
    Command="{Binding TappedCommand&lt;u&gt;&lt;font color="#ff0000"&gt;, Source={StaticResource DemoViewModel}&lt;/font&gt;&lt;/u&gt;}" 
    CommandParameter="{Binding}" Event="Tapped" /&amp;gt;
&amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/GridViewTappedItem.zip" target="_blank"&gt;Full working example can be found here.&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/yVPTkmCiC9w" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2013-01-20T16:45:55.462+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">9</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/11/a-winrt-behavior-to-mimic.html</feedburner:origLink></item><item><title>Data binding shapes to the new Windows Phone 8 Map control (and more)</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/MPpeiBOsdJw/data-binding-shapes-to-new-windows.html</link><category>MVVM</category><category>Mapping</category><category>MVVM Light</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Tue, 30 Oct 2012 11:25:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-1323957409596803256</guid><description>&lt;p&gt;&lt;font size="4"&gt;A little history&lt;/font&gt;&lt;/p&gt;When I accepted the invitation from &lt;a href="http://www.eventbrite.com/event/4039089024/eorg"&gt;MADNbe to talk about Maps and MVVM on September 20&lt;/a&gt; early in the summer (or what was supposed to be the summer) of 2012 the actual release date for the &lt;a href="http://wpdev.ms/wpsdkdl?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone SDK 8.0&lt;/a&gt; was still a mystery. As it gradually became clear the SDK would not be available at the date my talk was scheduled, I devised a plan B and in stead talked about Windows Phone 7 mapping and how to port this code and knowledge to &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt;. I also &lt;a href="http://dotnetbyexample.blogspot.nl/2012/09/data-binding-shapes-to-winrt-bing-maps.html"&gt;wrote a blog post I wrote about it&lt;/a&gt;. Now the funny thing is - the Windows Phone 8 mapping control and the Windows 8 Bing Maps control show some remarkable similarities. So if you read this article and think “Huh? I’ve read this before” that’s entirely possible!&amp;nbsp; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/019e0590d2d4_AD04/Hello-8-World.png"&gt;&lt;img title="Hello 8 World" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Hello 8 World" align="right" src="http://www.schaikweb.net/dotnetbyexample/019e0590d2d4_AD04/Hello-8-World_thumb.png" width="161" height="274"&gt;&lt;/a&gt;So world in general, and Belgium in particular, meet the new Hello World, Windows Phone 8 style!&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Windows Phone 7 map binding recap&lt;/font&gt; &lt;/p&gt; &lt;p&gt;Not going to happen - I am not going to repeat myself for the sake of content ;-). In the &lt;a href="http://dotnetbyexample.blogspot.nl/2012/09/data-binding-shapes-to-winrt-bing-maps.html"&gt;the Windows 8 article I give a short recap&lt;/a&gt; of how you can bind to a Windows Phone 7 map, using templates. I’d suggest you read that if you haven’t done so already ;-). By the way, the sample solution contained with this project is mostly the same as the &lt;a title="here" href="http://www.schaikweb.net/dotnetbyexample/mvvmmaps.zip"&gt;sample Windows Phone 7&lt;/a&gt; application I use in my talk. I upgraded to Windows Phone but did not even bother to change the libraries I used. (like &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt;, &lt;a href="http://phone7.codeplex.com/" target="_blank"&gt;Phone7.Fx&lt;/a&gt; or my own &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl library&lt;/a&gt;). That’s still Windows Phone 7 code and you call that code from Windows Phone 8 without any problem. Very soon I hope to publish updates for the libraries specific to the platform, and you will see them appearing in your NuGet package manager. The only thing you have to keep in mind is that the app no longer runs in quirks mode once you upgraded to Windows Phone 8. That means – if your library code does something funky that has a different behavior under Windows Phone 8, the platform is not going to help you keep that funky behavior&amp;nbsp; - unlike when you run a (real) Windows Phone 7 app on it. &lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Data binding and the new map control&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Without cheering overly loud for ‘my’ home team, I actually think the Windows Phone mapping team actually has done a better job on this part than their Windows 8 brethren. That’s actually not so very hard, as the Windows 8 Bing Maps control does not support data binding &lt;em&gt;at all. &lt;/em&gt;The Windows Phone 8 control actually (still) supports the binding of Center and ZoomLevel, as well as the new properties CartographicMode, LandMarksEnabled, Heading and Pitch, – “Heading” being the direction of the top of the map, default 0, being North – and Pitch the viewing angle of the map (normally zero, or ‘straight from above’). And probably some more I haven’t used yet.&lt;/p&gt; &lt;p&gt;But as far as drawing shapes on the maps are concerned, we are in the same boat as in Windows 8:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The shapes the control draws cannot be templated. They are apparently just projections of something native (as is the map itself).  &lt;li&gt;There are only two kinds of shapes: MapPolygon and MapPolyline, both descending from MapElement (as opposed to &lt;em&gt;MapShape&lt;/em&gt; in Windows 8), which in turn descends from DependencyObject – so I can use the same trick again – storing data in attached dependency properties.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;To solve this, I use the same approach as I did in Windows 8: apply behaviors. Only that’s a lot easier now because unlike Windows 8, Windows Phone 8 supports behaviors out of the box.&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Introducing MapShapeDrawBehavior for Windows Phone 8&lt;/font&gt;&lt;font size="4"&gt;&lt;br&gt;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;This behavior is, just like it’s Windows 8 brother, called MapShapeDrawBehavior. It’s use is quite similar:&lt;br&gt;&lt;/p&gt;&lt;pre&gt;&amp;lt;Maps:Map x:Name="map" CartographicMode="Road"&amp;gt;
  &amp;lt;i:Interaction.Behaviors&amp;gt;
    &amp;lt;MapBinding:MapShapeDrawBehavior LayerName="Roadblocks" 
       ItemsSource="{Binding RoadBlocks}" 
       PathPropertyName="Geometry"&amp;gt;
      &amp;lt;MapBinding:MapShapeDrawBehavior.EventToCommandMappers&amp;gt;
        &amp;lt;MapBinding:EventToCommandMapper EventName="Tap" 
                                         CommandName="SelectCommand"/&amp;gt;
      &amp;lt;/MapBinding:MapShapeDrawBehavior.EventToCommandMappers&amp;gt;
      &amp;lt;MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
        &amp;lt;MapBinding:MapPolylineDrawer Color="Green" Width="10"/&amp;gt;
      &amp;lt;/MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
    &amp;lt;/MapBinding:MapShapeDrawBehavior&amp;gt;
  &amp;lt;/i:Interaction.Behaviors&amp;gt;
&amp;lt;/Maps:Map&amp;gt;&lt;/pre&gt;
&lt;p&gt;The only difference, in fact, with the Windows 8 behavior is that there is not a TapCommand &lt;em&gt;property&lt;/em&gt; but an EventMapper &lt;em&gt;collection&lt;/em&gt;. That is because unlike the Windows 8 map shapes, Windows Phone 8 shapes don’t support events &lt;em&gt;at all&lt;/em&gt;. These are events of the &lt;em&gt;map&lt;/em&gt;. There aren’t any layers for shapes too – there is just a MapElements collection that you can add shapes to. &lt;/p&gt;
&lt;p&gt;So for every&lt;em&gt; &lt;/em&gt;category of objects you define a behavior; in this case the road blocks (the green line on the app sceenshot above). This translates conceptually to a ‘layer’. Then you need to define three things per layer: 
&lt;ul&gt;
&lt;li&gt;Which property in the item view model contains the &lt;em&gt;Path&lt;/em&gt; – this is the terminology for a MapElement collection of points. This is of type &lt;em&gt;GeoCoordinateCollection&lt;/em&gt;. 
&lt;li&gt;&lt;em&gt;A&lt;/em&gt;&amp;nbsp;&lt;em&gt;drawer&lt;/em&gt;. A drawer is a concept I made up myself. It’s a class that creates a shape from a collection of points contained in a GeoCoordinateCollection. It’s my way to make something that’s not templatable more or less configurable and the idea behind is exactly the same as for Windows 8. 
&lt;li&gt;What command in the item view model (in this case, a RoadBlockViewModel) must be called when a GestureEvent is called on the map. This can be either Tap or DoubleTap. You do this by adding an EventToCommandMapper to the EventToCommandMappers list. &lt;/li&gt;&lt;/ul&gt;
&lt;ul&gt;&lt;/ul&gt;
&lt;ul&gt;&lt;/ul&gt;
&lt;ul&gt;&lt;/ul&gt;
&lt;ul&gt;&lt;/ul&gt;
&lt;p&gt;This behavior comes, just like it’s Windows 8 brother,&amp;nbsp; the three out-of-the box standard drawers: MapPolylineDrawer, MapPolygonDrawer, and MapStarDrawer. The last one draws a configurable star shaped polygon around a point – since map shapes cannot be points by themselves. A drawer needs only to implement one method:&lt;/p&gt;&lt;pre&gt;public override MapElement CreateShape(object viewModel, LocationCollection path)&lt;/pre&gt;
&lt;p&gt;The basic drawers don’t do anything with the view model: they just take the settings from XAML. You can write your own if you want for instance return a shape of a different color based upon view model values. Thematic mapping again, just like I said last time. 
&lt;p&gt;If you just want to use the behavior, download the &lt;a href="http://www.schaikweb.net/dotnetbyexample/mvvmmaps728.zip"&gt;sample solution&lt;/a&gt;, rip the Wp8nl.Contrib project from it and use it. It just needs a reference to System.Windows.Interactivity.dll, that’s about all. 
&lt;p&gt;&lt;font size="4"&gt;Some technical details&lt;/font&gt;&lt;/p&gt;As the inner workings of the behavior are almost identical to that of their Windows 8 counterparts, I am not going to recap everything again. The trick is the same: view models and layer names are stored in and retrieved from attached dependency properties that are attached to the shapes themselves - the behavior uses this how to hold view models and map shapes together, and which shape belongs to which layer. For the technically interested I will stress a few small points. First of all, I already said the map elements themselves don’t have any events. Therefore, I have to attach events to the &lt;em&gt;map&lt;/em&gt;, using the “AddEventMappings” method that’s loaded when the behavior’s OnLoad is called: &lt;pre&gt;private void AddEventMappings()
{
  foreach (var mapper in EventToCommandMappers)
  {
    var evt = AssociatedObject.GetType().GetRuntimeEvent(mapper.EventName);
    if (evt != null)
    {
      AddEventMapping(mapper);
    }
  }
}

private void AddEventMapping(EventToCommandMapper mapper)
{
  Observable.FromEvent&amp;lt;GestureEventArgs&amp;gt;(AssociatedObject, mapper.EventName)
    .Subscribe(se =&amp;gt;
     {
       var gestureArgs = se.EventArgs;
       if (gestureArgs != null)
       {
         var shape = 
            AssociatedObject.&lt;font color="#ff0000"&gt;GetMapElementsAt&lt;/font&gt;(
               gestureArgs.GetPosition(AssociatedObject)).FirstOrDefault(
                 p =&amp;gt; MapElementProperties.GetLayerName(p)==LayerName);
         if (shape != null)
         {
           FireViewmodelCommand(
             MapElementProperties.GetViewModel(shape), mapper.CommandName);
         }
       }
     });
}&lt;/pre&gt;
&lt;p&gt;So this works fundamentally different from it’s Windows 8 counterpart: not the shapes respond to events, but the &lt;em&gt;map&lt;/em&gt; does so, and reports the shapes found at a location of the tap or the doubletap. The shapes in question can be retrieved using the map’s GetMapElementsAt method. And then I select the first shape I find that has the same layer name in it’s LayerName attached dependency property as the behavior. Note this filter is necessary: the &lt;em&gt;map&lt;/em&gt; reports the shapes and it reports &lt;em&gt;all&lt;/em&gt; of them - since there is no real layer structure the map has no notion of which behavior put the shape on the map. And you don’t want every behavior reporting all other shapes that happen to be on the same location as well – that would result in double events. But if the behavior finds a hit, it calls the FireViewModelCommand, which is essentially the same as in Windows 8, and it shows the window with alphanumeric info. That part has not been changed at all.&lt;/p&gt;
&lt;p&gt;The rest of the behavior is mainly concerned with adding, removing and replacing shapes again. I would suggest you’d study that if you are interested in how to respond to the various events of an ObservableCollection. To prove that data binding actually works, you can open the menu and select “change dhl building”.&amp;nbsp; That’s the most eastward building on the map. If you choose that, you will actually see the building change shape. The only thing the TestChangedShapeCommand command - that’s called when you hit that menu item – does, it change a building’s geometry property. The image on the map is updated automatically.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Some concluding observations&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Somewhere down in the guts of Windows Phone 8 there’s a native control, and I very much think both it and it’s Bing Maps control for Windows 8 counterpart are of the same breed. Both have similar, yet subtly different projections to managed code. As I already mentioned – in Windows 8 the shapes descend from MapShape, in Windows Phone 8 from MapElement. In addition, Windows Phone Map Elements support StrokeColor, StrokeThickness and StrokeDash – no such thing on Windows 8 - one more cheer for the Windows Phone team ;). But neither are supporting complex shapes and things like donuts (polygons with holes in it). These are the hallmarks of the real heavy duty GIS systems like the stuff &lt;a href="http://www.cadcorp.com/"&gt;Cadcorp&lt;/a&gt;. &lt;a href="http://www.esri.com/"&gt;ESRI&lt;/a&gt; et al are making. &lt;/p&gt;
&lt;p&gt;Also important when sharing code is to note the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In Windows Phone 7, we made shapes from a LocationCollection, which is a collection of GeoCoordinate 
&lt;li&gt;In Windows Phone 8, shapes are created from a GeoCoordinateCollection, which is a collection of GeoCoordinate 
&lt;li&gt;In Windows 8, shapes are created from a LocationCollection which is a collection of Location. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;So &lt;em&gt;both&lt;/em&gt; platforms refactored the Locations and their collection, and both in opposite ways. This can be solved by using converters or a generic subclass specific for both platforms but I leave things like that as exercise for the reader. The fun thing is: once again it shows that a lot of code can be reused as long as you keep application and business logic in models and view models – that way, you only have to deal with user interface and platform considerations, but your basic app structure stays intact. Once more: three cheers for MVVM.&lt;/p&gt;
&lt;p&gt;And as usual you can download the &lt;a href="http://www.schaikweb.net/dotnetbyexample/mvvmmaps728.zip"&gt;sample solution&lt;/a&gt;. I will shortly add this stuff to the Windows Phone 8 specific version of the &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;wp7nl library on CodePlex&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy mapping on &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939"&gt;Windows Phone&lt;/a&gt; 8! &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/MPpeiBOsdJw" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-11-23T21:48:04.921+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">6</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/10/data-binding-shapes-to-new-windows.html</feedburner:origLink></item><item><title>Introducing the new Windows Phone 8 Map control</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/JWPFE1GH-YE/introducing-new-windows-8-map-control.html</link><category>MVVM</category><category>Mapping</category><category>MVVM Light</category><category>Windows Phone 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Tue, 30 Oct 2012 11:04:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-553560438932431806</guid><description>&lt;p&gt;The time is finally there: the &lt;a href="http://wpdev.ms/wpsdkdl?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone SDK 8.0&lt;/a&gt; is out, and now we can finally talk about all the great news things for developers that this new SDK brings, and I’ll start that right now. And I don’t think it will surprise anyone who knows me that the first thing I did was looking at the much-rumored new maps control.&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Introducing-the-new-Windows-8-Map-contro_10AF4/map1.png"&gt;&lt;img title="map1" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="map1" align="right" src="http://www.schaikweb.net/dotnetbyexample/Introducing-the-new-Windows-8-Map-contro_10AF4/map1_thumb.png" width="148" height="244"&gt;&lt;/a&gt;I was not disappointed. In general, just two words: &lt;em&gt;super slick&lt;/em&gt;. The very &lt;em&gt;embodiment&lt;/em&gt; of fast and fluid. What Windows Phone 8 brings to the mapping table made by geo hart skip and is nothing short of dramatic. Think the Nokia drive map on your Windows Phone 7. On steroids. As a control. For you to use in your apps. With downloadable maps for use offline. I have seen it run on actual hardware and for me as a GIS buff, used to the fact that maps stuff usually take a lot of processing power and doesn’t necessary always go super fast, this was a serious &lt;a href="http://www.urbandictionary.com/define.php?term=nerdgasm"&gt;nerdgasm&lt;/a&gt;. So I created a little app to show off the very basics of this map control. It allows you to select the various map modes, as well to to select map heading and pitch. Heading is the direction the top of the map is pointing – in Bing Maps this was always “North”, and Pitch is how you are looking on the map. If that’s 0, you are looking straight from above. &lt;/p&gt; &lt;p&gt;Now the important the thing about Windows Phone 8 is that the team really went out of their way to make sure code is backwards compatible. That means that not only the new maps control is in the framework, but also Ye Olde Bing Maps control. This can lead to some confusing situations. The important thing to remember when working with the new map control is &lt;/p&gt; &lt;ul&gt; &lt;li&gt;The (old) Bing Maps control stuff is in namespace &lt;strong&gt;Microsoft.Phone.Controls.Maps &lt;/strong&gt; &lt;li&gt;The new map control stuff in in namespace &lt;strong&gt;Microsoft.Phone.Maps.Controls&lt;/strong&gt;.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;So “Controls” and “Maps” are swapped. I always keep in mind “&lt;strong&gt;maps first&lt;/strong&gt;” as a mnemonic to remember which namespace to use. Especially when you are using &lt;a href="http://www.jetbrains.com/resharper/"&gt;ReSharper&lt;/a&gt; or a tool like it that most helpfully offers you to add namespaces and references (again) can really get you caught on the wrong foot, so pay attention.&lt;/p&gt; &lt;p&gt;I started out creating a “New Windows Phone App”, selected OS 8.0 (of course), fired up the Library Package Manager and downloaded my wp7nl library. This gives &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt; and some other stuff I need for my sample. At the moment of this writing this is still Windows Phone 7 code but this will run fine (of course this all will be updated shortly). The only thing you need to take care of is that you &lt;em&gt;delete the references to Windows Phone Controls.dll and Windows Phone Controls.Maps.dll&lt;/em&gt; the package makes.&lt;/p&gt; &lt;p&gt;First step is to make a simple view model describing the cartographic modes the new map control supports:&lt;/p&gt;&lt;pre&gt;using GalaSoft.MvvmLight;
using Microsoft.Phone.Maps.Controls;

namespace MvvmMapDemo1.ViewModels
{
  public class MapMode : ViewModelBase
  {
    private string name;
    public string Name
    {
      get { return name; }
      set
      {
        if (name != value)
        {
          name = value;
          RaisePropertyChanged(() =&amp;gt; Name);
        }
      }
    }

    private MapCartographicMode cartographicMode;
    public MapCartographicMode CartographicMode
    {
      get { return cartographicMode; }
      set
      {
        if (cartographicMode != value)
        {
          cartographicMode = value;
          RaisePropertyChanged(() =&amp;gt; CartographicMode);
        }
      }
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;The main view is basically some properties and a little bit of logic. First part handles the setup and the properties for displaying and selecting the cartographic map modes:&lt;/p&gt;&lt;pre&gt;using System;
using System.Collections.ObjectModel;
using System.Device.Location;
using GalaSoft.MvvmLight;
using Microsoft.Phone.Maps.Controls;

namespace MvvmMapDemo1.ViewModels
{
  public class MapViewModel : ViewModelBase
  {
    public MapViewModel()
    {
      modes = new ObservableCollection&amp;lt;MapMode&amp;gt;
      {
        new MapMode 
          {CartographicMode = MapCartographicMode.Road, Name = "Road"},
        new MapMode 
          {CartographicMode = MapCartographicMode.Aerial, Name = "Aerial"},
        new MapMode 
         {CartographicMode = MapCartographicMode.Hybrid, Name = "Hybrid"},
        new MapMode
         {CartographicMode = MapCartographicMode.Terrain, Name = "Terrain"}
      };
      selectedMode = modes[0];
    }
    
    private MapMode selectedMode;
    public MapMode SelectedMode
    {
      get { return selectedMode; }
      set
      {
        if (selectedMode != value)
        {
          selectedMode = value;
          RaisePropertyChanged(() =&amp;gt; SelectedMode);
        }
      }
    }

    private ObservableCollection&amp;lt;MapMode&amp;gt; modes;
    public ObservableCollection&amp;lt;MapMode&amp;gt; Modes
    {
      get { return modes; }
      set
      {
        if (modes != value)
        {
          modes = value;
          RaisePropertyChanged(() =&amp;gt; Modes);
        }
      }
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;The only important part about this is that there &lt;em&gt;must&lt;/em&gt; be an initially selected mode, as the control does not take it very well if the mode is forcibly set to null by the data binding. &lt;/p&gt;
&lt;p&gt;At little bit more interesting are the next two properties of the view model, which control heading and pitch:&lt;/p&gt;&lt;pre&gt;private double pitch;
public double Pitch
{
  get { return pitch; }
  set
  {
    if (Math.Abs(pitch - value) &amp;gt; 0.05)
    {
      pitch = value;
      RaisePropertyChanged(() =&amp;gt; Pitch);
    }
  }
}

private double heading;
public double Heading
{
  get { return heading; }
  set
  {
    if (value &amp;gt; 180) value -= 360;
    if (value &amp;lt; -180) value += 360;
    if (Math.Abs(heading - value) &amp;gt; 0.05)
    {
      heading = value;
      RaisePropertyChanged(() =&amp;gt; Heading);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;The map seems to try to keep its heading between 0 and 360 degrees, but I like to have the slider in the middle for North position – that way you can use it to rotate the map left and right. So I want heading to be between –180 and +180, which should be functionally equivalent to between 0 and 360 - and apparently I get away with it. Since both values are doubles I don’t do the standard equals but use a threshold value to fire a PropertyChanged. Courtesy of ReSharper suggesting this.&lt;/p&gt;
&lt;p&gt;Then there’s a MapCenter property, that doesn’t do very much in this solution apart from setting the initial map center. I have discovered that the center map does not like being set to null either – this beasty is a bit more picky than the Bing Maps control it seems so I take care to set an initial value:&lt;/p&gt;&lt;pre&gt;private GeoCoordinate mapCenter = new GeoCoordinate(40.712923, -74.013292);
/// &lt;summary&gt;
/// Stores the map center
/// &lt;/summary&gt;
public GeoCoordinate MapCenter
{
  get { return mapCenter; }
  set
  {
    if (mapCenter != value)
    {
      mapCenter = value;
      RaisePropertyChanged(() =&amp;gt; MapCenter);
    }
  }
}
private double zoomLevel = 15;

public double ZoomLevel
{
  get { return zoomLevel; }
  set
  {
    if (zoomLevel != value)
    {
      zoomLevel = value;
      RaisePropertyChanged(() =&amp;gt; ZoomLevel);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Together with the initial ZoomLevel set to 15, this will give you a nice view of Manhattan Island, New York City, USA. There's also a boolean property "Landmarks" that will enable or disable landmarks - you can look that up in the sources if you like.&lt;/p&gt;
&lt;p&gt;Then I opened up Blend, plonked in a map, two sliders, a checkbox on the screen, did some fiddling with grids and stuff, and deleted a lot of auto-generated comments. That made me end up with quite a bit of XAML. I won’t show it all verbatim, but the most important thing is the map itself:&lt;/p&gt;&lt;pre&gt;&amp;lt;maps:Map x:Name="map" 
          CartographicMode="{Binding SelectedMode.CartographicMode,Mode=TwoWay}"
          LandmarksEnabled="{Binding Landmarks,Mode=TwoWay}"
          Pitch="{Binding Pitch, Mode=TwoWay}"
          Heading="{Binding Heading, Mode=TwoWay}" 
          Center="{Binding MapCenter, Mode=TwoWay}"
          ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}"
          Grid.ColumnSpan="2"/&amp;gt;&lt;/pre&gt;
&lt;p&gt;Does not look like exactly rocket science, right? It is not, &lt;em&gt;as long as you make sure the maps namespace is declared as&lt;/em&gt;:&lt;/p&gt;&lt;pre style="font-size: 12px"&gt;xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps" &lt;/pre&gt;
&lt;p&gt;The horizontal slider, controlling the heading, is defined as follows:&lt;/p&gt;&lt;pre&gt;&amp;lt;Slider Minimum ="-180" Maximum="180" Value="{Binding Heading, Mode=TwoWay}"/&amp;gt;&lt;/pre&gt;The vertical slider, controlling the pitch, looks like this: &lt;pre&gt;&amp;lt;Slider Minimum="0" Maximum="75" Value="{Binding Pitch, Mode=TwoWay}" /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Sue me, I took the easy way out and declared the valid ranges in XAML in stead of in my (view) model. But the point of the latter is this: apparently you can only supply ranges between 0 and 75 for pitch. And the pitch is only effective from about level 7 and higher. If you zoom out further, the map just become orthogonal (i.e. viewed straight from above, as if the pitch is 0). This is actually animated if you zoom out using pinch zoom, a very nice visual effect.&lt;/p&gt;
&lt;p&gt;Finally, the list picker controlling which kind of map you see, and the checkbox indicating if the map should show landmarks or not &lt;/p&gt;&lt;pre&gt;&amp;lt;toolkit:ListPicker ItemsSource="{Binding Modes}" 
                    SelectedItem="{Binding SelectedMode, Mode=TwoWay}" 
                    DisplayMemberPath="Name"/&amp;gt;
&amp;lt;CheckBox Content="Landmarks" IsChecked="{Binding Landmarks, Mode=TwoWay}"/&amp;gt;&lt;/pre&gt;
&lt;p&gt;… only I haven’t been able to find any landmarks, not in my hometown Amersfoort, not Berlin nor New York so I suppose this is something that’s not implemented yet ;-)&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/dotnetbyexample/Introducing-the-new-Windows-8-Map-contro_10AF4/CapMap.png"&gt;&lt;img title="CapMap" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: left; padding-top: 0px; padding-left: 0px; margin: 0px 10px 0px 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="CapMap" align="left" src="http://www.schaikweb.net/dotnetbyexample/Introducing-the-new-Windows-8-Map-contro_10AF4/CapMap_thumb.png" width="168" height="127"&gt;&lt;/a&gt;If you fire up this application you will get an immediate error message indicating that you have asked for the map but that you have not selected the right capability for this in the manifest. So double click on “Properties/WMAppManifest.xml” and select ID_CAP_MAP (yeah, the manifest’s got a nice editor too now), and fire up your app. &lt;/p&gt;
&lt;p&gt;And that’s all there is to your first spin with the new Windows Phone map control. It supports data binding – to an extent, and it’s easy to control and embed. Play with the sliders and scroll over the map – it’s amazingly fast and I can assure you it is even more so on actual hardware. Stay tuned: more is coming on this subject!&lt;/p&gt;
&lt;p&gt;Note: I have not touched upon creating and adding map keys to the map in this solution. &lt;a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207033(v=vs.105).aspx" target="_blank"&gt;This procedure is described here.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As usual: download the sample solution &lt;a href="http://www.schaikweb.net/dotnetbyexample/MvvmMapDemo1.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/JWPFE1GH-YE" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-11-15T10:44:54.477+01:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/10/introducing-new-windows-8-map-control.html</feedburner:origLink></item><item><title>A WinRT behavior to start a storyboard on an event</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/mA7PpUZ35So/a-winrt-behavior-to-start-storyboard-on.html</link><category>behavior</category><category>XAML</category><category>Win8nl</category><category>WinRt</category><category>Windows 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 03 Oct 2012 05:36:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-7987039987612823727</guid><description>&lt;p&gt;Sometimes I get a bit distracted. In &lt;a href="http://dotnetbyexample.blogspot.nl/2012/06/reflection-in-winrt-use-x-extensions.html" target="_blank"&gt;this article&lt;/a&gt; I mention a behavior that I wrote which starts a storyboard on an event, I even put in in the &lt;a href="http://win8nl.codeplex.com/" target="_blank"&gt;win8nl&lt;/a&gt; library – and then totally forget to blog about it, or even to announce it. So anyway, when &lt;a href="http://twitter.com/Goofys_Friend" target="_blank"&gt;Danny van Neyghem&lt;/a&gt; asked me about a problem that was almost solved by my behavior, I kinda remembered it, and that I totally forgot about it - and decided a) to improve it and b) to talk about it (well, write).&lt;/p&gt; &lt;p&gt;World, meet StartStoryboardBehavior. It’s a very simple behavior that has the following properties:&lt;/p&gt; &lt;table cellspacing="0" cellpadding="2" width="660" border="0"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top" width="138"&gt;Storyboard&lt;/td&gt; &lt;td valign="top" width="520"&gt;The name of the Storyboard to start. Mandatory.&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="138"&gt;StartImmediately &lt;/td&gt; &lt;td valign="top" width="520"&gt;true = don’t wait for an event to start, just start the storyboard when the behavior is loaded. Optional; default is false&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="138"&gt;EventName&lt;/td&gt; &lt;td valign="top" width="520"&gt;The event of the AttachedObject that will initiate the start of the storyboard (e.g. ‘Click’ on a button). Ignored when StartImmediately&amp;nbsp; == true, mandatory otherwise &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="138"&gt;SearchTopDown&lt;/td&gt; &lt;td valign="top" width="520"&gt;Optional, default is true. If true, the behavior will start to search for your storyboard from the top of the visual tree. This is the scenario in which for instance clicking a button will initiate a storyboard that sits somewhere in the top of the page. If this value is set to false, the behavior will search from the attached object up. Choose this setting when you use the behavior to start a storyboard that’s sitting inside a template.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;“SearchTopDown” was added just yet, and I hope it solves Danny’s problem. For those who just want to use the behavior: &lt;a href="http://nuget.org/packages/Win8nl" target="_blank"&gt;Nuget Win8nl&lt;/a&gt; and you have the behavior armed and ready. I’ve updated the package with the improved behavior already. For those who want to learn – well, it’s not rocket science but read on.&lt;/p&gt; &lt;p&gt;The first part is not so very interesting – just your basic setting up of the behavior, the wiring up and a wiring down of the events. The only interesting things happen in AssociatedObjectLoaded:&lt;/p&gt;&lt;pre&gt;using System;
using System.Linq;
using Windows.UI.Xaml;
using WinRtBehaviors;
using System.Reflection;
using Win8nl.External;
using Windows.UI.Xaml.Media.Animation;
using System.Reactive.Linq;

namespace Win8nl.Behaviors
{
  public class StartStoryboardBehavior : Behavior&amp;lt;FrameworkElement&amp;gt;
  {
    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.Loaded += AssociatedObjectLoaded;
    }
    
    protected override void OnDetaching()
    {
      AssociatedObject.Loaded -= AssociatedObjectLoaded;
      base.OnDetaching();
    }

    private void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
    {
      if (StartImmediately)
      {
        StartStoryboard();
      }

      if (!string.IsNullOrWhiteSpace(EventName))
      {
        var evt = AssociatedObject.GetType().GetRuntimeEvent(EventName);
        if (evt != null)
        {
          Observable.FromEventPattern&amp;lt;RoutedEventArgs&amp;gt;(AssociatedObject, EventName)
            .Subscribe(se =&amp;gt; StartStoryboard());
        }
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;If StartImmediately is true, the storyboard is fired immediately. If not, the behavior tries to find an event with the name supplied in the EventName property and tries to attach a dynamic handler to it using Rx. Nothing new here, &lt;a href="http://dotnetbyexample.blogspot.nl/2012/06/reflection-in-winrt-use-x-extensions.html" target="_blank"&gt;I already described this technique earlier&lt;/a&gt; - in the article where I announced this forgotten behavior :-) &lt;/p&gt;
&lt;p&gt;More interesting is this funny little method, that’s basically one big Linq statement:&lt;/p&gt;&lt;pre style="font-size: 12px"&gt;private Storyboard GetStoryBoardInVisualDescendents(FrameworkElement f)
{
  return f.GetVisualDescendents()
    .Where(p =&amp;gt; p.Resources.ContainsKey(Storyboard) &amp;amp;&amp;amp; p.Resources[Storyboard] is Storyboard)
    .Select(p =&amp;gt; p.Resources[Storyboard] as Storyboard).FirstOrDefault();
}&lt;/pre&gt;
&lt;p&gt;It checks in all visual children’s resources for a storyboard with the name supplied in “Storyboard”, and if so, it selects it. It uses the extension method GetVisualDescendents to generate a list of all the children – all the way to the bottom of the visual tree from the element in “f”.&lt;/p&gt;
&lt;p&gt;As for the behavior’s default behavior (meh), it searches top-down for the storyboard, using this method:&lt;/p&gt;&lt;pre&gt;private void StartStoryboardTopDown()
{
  var root = AssociatedObject.GetVisualAncestors().Last() ?? AssociatedObject;

  var storyboard = GetStoryBoardInVisualDescendents(root);
  if (storyboard != null)
  {
    storyboard.Begin();
  }
}&lt;/pre&gt;
&lt;p&gt;In a nutshell: find the very last top object in the visual tree – that is the root. If that’s null, apparently the current associated object already is the root. Then it starts to search downward for the storyboard and if it finds it, it will fire it.&lt;/p&gt;
&lt;p&gt;For the bottom-up strategy, another method is employed, with a very original name: &lt;/p&gt;&lt;pre&gt;private void StartStoryboardBottomUp()
{
  var root = AssociatedObject;
  Storyboard storyboard;
  do
  {
    storyboard = GetStoryBoardInVisualDescendents(root);
    if (storyboard == null)
    {
      root = root.GetVisualParent();
    }
  } while (root != null &amp;amp;&amp;amp; storyboard == null);

  if (storyboard != null)
  {
    storyboard.Begin();
  }
}&lt;/pre&gt;
&lt;p&gt;This method starts by trying to find the storyboard in the visual tree below the current associated object. If it doesn’t find it, in moves one level up and tries again. And another one. Till it a) finds the storyboard or b) runs out of levels. If a storyboard is found, then it fires it. Okay, so that’s a little inefficient, but it only happens upon firing the event.&lt;/p&gt;
&lt;p&gt;The final pieces of the puzzle is StartStoryboard, which simply selects the method based upon the SearchTopDown value.&lt;/p&gt;&lt;pre&gt;private void StartStoryboard()
{
  if( SearchTopDown)
  {
    StartStoryboardTopDown();
  }
  else
  {
    StartStoryboardBottomUp();
  }
}&lt;/pre&gt;
&lt;p&gt;And that’s all there is to it. I’ve omitted the declaration of the four (attached dependency) properties as that only bulks up this post with no actual value, and the complete listing can be found &lt;a href="http://win8nl.codeplex.com/SourceControl/changeset/view/19620#349522" target="_blank"&gt;here on CodePlex&lt;/a&gt; if that helps you to get overview. &lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/blog/bff069ed72ce_BCF1/Screenshot8.png"&gt;&lt;img title="Screenshot8" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Screenshot8" align="right" src="http://www.schaikweb.net/blog/bff069ed72ce_BCF1/Screenshot8_thumb.png" width="336" height="192"&gt;&lt;/a&gt;For those who love to see the behavior in action I created &lt;a href="http://www.schaikweb.net/dotnetbyexample/StoryBoardDemo.zip" target="_blank"&gt;a little sample app&lt;/a&gt;, which shows a few items in a ListBox. At the end of each row there’s a button, and if you click that the color of three texts to the left is animated from black to red in about a second. That’s a storyboard being fired by the behavior. Very exiting ;-) - but it proves the point.&lt;/p&gt;
&lt;p&gt;Enjoy! I hope this helps you with your &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt; development! Global Availability is coming, get cracking to get your stuff in the store!&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/mA7PpUZ35So" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-10-04T11:00:55.392+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/10/a-winrt-behavior-to-start-storyboard-on.html</feedburner:origLink></item><item><title>Repairing the Windows Phone 7 behavior to show an image background for a search string</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/3FAgBztc7Mg/repairing-windows-phone-7-behavior-to.html</link><category>Rx</category><category>behavior</category><category>Windows Phone 7</category><category>wpdev</category><category>WP7</category><category>Bing Search API</category><category>Reactive</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Sun, 30 Sep 2012 10:25:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-3835048345436615037</guid><description>&lt;p&gt;On the last day of 2011 ago I made &lt;a href="http://dotnetbyexample.blogspot.nl/2011/12/windows-phone-7-behavior-to-show-image.html" target="_blank"&gt;DynamicBackgroundBehavior&lt;/a&gt; - a quite bizarre behavior which plays a supporting role in my latest &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; application “&lt;a href="http://windowsphone.com/s?appid=97382680-f222-47c9-9917-205eabc131b1&amp;amp;ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;What’s cooking&lt;/a&gt;”. It basically shows a picture from a search string as a background, using Bing Image search. Quite neat. Until Microsoft decided to change the Bing Search API a bit. Up until then, it had been a free unlimited ride – since about August you have to buy a package of searches (anything below 5000 searches per month is free). And some more stuff has been changed.&lt;/p&gt; &lt;p&gt;Microsoft provides a nice little C# client library that should solve all of this using an OData protocol. The sad thing is that for the life of it I could not get it to compile on Windows Phone. So I ended up analyzing the PHP (*shudder*) sample in &lt;a href="http://www.bing.com/webmaster/content/developers/ADM_MIGRATION_GUIDE.docx" target="_blank"&gt;this document&lt;/a&gt; – a Word document no less – to see what I needed to do (see page 27 and further).&lt;/p&gt; &lt;p&gt;From a coding perspective, the following details have been changed:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The actual location of the API has been changed from &lt;a href="http://api.bing.net/xml.aspx"&gt;http://api.bing.net/xml.aspx&lt;/a&gt; to &lt;a title="https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image" href="https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image"&gt;https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image&lt;/a&gt;  &lt;li&gt;The schema of the MediaUrl element where the actual image in is returned moved from name space &lt;a href="http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia"&gt;http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia&lt;/a&gt; to name space &lt;a title="http://schemas.microsoft.com/ado/2007/08/dataservices" href="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;http://schemas.microsoft.com/ado/2007/08/dataservices&lt;/a&gt;  &lt;li&gt;It uses an account key in stead of an App id.  &lt;li&gt;The App Id must be send base 64 encoded in the header of the request in stead of in the url as plain text.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Okay. My cheese moved a little. First things first. I need base64 encoded text. Samples of this are on the internet a dime a dozen, I took this one:&lt;/p&gt;&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// Converts string to base64
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="data"&amp;gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
private string Base64Encode(string data)
{
  try
  {
    var encData_byte = new byte[data.Length];
    encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
    return Convert.ToBase64String(encData_byte);
  }
  catch (Exception e)
  {
    throw new Exception("Error in Base64Encode" + e.Message);
  }
}&lt;/pre&gt;
&lt;p&gt;Now the method that does the actual calling of the Bing Search API has changed a little, but not very much:&lt;/p&gt;&lt;pre style="font-size: 10px"&gt;/// &amp;lt;summary&amp;gt;
/// Start the image request using Bing Serach
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="searchString"&amp;gt;&amp;lt;/param&amp;gt;
protected void StartGetFirstImage(string searchString)
{
  if (!string.IsNullOrWhiteSpace(searchString))
  {
    var queryUri =
      string.Format(
        "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query=%27{0}%27&amp;amp;$top=1&amp;amp;$format=Atom",
         HttpUtility.UrlEncode(searchString));
    var request = WebRequest.Create(queryUri) as HttpWebRequest;
    &lt;font color="#ff0000"&gt;request.Headers["Authorization"] = "Basic " + Base64Encode(string.Format("{0}:{0}", BingSearchKey));&lt;/font&gt;
    
    var response =
      Observable.FromAsyncPattern&amp;lt;WebResponse&amp;gt;(
        request.BeginGetResponse, request.EndGetResponse)();
    response.Subscribe(WebClientOpenReadCompleted, WebClientOpenReadError);
  }
}&lt;/pre&gt;
&lt;p&gt;Note the new url. It goes to a different location, the search term must be enclosed by %27 (i.e. the double quote “) and I have to specify a format (Atom). Really interesting is the thing I marked red, for a variety of reasons:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Windows Phone’s Response.Headers collection does not sport the Add method. That stopped me a little, until I realized you could poke directly a new key in the collection by using [“Autorization”] =.&lt;/li&gt;
&lt;li&gt; Now the authentication is Basic, followed by a space, your account key, colon, your key again and that key:key sequence needs to base 64 encoded. Why this is implemented this way – no idea, but it gets your key across – and validated.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;The final thing is that in the callback WebClientOpenReadCompleted I need to use “&lt;a title="http://schemas.microsoft.com/ado/2007/08/dataservices" href="http://schemas.microsoft.com/ado/2007/08/dataservices"&gt;http://schemas.microsoft.com/ado/2007/08/dataservices&lt;/a&gt;” for a namespace,as I already stated.&lt;/p&gt;
&lt;p&gt;And then my little Windows Phone behavior works again. &lt;a href="http://www.schaikweb.net/dotnetbyexample/DynamicBackgroundBehavior.zip" target="_blank"&gt;The fixed version can be downloaded here&lt;/a&gt;. I will fix &lt;a href="http://wp7nl.codeplex.com/" target="_blank"&gt;my #wp7nl library on codeplex&lt;/a&gt; ASAP. &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/3FAgBztc7Mg" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-10-04T11:09:01.132+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/09/repairing-windows-phone-7-behavior-to.html</feedburner:origLink></item><item><title>Data binding shapes to the WinRT Bing Maps control – coming from Windows Phone</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/oxT20gWKGAs/data-binding-shapes-to-winrt-bing-maps.html</link><category>MVVM</category><category>XAML</category><category>Windows Phone 7</category><category>WinRt</category><category>Windows 8</category><category>MVVM Light</category><category>DataBinding</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Wed, 26 Sep 2012 06:15:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-3813829792336782870</guid><description>&lt;p&gt;&lt;em&gt;Disclaimer: this is not a 101 article. It requires understanding of the basic idea about MVVM, data binding, the MVVMLight messenger, and the use of behavior in Windows 8 XAML.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Updated for RTM Bing Maps Control October 3 2012&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.schaikweb.net/blog/2425720ac8ed_12E5B/MVVMLightwp7.png"&gt;&lt;img title="MVVMLightwp7" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="MVVMLightwp7" align="right" src="http://www.schaikweb.net/blog/2425720ac8ed_12E5B/MVVMLightwp7_thumb.png" width="148" height="244"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Introduction&lt;br&gt;&lt;/font&gt;Let me get this straight: I don’t want you to wean off &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; development – far from it. It’s value proposition is great, and it will become much greater still. This article is yet another way to show you how to carry over code and architecture principles between Microsoft’s great tile based operating systems. It’s all about re-using skills and code. C# and XAML code that is.&lt;/p&gt; &lt;p&gt;Those who have attended my talks about this subject during this year, have seen the application to the right popping up. Basically it generates shapes (be it points, lines or polygons) by data binding from ‘business objects’ - using MVVMLight view models. If you tap any of those shapes, a “SelectCommand” on the bound view model will be fired, and the view model will put itself on the MVVMLight Messenger. Some other view model will listen for those messages, and pop up the info window. The app shows gas stations (points), roadblocks (lines) and buildings (shapes). Don’t go look for the gas stations, they are not there and the fuel prices a way bit behind the (expensive) times, the roadblock are all but one fictional as well. Only the buildings are real – location wise that is. Sources of the original Windows Phone (7) application can be found &lt;a href="http://www.schaikweb.net/dotnetbyexample/mvvmmaps.zip" target="_blank"&gt;here&lt;/a&gt;:&lt;/p&gt; &lt;p&gt;&lt;font size="4"&gt;Windows Phone map binding recap&lt;/font&gt;&lt;br&gt;A quick recap: if you want to data bind to a Bing Maps control in Windows Phone, you will go about like this – first, you would define a data template for a layer:&lt;/p&gt;&lt;pre&gt;&amp;lt;DataTemplate x:Key="RoadBlockViewModelTemplate"&amp;gt;
  &amp;lt;Microsoft_Phone_Controls_Maps:MapPolyline Locations="{Binding Geometry}"
                         Stroke="#FF71FF00"
                         StrokeThickness="5"&amp;gt;
    &amp;lt;i:Interaction.Triggers&amp;gt;
      &amp;lt;i:EventTrigger EventName="Tap"&amp;gt;
        &amp;lt;GalaSoft_MvvmLight_Command:EventToCommand 
             Command="{Binding SelectCommand}" /&amp;gt;
      &amp;lt;/i:EventTrigger&amp;gt;
    &amp;lt;/i:Interaction.Triggers&amp;gt;
  &amp;lt;/Microsoft_Phone_Controls_Maps:MapPolyline&amp;gt;
&amp;lt;/DataTemplate&amp;gt;&lt;/pre&gt;This would be able to make a line geometry from a viewmodel containing a “Geometry” attribute containing a LocationCollection object, and an ICommand “SelectCommand” that is executed when the user taps the line. Second, you would make a Bing Maps control, and define a layer like this. &lt;pre&gt;&amp;lt;Microsoft_Phone_Controls_Maps:Map x:Name="map"
    CredentialsProvider="Your-credentials-here"&amp;gt;
  &amp;lt;Microsoft_Phone_Controls_Maps:MapLayer 
     x:Name="MapLayer_RoadBlocks"&amp;gt;
    &amp;lt;Microsoft_Phone_Controls_Maps:MapItemsControl 
      ItemsSource="{Binding RoadBlocks}" 
      ItemTemplate="{StaticResource RoadBlockViewModelTemplate}"/&amp;gt;
  &amp;lt;/Microsoft_Phone_Controls_Maps:MapLayer&amp;gt;
&amp;lt;/Microsoft_Phone_Controls_Maps:Map&amp;gt;;&lt;/pre&gt;
&lt;p&gt;The roadblock view model would look like this: &lt;/p&gt;&lt;pre&gt;using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls.Maps;
using MvvmMaps.Logic.Models.GeoObjects;
using MvvmMaps.Logic.Models.Geometries;
using Wp7nl.Utilities;

namespace MvvmMaps.Logic.ViewModels
{
  public class RoadBlockViewModel : ViewModelBase
  {
    public RoadBlock Model { get; set; }

    // Some code omitted&lt;br&gt;
    [DoNotSerialize]
    public LocationCollection Geometry
    {
      get
      {
        var modelGeom = Model.Location as LineGeometry;
        return modelGeom.GetLocationCollection();
      }

      set
      {
        var modelGeom = Model.Location as LineGeometry;
        modelGeom.SetLocationCollection(value);
      }
    }

    [DoNotSerialize]
    public ICommand SelectCommand
    {
      get
      {
        return new RelayCommand(
            () =&amp;gt; Messenger.Default.Send(this),
            () =&amp;gt; true);
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;Basically it comes down to a Geometry view model property that converts a business object geometry to and from something the Bing Maps control understands – a LocationCollection. This is a named collection that contains objects of type GeoCoordinate – your basic Lat/Lon container. As said above, when you tap select the MVVMLight Messenger just sets off the selected viewmodel, and ‘something’&amp;nbsp; should capture that message and handle it.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Going to Windows 8 – challenges&lt;/font&gt;&lt;br&gt;Now let’s re-use our skills on &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt;. Simply put – in its current state, the data binding support for the &lt;a href="http://visualstudiogallery.msdn.microsoft.com/bb764f67-6b2c-4e14-b2d3-17477ae1eaca?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Bing Maps SDK for Windows Store apps&lt;/a&gt; is pretty easy to describe with one word – non-existent. Some developers immediately go into the ‘blame-and-flame-the-Microsoft-dev-team’ mode when they encounter things like this. I think ‘CodePlex library’. I always see things like this as an intellectual challenge, a chance to contribute to the community, and fortunately there are more people thinking that way. My very smart fellow Dutch developer community member Dave Smits has created &lt;a href="http://bindablemaprt.codeplex.com/" target="_blank"&gt;BindableRTMaps&lt;/a&gt;, which is very useful for binding &lt;em&gt;point&lt;/em&gt; objects – but its shape support is a bit limited. Being a GIS professional and an &lt;a href="http://mvvmlight.codeplex.com/" target="_blank"&gt;MVVMLight&lt;/a&gt; junkie, I want the control to be able to generate geographical elements directly from view models, just like I was able to do in Windows Phone. I solved the data binding issue for shapes using a Behavior based upon my &lt;a href="http://winrtbehaviors.codeplex.com/" target="_blank"&gt;WinRtBehaviors&lt;/a&gt; library. Not quite surprising for those who know me.&lt;/p&gt;
&lt;p&gt;The result can be seen below:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.schaikweb.net/blog/2425720ac8ed_12E5B/Screenshot-9.png"&gt;&lt;img title="Screenshot (9)" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="Screenshot (9)" src="http://www.schaikweb.net/blog/2425720ac8ed_12E5B/Screenshot-9_thumb.png" width="671" height="424"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the center, next to the river, the &lt;a href="http://www.vicrea.nl" target="_blank"&gt;Vicrea&lt;/a&gt; offices, where I work. Say cheese fellows! ;-) As you can see, the shapes are beautifully re-projected when Birds’ Eye View is selected. This is the stuff that makes a GIS buff tick.&lt;/p&gt;
&lt;p&gt;Researching the control I quickly found the following:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;There’s no data binding support at all (as stated) 
&lt;li&gt;The shapes the control draws cannot be templated. They are apparently just projections of something native (as is the map itself). 
&lt;li&gt;There are only two kinds of shapes: MapPolygon and MapPolyline, both descending from MapShape, which in turn descends from DependencyObject – which is very fortunate, as I hope will become clear over the course of this article.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;So I had the challenge to create something that can be put into XAML to still give the designer an amount of control how things appear, without having to resort to code. &lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Introducing MapShapeDrawBehavior&lt;/font&gt;&amp;nbsp;&lt;br&gt;The behavior I created is called MapShapeDrawBehavior&amp;nbsp; (I’ve never been one for original catchy names) and can be used like this:&lt;/p&gt;&lt;pre&gt;&amp;lt;Maps:Map Credentials="Your-credentials-here"&amp;gt;
  &amp;lt;WinRtBehaviors:Interaction.Behaviors&amp;gt;
  
    &amp;lt;MapBinding:MapShapeDrawBehavior 
       LayerName="Roadblocks" 
       ItemsSource="{Binding RoadBlocks, Mode=TwoWay}" 
       TapCommand="SelectCommand" PathPropertyName="Geometry" &amp;gt;
         &amp;lt;MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
           &amp;lt;MapBinding:MapPolylineDrawer Color="Green" Width="10"/&amp;gt;
         &amp;lt;/MapBinding:MapShapeDrawBehavior.ShapeDrawer&amp;gt;
    &amp;lt;/MapBinding:MapShapeDrawBehavior&amp;gt;
  
  &amp;lt;/WinRtBehaviors:Interaction.Behaviors&amp;gt;
&amp;lt;/Maps:Map&amp;gt;&lt;/pre&gt;
&lt;p&gt;For every&lt;em&gt; &lt;/em&gt;category of objects there’s a &lt;em&gt;layer&lt;/em&gt; – which translates to one behavior per list of objects, in this case the road blocks (the green line on the app sceenshot above). Then you need to define three things per layer:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What command in the item view model (in this case, a RoadBlockViewModel) must be fired when a MapShape’s only event – Tap – is called. 
&lt;li&gt;Which property in the item view model contains the &lt;em&gt;Path&lt;/em&gt; – this is the terminology for a MapShape’s collection of points. This is, once again, of type LocationCollection. Only that’s no longer a collection of GeoCoordinate but of &lt;em&gt;Location&lt;/em&gt;. 
&lt;li&gt;Finally, you need to define a &lt;em&gt;drawer&lt;/em&gt;. A drawer is a concept I sucked from my own thumb – it determines how a collection of points is supposed to be transformed to something on the map. It’s my way to make something that’s not templatable more or less configurable.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;I created three drawers out of the box: MapPolylineDrawer, MapPolygonDrawer, and MapStarDrawer. The last one draws a configurable star shaped polygon around a point – since map shapes cannot be points by themselves. A drawer needs only to implement one method:&lt;/p&gt;&lt;pre&gt;public override MapShape CreateShape(object viewModel, LocationCollection path)&lt;/pre&gt;
&lt;p&gt;The basic drawers don’t do anything with the view model: they just take the settings from XAML. But if you want for instance your shapes having different colors based upon some view model property – say you want to color urban areas based upon their crime rate (what we GIS buffs call a &lt;em&gt;thematic map) &lt;/em&gt;– you can write a little custom drawer.&lt;/p&gt;
&lt;p&gt;If you just want to &lt;em&gt;use&lt;/em&gt; the behavior you are done with reading. You can download the &lt;a href="http://www.schaikweb.net/dotnetbyexample/mvvmmapsrt.zip" target="_blank"&gt;demo solution&lt;/a&gt; with code (which, incidentally, shows off a lot of more things than just binding to a map) and start playing around with it. Be aware of the following issues/caveats:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You will need to install the &lt;a href="http://visualstudiogallery.msdn.microsoft.com/bb764f67-6b2c-4e14-b2d3-17477ae1eaca?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Bing Maps SDK for Windows Store apps&lt;/a&gt; first 
&lt;li&gt;When I moved the solution from my Big Black Box to my slate I had to delete and redo all references to Bing.Maps and “Bing Maps for C#, C++, or Visual Basic” (this was using the Beta, I don’t know if that still applies to the RTM version)
&lt;li&gt;The control apparently contains native code, so you cannot build it for Any CPU. 
&lt;li&gt;The designer only works when you build for x86 (this still the case in RTM)&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;For the technically interested I will continue with some gory details.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;The inner guts&lt;/font&gt;&lt;br&gt;The behavior itself is actually pretty big, so I won’t repeat all code verbatim; I will concentrate on the interesting parts.&lt;/p&gt;
&lt;p&gt;First of all, I already mentioned the fact MapShape descends from DependencyObject. That spells ‘Ahoy, Attached Dependency Property ahead!’&amp;nbsp; to me. So I created two of those, one holding the name of the layer (I use those to find out which shapes belong to a single layer) and one in which I &lt;em&gt;store the view model from which the shape was created:&lt;/em&gt;&lt;/p&gt;&lt;pre&gt;using Windows.UI.Xaml;

namespace Win8nl.MapBinding
{
  public static class MapElementProperties
  {
    public static readonly DependencyProperty ViewModelProperty =
         DependencyProperty.RegisterAttached("ViewModel",
         typeof(object),
         typeof(MapElementProperties),
         new PropertyMetadata(default(object)));

    // Called when Property is retrieved
    public static object GetViewModel(DependencyObject obj)
    {
      return obj.GetValue(ViewModelProperty) as object;
    }

    // Called when Property is set
    public static void SetViewModel(
       DependencyObject obj,
       object value)
    {
      obj.SetValue(ViewModelProperty, value);
    }

    public static readonly DependencyProperty LayerNameProperty =
         DependencyProperty.RegisterAttached("LayerName",
         typeof(string),
         typeof(MapElementProperties),
         new PropertyMetadata(default(string)));

    // Called when Property is retrieved
    public static string GetLayerName(DependencyObject obj)
    {
      return obj.GetValue(LayerNameProperty) as string;
    }

    // Called when Property is set
    public static void SetLayerName(
       DependencyObject obj,
       string value)
    {
      obj.SetValue(LayerNameProperty, value);
    }
  }
}&lt;/pre&gt;
&lt;p&gt;The core of the MapShapeDrawBehavior self consists out of just five little methods, and the VERY core method is CreateShape. The behavior iterates over the object list databound to ItemsSource, and calls CreateShape for every view model:&lt;/p&gt;&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// Creates a new shape
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name="viewModel"&amp;gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
private MapShape CreateShape(object viewModel)
{
  var path = GetPathValue(viewModel);
  if (path != null &amp;amp;&amp;amp; path.Any())
  {
    var newShape = CreateDrawable(viewModel, path);
    newShape.Tapped += ShapeTapped;

    MapElementProperties.SetViewModel(newShape, viewModel);
    MapElementProperties.SetLayerName(newShape, LayerName);

    // Listen to property changed event of geometry property to check 
    // if the shape needs tobe redrawed
    var evt = viewModel.GetType().GetRuntimeEvent("PropertyChanged");
    if (evt != null)
    {
      Observable
        .FromEventPattern&amp;lt;PropertyChangedEventArgs&amp;gt;(viewModel, "PropertyChanged")
        .Subscribe(se =&amp;gt;
                     {
                       if (se.EventArgs.PropertyName == PathPropertyName)
                       {
                         ReplaceShape(se.Sender);
                       }
                     });
    }
    return newShape;
  }
  return null;
}&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;First, it reads the view model property that holds the geometry (or at least, it tries that) 
&lt;li&gt;It creates the actual shape 
&lt;li&gt;It attaches an event listener to the “Tapped” event 
&lt;li&gt;It puts the view model and the layer name in attached dependency properties for said shape 
&lt;li&gt;Finally it attaches a property changed listener so that when the property that’s holding the view model’s geometry changes, the ReplaceShape method is called (which replaces the shape on the map – duh)&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;GetPathValue is a simple method that retrieves the view model’s geometry using reflection. Nothing special there:&lt;/p&gt;&lt;pre&gt;private LocationCollection GetPathValue(object viewModel)
{
  if (viewModel != null)
  {
    var dcType = viewModel.GetType();

    var methodInfo = dcType.GetRuntimeMethod("get_" + PathPropertyName, 
                     new Type[0]);
    if (methodInfo != null)
    {
      return methodInfo.Invoke(viewModel, null) as LocationCollection;
    }
  }
  return null;
}&lt;/pre&gt;
&lt;p&gt;CreateDrawable – well that’s VERY simple. Get the drawer and let it decide how the shape will look&lt;/p&gt;&lt;pre&gt;protected virtual MapShape CreateDrawable(object viewModel, LocationCollection path )
{
  var newShape = ShapeDrawer.CreateShape(viewModel, path);
  return newShape;
}&lt;/pre&gt;
&lt;p&gt;And finally ShapeTapped and FireViewModelCommand:&lt;/p&gt;&lt;pre&gt;private void ShapeTapped(object sender, TappedRoutedEventArgs e)
{
  var shape = sender as MapShape;
  if( shape != null )
  {
    var viewModel = MapElementProperties.GetViewModel(shape);
    if( viewModel != null )
    {
      FireViewmodelCommand(viewModel, TapCommand);
    }
  }
}

private void FireViewmodelCommand(object viewModel, string commandName)
{
  if (viewModel != null &amp;amp;&amp;amp; !string.IsNullOrWhiteSpace(commandName))
  {
    var dcType = viewModel.GetType();
    var commandGetter = dcType.GetRuntimeMethod("get_" + commandName, new Type[0]);
    if (commandGetter != null)
    {
      var command = commandGetter.Invoke(viewModel, null) as ICommand;
      if (command != null)
      {
        command.Execute(viewModel);
      }
    }
  }
}&lt;/pre&gt;
&lt;p&gt;ShapeTapped checks if it the object sending the event is actually a shape, then tries to retrieve a view model from the attached dependency property, and calls FireViewModelCommand on it. Which basically is directly ripped from my earlier &lt;a href="http://dotnetbyexample.blogspot.nl/2012/07/a-winrt-behavior-to-mimic-eventtocommand.html" target="_blank"&gt;EventToCommandBehavior&lt;/a&gt;. And then the circle is round again – user taps, view model command is called (just as Laurent Bugnion’s EventToCommand trigger did for Windows Phone) and the view model takes it further just like before. &lt;/p&gt;
&lt;p&gt;There’s more to this behavior, but mostly it’s just reacting to events that occur when the ObservableCollection ItemsSource changes. &lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;Some concluding remarks&lt;br&gt;&lt;/font&gt;Of course this behavior was geared to make the code I already had as much reusable as possible, but I think the way WinRT XAML apps and Windows Phone apps can be put together are remarkably similar – provided you make good use of MVVM and keep your code as clean as possible. So what did I have to do to move over my business and view model code to get this working? Well not very much, actually.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A tiny thing in my model library because I was so clever to use a BackgroundWorker somewhere in my models – which is not supported in WinRt 
&lt;li&gt;The Gas station view model was changed to do the conversion form business object geometry to Bing Maps’ Location in stead of the converter I originally - because my solution does not support converters. 
&lt;li&gt;I had to change some name spaces and data types. Mainly GeoCoordinate was now called Location. 
&lt;li&gt;Oh yeah – in stead of "clr-namespace" I had to use "using" for declaring namespaces in XAML. I used ReSharper toalt-enter trough the errors and add the namespaces almost automatically.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And that was about &lt;em&gt;it&lt;/em&gt;. Of course, the code in it was quite trivial, but still. On the XAML side things were a bit more complicated:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Converters and Attached Dependency Properties were carried over with minimal changes. 
&lt;li&gt;I had to trash my geometry templates and had to write the behavior to emulate the templates – in a way, which admittedly was no small feat. But that’s a hole that only needs to be plugged once, and can now act as a base for possible better solutions. 
&lt;li&gt;I had to do some fiddling around with the DataTemplateSelector – that works a wee bit different, and will be subject of a future blog post. 
&lt;li&gt;‘Tombstoning’ works a bit differently, but quite analogous. &lt;a href="http://dotnetbyexample.blogspot.nl/2012/07/using-provisional-port-of.html" target="_blank"&gt;Been there, done that, wrote the blogpost&lt;/a&gt;. 
&lt;li&gt;The App Bar on Windows 8 has a &lt;em&gt;lot&lt;/em&gt; more possibilities. And – thank Saint Sinofsky and his minions – it supports data binding out of the box. Moving from Windows Phone app bars to Windows 8 app bars is quite easy. Provided you used the BindableApplicationbar and MVVM of course ;-)&amp;nbsp; &lt;li&gt;I kinda 1:1 copied the data window (the popup with alphanumeric data that appears when you tap a shape) – that worked remarkably well, but you might want to do something about the styling for a real-world application. The data window is a wee bit small now and does fit in styling wise ;-)&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;This is still a work in progress, but I think for basic shape data binding this is already very usable. The Bing Maps control is &lt;em&gt;very&lt;/em&gt; fast, courtesy of native code, no doubt. I hope this will help people.&lt;/p&gt;
&lt;p&gt;Once again, for those who don’t feel scrolling all the way up: &lt;a href="http://www.schaikweb.net/dotnetbyexample/mvvmmapsrt.zip" target="_blank"&gt;the source code&lt;/a&gt;. Also updated for RTM. Enjoy!&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/oxT20gWKGAs" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-10-03T21:45:13.510+02:00</atom:updated><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/09/data-binding-shapes-to-winrt-bing-maps.html</feedburner:origLink></item><item><title>A WinRT behavior to turn a FlipView into a kind of Windows 8 Panorama</title><link>http://feedproxy.google.com/~r/blogspot/dotnetbyexample/~3/Qa_yG8hJHq0/a-winrt-behavior-to-turn-flipview-into.html</link><category>behavior</category><category>Win8nl</category><category>WinRt</category><category>Windows 8</category><category>dotnetmag</category><author>noreply@blogger.com (Joost van Schaik)</author><pubDate>Fri, 10 Aug 2012 13:50:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-5295746446529817470.post-1662020199302629958</guid><description>&lt;a href="http://lh5.ggpht.com/-0fuBgrwWG08/UCVz_nsRlLI/AAAAAAAAJ9o/Utej8D2XTAU/s1600-h/IC4258136.jpg"&gt;&lt;img align="right" alt="IC425813" border="0" height="202" src="http://lh4.ggpht.com/-Bt9L9FvU5kU/UCV0AbeF7yI/AAAAAAAAJ9s/swl07epR3JU/IC425813_thumb4.jpg?imgmax=800" style="background-image: none; border-width: 0px; display: inline; float: right; padding-left: 0px; padding-right: 0px; padding-top: 0px;" title="IC425813" width="269" /&gt;&lt;/a&gt;&lt;strong&gt;(UPDATED for RTM August 18 2012)&lt;/strong&gt; &lt;br /&gt;
One of the most beautiful controls of &lt;a href="http://www.microsoft.com/windowsphone/?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows Phone&lt;/a&gt; is the Panorama. It’s ideal for showing a lot related content on a small screen and enable the user to easily pan trough it. A visual cue for ‘there is more’ is provided by showing a little part of the next panel to the very right of the current data. A typical example is showed right.&lt;br /&gt;
&lt;br /&gt;
It’s also one of the most abused controls (guilty as charged Your Honor), but still I wanted to port &lt;a href="http://catalog.zune.net/v3.2/en-US/apps/48fd8097-f07e-e011-986b-78e7d1fa76f8/primaryImage?width=100&amp;amp;height=100&amp;amp;resize=true&amp;amp;ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Catch’em Birds&lt;/a&gt; to &lt;a href="http://windows.microsoft.com/en-US/windows-8/release-preview?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;Windows 8&lt;/a&gt; – and I found out there was no ready-to-use control. After fighting with ScrollViewers and GridViewers and whatnot I came to this very simple behavior, which basically takes a FlipView and hammers it into a kind of Panorama.&lt;br /&gt;
&lt;br /&gt;
Now the FlipView is designed to be a full-screen control so the behavior basically walks past all the items in the FlipView, shrinks them horizontally by a configurable percentage of the screen, and displaces the ‘next’ panel a little to the left (making it appear at the right side of the screen on the current panel). To make this look a little bit more fast and fluid, I have made the displacement itself animated, so that the ‘next’ screen not so much snaps as &lt;em&gt;glides&lt;/em&gt; into view. The overall effect looks pretty nice to me. I hope Microsoft will think so as well, as my app is up for an App Excellence Lab soon ;-)&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: left;"&gt;
&lt;object class="BLOGGER-youtube-video" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" data-thumbnail-src="http://i.ytimg.com/vi/fdWNnMayuDk/0.jpg" height="532" width="640"&gt;&lt;param name="movie" value="http://www.youtube.com/v/fdWNnMayuDk?version=3&amp;f=user_uploads&amp;c=google-webdrive-0&amp;app=youtube_gdata" /&gt;&lt;param name="bgcolor" value="#FFFFFF" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;embed width="640" height="532"  src="http://www.youtube.com/v/fdWNnMayuDk?version=3&amp;f=user_uploads&amp;c=google-webdrive-0&amp;app=youtube_gdata" type="application/x-shockwave-flash" allowfullscreen="true"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/div&gt;
In my app it looks like this. I still lack a decent screen recorder for Windows 8, so I took out the video camera&lt;br /&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:6ed5f125-690a-4d16-aab7-3bbd3ef5b2a1" style="display: inline; float: none; margin: 0px; padding: 0px;"&gt;
&lt;div class="wlWriterSmartContent" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:6ed5f125-690a-4d16-aab7-3bbd3ef5b2a1" style="display: inline; float: none; margin: 0px; padding: 0px;"&gt;
&lt;br /&gt;
So this behavior, most originally called “FlipViewPanoramaBehavior” is of course based upon my earlier &lt;a href="http://winrtbehaviors.codeplex.com/" target="_blank"&gt;WinRtBehaviors&lt;/a&gt; CodePlex project. It starts out like this, with the following dependency properties:&lt;br /&gt;
&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Win8nl.External;
using Win8nl.Utilities;
using WinRtBehaviors;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;

namespace Win8nl.Behaviors
{
  /// &amp;lt;summary&amp;gt;
  /// A behavior to turn a FlipView into a kind of panorama
  /// &amp;lt;/summary&amp;gt;
  public class FlipViewPanoramaBehavior : Behavior&amp;lt;FlipView&amp;gt;
  {
    #region AnimationTime

    /// &amp;lt;summary&amp;gt;
    /// AnimationTime Property name
    /// &amp;lt;/summary&amp;gt;
    public const string AnimationTimePropertyName = "AnimationTime";

    public int AnimationTime
    {
      get { return (int)GetValue(AnimationTimeProperty); }
      set { SetValue(AnimationTimeProperty, value); }
    }

    /// &amp;lt;summary&amp;gt;
    /// AnimationTime Property definition
    /// &amp;lt;/summary&amp;gt;
    public static readonly DependencyProperty AnimationTimeProperty = 
      DependencyProperty.Register(
        AnimationTimePropertyName,
        typeof(int),
        typeof(FlipViewPanoramaBehavior),
        new PropertyMetadata(250));

    #endregion

    #region NextPanelScreenPercentage

    /// &amp;lt;summary&amp;gt;
    /// NextPanelScreenPercentage Property name
    /// &amp;lt;/summary&amp;gt;
    public const string NextPanelScreenPercentagePropertyName = 
      "NextPanelScreenPercentage";

    public double NextPanelScreenPercentage
    {
      get { return (double)GetValue(NextPanelScreenPercentageProperty); }
      set { SetValue(NextPanelScreenPercentageProperty, value); }
    }

    /// &amp;lt;summary&amp;gt;
    /// NextPanelScreenPercentage Property definition
    /// &amp;lt;/summary&amp;gt;
    public static readonly DependencyProperty NextPanelScreenPercentageProperty = 
      DependencyProperty.Register(
        NextPanelScreenPercentagePropertyName,
        typeof(double),
        typeof(FlipViewPanoramaBehavior),
        new PropertyMetadata(10.0));
    #endregion
  }
}&lt;/pre&gt;
So “AnimationTime” is the number of milliseconds the behavior takes to glide the next panel into view, and NextPanelScreenPercentage is an indication of how much screen real estate the next panel will take. Nothing special here yet.&lt;br /&gt;
&lt;br /&gt;
If I want to muck around with a FlipView contents, I first have to &lt;em&gt;find&lt;/em&gt; these contents. With some breakpoints and watches I found out I could use the following code to find the FlipViewItems:&lt;br /&gt;
&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// Find all Flip view items
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
private List&amp;lt;FlipViewItem&amp;gt; GetFlipViewItems()
{
  var grid = AssociatedObject.GetVisualChildren().FirstOrDefault();
  if (grid != null)
  {
    return grid.GetVisualDescendents().OfType&amp;lt;FlipViewItem&amp;gt;().ToList();
  }
  return null;
}&lt;/pre&gt;
Attentive readers might observe that neither GetVisualChildren nor GetVisualDescendents are part of the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx?ocid=aff-n-we-loc--ITPRO40939&amp;amp;WT.mc_id=aff-n-we-loc--ITPRO40939" target="_blank"&gt;WinRT&lt;/a&gt; api, which is perfectly correct – they come from the &lt;a href="http://dotnetbyexample.blogspot.nl/2012/04/porting-dragflickbehavior-from-windows.html" target="_blank"&gt;VisualTreeHelperExtensions I ported from Windows Phone some time ago&lt;/a&gt;. Don’t start to download this stuff and build it together yourself – wait till the end and I will show the lazy way to do this.&lt;br /&gt;
&lt;br /&gt;
Anyway – I wanted to move the FlipView’s contents &lt;em&gt;fluently&lt;/em&gt;. That means I will use some Storyboards to work on Translations. So we identify the contents of each FlipViewItem and set its &lt;em&gt;fist visual child’s &lt;/em&gt;Rendertransform to CompositeTransform, if that’s not already present:&lt;br /&gt;
&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// At compositions transforms to every item within every flip view item
/// &amp;lt;/summary&amp;gt;
private void AddTranslates()
{
  var items = GetFlipViewItems();
  if (items != null &amp;amp;&amp;amp; items.Count &amp;gt; 1)
  {
    foreach (var item in items)
    {
      var firstChild = item.GetVisualChild(0);
      if (!(firstChild.RenderTransform is CompositeTransform))
      {
        firstChild.RenderTransform = new CompositeTransform();
        firstChild.RenderTransformOrigin = new Point(0.5, 0.5);
      }
    }
  }
}&lt;/pre&gt;
&lt;em&gt;This assumes every FlipViewItem contains just one child.&lt;/em&gt; You better make sure it does for this to work, so put a Grid around it if you need more than one thing to sit in there.&lt;br /&gt;
&lt;br /&gt;
Now the core of the whole behavior is this one piece of code:&lt;br /&gt;
&lt;pre&gt;/// &amp;lt;summary&amp;gt;
/// Does the actual repositioning and sizing of the items displayed in the Flipview
/// &amp;lt;/summary&amp;gt;
private void SizePosFlipViewItems()
{
  AddTranslates(); &lt;strong&gt;// &amp;lt;-- moved from AssociatedObjectLoaded for RTM&lt;/strong&gt;
  var size = AssociatedObject.ActualWidth*(NextPanelScreenPercentage/100);
  var shift = size - 15;

  var items = GetFlipViewItems();
  if (items != null &amp;amp;&amp;amp; items.Count &amp;gt; 1)
  {
    // Make all items a bit smaller and make sure they are aligned left
    foreach (var item in items)
    {
      item.GetVisualChild(0).HorizontalAlignment = HorizontalAlignment.Left;
      item.GetVisualChild(0).Width = items[0].ActualWidth - size;
    }

    var selectedIndex = AssociatedObject.SelectedIndex;

    if (selectedIndex &amp;gt; 0)
    {
      StartTranslateStoryBoard(0, 0, 
                               items[selectedIndex - 1].GetVisualChild(0), 0);
    }

    StartTranslateStoryBoard(0, 0, items[selectedIndex].GetVisualChild(0), 
                             AnimationTime);

    if (selectedIndex + 1 &amp;lt; items.Count)
    {
      StartTranslateStoryBoard(-shift, 0,
                                items[selectedIndex + 1].GetVisualChild(0), 
                                AnimationTime);
    }
  }
}
&lt;/pre&gt;
First it calculates the new size of the FlipViewItems, and then it calculates how much it can shift the ‘next panel’ – basically, how much room is there between this panel and the next. This is currently a hard coded number, but feel free to make that a property as well ;-). &lt;br /&gt;
&lt;br /&gt;
Then, for every FlipViewItem it makes the first visual child “size” smaller, and makes sure it’s aligned to the left (so space comes free and the right side). Then:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;It moves the panel that just disappeared to the left (if any) back&amp;nbsp; to it’s normal position, in no time (i.e. not animated – it’s invisible to the leftanyway, so why bother).
&lt;li&gt;It moves the &lt;em&gt;current&lt;/em&gt; panel to its normal position, but it animates it. This is because if it’s moved in from the left, it moves a bit too far, as you might have noticed in the movie – so it glides back
&lt;li&gt;It moves the &lt;em&gt;next&lt;/em&gt; panel (if any) a little bit to the left – animated, so it glides into view on the right hand side of the screen.&lt;/li&gt;
&lt;/li&gt;
&lt;/li&gt;
&lt;/ol&gt;
Now of course there is the slight matter of the method that make the storyboards to make it happen:&lt;br /&gt;
&lt;pre&gt;private static void StartTranslateStoryBoard(double desiredX, double desiredY, 
                                             FrameworkElement fe, int time)
{
  var translatePoint = fe.&lt;u&gt;GetTranslatePoint&lt;/u&gt;();
  var destinationPoint = new Point(desiredX, desiredY);
  if (destinationPoint.&lt;u&gt;DistanceFrom&lt;/u&gt;(translatePoint) &amp;gt; 1)
  {
    var storyboard = new Storyboard { FillBehavior = FillBehavior.HoldEnd };
    storyboard.&lt;u&gt;AddTranslationAnimation&lt;/u&gt;(
         fe, translatePoint, destinationPoint,
         new Duration(TimeSpan.FromMilliseconds(time)),
         new CubicEase { EasingMode = EasingMode.EaseOut });
    storyboard.Begin();
  }
}&lt;/pre&gt;
Once again, I use some extension methods from code ported from Windows Phone in &lt;a href="http://dotnetbyexample.blogspot.nl/2012/04/porting-dragflickbehavior-from-windows.html" target="_blank"&gt;the article I mentioned before&lt;/a&gt;, I underlined them to make them distinguishable from the standard API. Basically: this method accepts a FrameworkElement and moves it to a desired position in a desired time, using a storyboard that animates a translation. That is to say, unless it is already &lt;em&gt;in&lt;/em&gt; that desired position. I think I will make this into a separate extension method in a utilities library one day but for the moment it’s doing fine. &lt;br /&gt;
&lt;br /&gt;
All that’s left now is some wiring up, I cobbled that all together in one code block:&lt;br /&gt;
&lt;pre&gt;protected override void OnAttached()
{
  AssociatedObject.Loaded += AssociatedObjectLoaded;
  base.OnAttached();
}
protected override void OnDetaching()
{
  AssociatedObject.Loaded -= AssociatedObjectLoaded;
  AssociatedObject.SelectionChanged -= AssociatedObjectSelectionChanged;
  AssociatedObject.SizeChanged -= AssociatedObjectSizeChanged;
}

private void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
{
  //AddTranslates(); deleted for RTM
  SizePosFlipViewItems();
  AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
  AssociatedObject.SizeChanged += AssociatedObjectSizeChanged;
}

private async void AssociatedObjectSelectionChanged(object sender, 
                                                    SelectionChangedEventArgs e)
{
  await Task.Delay(250); // Updated after bug report from SCPRedMage
  SizePosFlipViewItems();
}

private async void AssociatedObjectSizeChanged(object sender, 
                                               SizeChangedEventArgs e)
{
  await Task.Delay(250);
  SizePosFlipViewItems();
}&lt;/pre&gt;
OnAttached and OnDetaching do their usual basic wiring and unwiring of events. &lt;br /&gt;
When the AssociatedObject (i.e. the FlipView) is first loaded the FlipViewItems’ first child gets their CompositeTransforms, then the initial screen layout is created by calling SizePosFlipViewItems. Then two events are wired up:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;SelectionChanged
&lt;li&gt;SizeChanged &lt;/li&gt;
&lt;/li&gt;
&lt;/ul&gt;
Now the first one is logical – when the user selects the next panel (i.e. he scrolls it in from the left or right) the panels need to be arrange again so that the newly selected panel stays in view (it scrolls too much to the right, remember) and the ‘new’ next panel comes into view at the left hand side of the screen.&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;The SizeChanged intercept is necessary for when the user rotates his screen or snaps the application. &lt;/em&gt;For then the size of the screen changes, and the portion of the screen that the next panel may use is considerably smaller – in pixels. In my app this is taken care of by a Visual State Manager that listens to page events – basically something stolen from the LayoutAwarePage that’s in every template project – &lt;em&gt;but that takes a while&lt;/em&gt;. Now I know I am going to be lambasted for this (and I have a pretty good idea by whom), but to solve this the SizeChanged handler waits a bit for actually calling SizePosFlipViewItems. And to prevent UI blocking I interestingly abused Task.Delay for that. It’s crude, but it works. As you may have seen in the movie when I snapped the app.&lt;br /&gt;
&lt;br /&gt;
So there you have it. The code works, you have seen it in action. Its usage is ridicilously simple: make a FlipView, add items, and add this behavior to the FlipView. Done. You can download the the behavior &lt;a href="http://win8nl.codeplex.com/SourceControl/changeset/view/18472#349520" target="_blank"&gt;here&lt;/a&gt; but you will need quite some base libs to get it working – as it uses a lot of my &lt;a href="http://win8nl.codeplex.com/" target="_blank"&gt;win8nl&lt;/a&gt; library on CodePlex. If you want to go the easy and quick way: just &lt;a href="http://nuget.org/packages/Win8nl" target="_blank"&gt;use the Win8nl NuGet package&lt;/a&gt;. That will get you the behavior and all the prerequisites, including MVVMLight.&lt;br /&gt;
&lt;br /&gt;
Be aware that win8nl now uses the Reactive extensions. They are included in the NuGet package and they will come with it as a dependency&lt;br /&gt;
&lt;br /&gt;
UPDATE: Please note there is a tiny code change since original publication: due to Microsoft optimizing the FlipView not all elements are initially loaded, so the check if every FlipViewItem child has a CompositeTransform has to performed at &lt;em&gt;every&lt;/em&gt; manipulation. &lt;/div&gt;
&lt;br /&gt;
UPDATE 2: There's a tiny update to AssociatedObjectSelectionChanged. And those who want a simple working sample, download the sources from codeplex and fire up FlipViewTest.XAML as the start page.
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/blogspot/dotnetbyexample/~4/Qa_yG8hJHq0" height="1" width="1"/&gt;</description><atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2012-11-14T08:09:32.798+01:00</atom:updated><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/-Bt9L9FvU5kU/UCV0AbeF7yI/AAAAAAAAJ9s/swl07epR3JU/s72-c/IC425813_thumb4.jpg?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">8</thr:total><feedburner:origLink>http://dotnetbyexample.blogspot.com/2012/08/a-winrt-behavior-to-turn-flipview-into.html</feedburner:origLink></item></channel></rss>
