<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jesse Liberty &#187; WindowsPhone</title>
	<atom:link href="http://jesseliberty.com/Tags/phone/feed/" rel="self" type="application/rss+xml" />
	<link>http://jesseliberty.com</link>
	<description>Code To Live. Live To Code.</description>
	<lastBuildDate>Tue, 31 Jan 2012 17:18:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Coming In Mango&#8211;ICommand</title>
		<link>http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/</link>
		<comments>http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/#comments</comments>
		<pubDate>Mon, 02 May 2011 13:47:24 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Data]]></category>
		<category><![CDATA[Essentials]]></category>
		<category><![CDATA[Mango]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[Patterns & Skills]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/</guid>
		<description><![CDATA[Mango From Scratch As noted in earlier posts, Mango represents a move from Silverlight 3+ to Silverlight 4, and with that comes ICommand on ButtonBase and Hyperlink (and classes that derive from these two).&#160; This is a significant breakthrough, especially &#8230; <a href="http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>Mango From Scratch</strong></p>
<p>As noted in earlier posts, Mango represents a move from Silverlight 3+ to Silverlight 4, and <a href="http://jesseliberty.com/wp-content/uploads/2011/05/ICommand.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top: 0px; border-right: 0px; padding-top: 0px" title="ICommand" border="0" alt="ICommand" align="right" src="http://jesseliberty.com/wp-content/uploads/2011/05/ICommand_thumb.jpg" width="133" height="244"/></a> with that comes ICommand on ButtonBase and Hyperlink (and classes that derive from these two).&nbsp; </p>
<p>This is a significant breakthrough, especially if you are programming with <a href="http://jesseliberty.com/2010/05/08/mvvm-its-not-kool-aid-3/">MVVM</a>.&nbsp;&nbsp; </p>
<p>ICommand allows you to <em>bind</em> an action as a property, thus keeping a clean separation from the controlling class (typically the view model) to the presentation class (typically the view).&nbsp; </p>
<p><span id="more-4634"></span>
<p>To see this at work, we’ll create a program that retrieves data from a (pseudo-) web service, and displays that data when a button is pushed.&nbsp; </p>
<p>To do this, I created a new program in Mango. The Xaml consists of a button (Load) and a list box (initially empty).&nbsp; I opted to put a white border on the list box so that it acts as a placeholder.</p>
<p>The heart of the program sits in DelegateCommand.cs where I implement ICommand. </p>
<p>In his <a href="http://johnpapa.net/5-simple-steps-to-commanding-in-silverlight">excellent article on ICommand</a> John Papa describes 5 steps for Commanding in Silverlight, and I followed the five steps exactly to do the same in Windows Phone. What worked in Silverlight now works in the Phone.</p>
<p>John says, <strong>Step 1: Implement ICommand</strong> – that is,&nbsp; implement the interface, which I do in the DelegateCommand class.</p>
<pre class="brush: csharp; toolbar: false;">using System;
using System.Windows.Input;

namespace ICommandPhone
{
   public class DelegateCommand : ICommand
   {
      Func&lt;object, bool&gt; canExecute;
      Action&lt;object&gt; executeAction;
      bool canExecuteCache;

      public DelegateCommand(
            Action&lt;object&gt; executeAction,
            Func&lt;object, bool&gt; canExecute )
      {
         this.executeAction = executeAction;
         this.canExecute = canExecute;
      }

      public bool CanExecute( object parameter )
      {
         bool temp = canExecute( parameter );

         if ( canExecuteCache != temp )
         {
            canExecuteCache = temp;
            if ( CanExecuteChanged != null )
            {
               CanExecuteChanged( this, new EventArgs() );
            }
         }

         return canExecuteCache;
      }

      public event EventHandler CanExecuteChanged;

      public void Execute( object parameter )
      {
         executeAction( parameter );
      }
   }
}
</pre>
<p>&nbsp;</p>
<p>Key here is that the Silverlight code works as is. In fact, that is true throughout this program.&nbsp; The only changes for the phone have to do with layout on the MainPage. </p>
<p>The ViewModel class is named BookViewModel, which derives ViewModelBase, which, in turn, implements INotifyPropertyChanged.</p>
<p><strong>Step 2 – Define the Command</strong></p>
<p>In the ViewModel I define the ICommand that I’ll be implementing</p>
<pre class="brush: csharp; toolbar: false;">public ICommand LoadBooksCommand { get; set; }
</pre>
<p>&nbsp;</p>
<p><strong>Step 3 – Create The Command</strong></p>
<p>Again, I do this in the ViewModel, this time in the constructor. </p>
<pre class="brush: csharp; toolbar: false;">LoadBooksCommand = new DelegateCommand( LoadBooks, CanLoadBooks );
</pre>
<p>&nbsp;</p>
<p>While I’m in the constructor, I also mimic the creation of data that would normally be retrieved from, e.g., a web service,</p>
<pre class="brush: csharp; toolbar: false;">public BookViewModel()
{
   Books = new ObservableCollection&lt;Book&gt;();

   AllBooks = new ObservableCollection&lt;Book&gt;();
   AllBooks.Add( new Book { ID = 1, Name = "Programming Rx and Linq" } );
   AllBooks.Add( new Book { ID = 2, Name = "Migrating Windows Phone" } );
   AllBooks.Add( new Book { ID = 3, Name = "Programming C#" } );
   AllBooks.Add( new Book { ID = 4, Name = "Learning C#" } );
   AllBooks.Add( new Book { ID = 5, Name = "Visual C# Notebook" } );
   AllBooks.Add( new Book { ID = 6, Name = "Learning VB.Net" } );
   AllBooks.Add( new Book { ID = 7, Name = "Programming .NET" } );
   AllBooks.Add( new Book { ID = 8, Name = "Programming ASP.NET" } );
   AllBooks.Add( new Book { ID = 9, Name = "TY C++ In 21 Days" } );
   AllBooks.Add( new Book { ID = 10, Name = "TY C++ In 24 Hours" } );
   AllBooks.Add( new Book { ID = 11, Name = "TY C++ In 10 Minutes" } );
   AllBooks.Add( new Book { ID = 12, Name = "Clouds To Code" } );
   AllBooks.Add( new Book { ID = 13, Name = "Beginning OOAD" } );
   AllBooks.Add( new Book { ID = 14, Name = "XML Web Classes From Scratch" } );
   AllBooks.Add( new Book { ID = 15, Name = "C++ From Scratch" } );
   AllBooks.Add( new Book { ID = 16, Name = "Web Classes Fronm Scratch" } );

   }
</pre>
<p><strong>Step 4 – Create the VM </strong></p>
<p>We are now ready to bind the Command property of the Button to the LoadBooksCommand shown above (which in turn, will invoke the LoadBooks method).&nbsp; To do this, we must tell the View what its ViewModel is.&nbsp; Still following John, I took the expedient of using a Resource in the View,</p>
<pre class="brush: csharp; toolbar: false;">&lt;phone:PhoneApplicationPage.Resources&gt;
    &lt;local:BookViewModel
       x:Key="vm" /&gt;
 &lt;/phone:PhoneApplicationPage.Resources&gt;
</pre>
<p>&nbsp;</p>
<p>I then set this ViewModel to be the DataContext for the StackPanel that holds the Button,</p>
<pre class="brush: csharp; toolbar: false;">&lt;StackPanel
   DataContext="{StaticResource vm}"
</pre>
<p>&nbsp;</p>
<p><strong>Step 5 – Bind the Command</strong></p>
<p>Finally, in the button itself, I make the link to the LoadBooksCommand,</p>
<pre class="brush: csharp; toolbar: false; highlight: [5];">&lt;Button
  Name="LoadButton"
  Content="Load"
  Margin="5"
  Command="{Binding LoadBooksCommand}" /&gt;
</pre>
<p>With that, when the button is pressed, the LoadBooksCommand is invoked through the ICommand mechansim, causing the LoadBooks method in the VM to be invoked,</p>
<pre class="brush: csharp; toolbar: false;">private void LoadBooks( object param )
{
   string filter = param as string ?? string.Empty;
   Books.Clear();
   var query = from p in this.AllBooks
               where p.Name.ToLower().StartsWith( filter.ToLower() )
               select p;
   foreach ( var item in query )
   {
      this.Books.Add( item );
   }
}
</pre>
<p>As you can see from the illustration at the top of this posting, it works exactly as expected; the view contains a button, the codebehind for that view is empty, and we’ve bound the clicking of that button to the Command property in the View Model.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Application Bar Buttons Are Null</title>
		<link>http://jesseliberty.com/2011/03/28/application-bar-buttons-are-null/</link>
		<comments>http://jesseliberty.com/2011/03/28/application-bar-buttons-are-null/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 11:15:00 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Essentials]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/03/28/application-bar-buttons-are-null/</guid>
		<description><![CDATA[Windows Phone From Scratch #50 In a recent posting, I demonstrated how easy it is to add buttons to the phone’s Application Bar. I went back to that application to disable the “faster” button when the maximum speed was reached. &#8230; <a href="http://jesseliberty.com/2011/03/28/application-bar-buttons-are-null/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #50</a></p>
<p>In a <a href="http://jesseliberty.com/2011/03/22/adding-an-application-bar/">recent posting</a>, I demonstrated how easy it is to add buttons to the phone’s Application Bar. </p>
<p>I went back to that application to disable the “faster” button when the maximum speed was reached. I named the button and then tried to access that button in code. Much to my surprise, the button was null. It was always null. </p>
<p><span id="more-4499"></span>
<p>I’ve recently been turning to search rather than to the standard documentation as my first line of defense when I run into unexpected problems.&#160; Thus, I entered “Windows Phone Application Bar Button Null” into <em>Bing</em> and the first result was a <a href="http://geekswithblogs.net/lbugnion/archive/2010/06/08/two-small-issues-with-windows-phone-7-applicationbar-buttons-and.aspx">wonderful article</a> on this very issue written by Laurent Bugnion (author of MVVM Light).&#160; </p>
<p>He solves the problem elegantly, and I won’t repeat his work here, but I will walk you through the changes I made to the program.</p>
<p>I first opened the program and, following Laurent’s suggestion, I created an enumeration for the two buttons that were in place,</p>
<pre class="brush: csharp; toolbar: false;">public enum ButtonTypes
{
   Slower = 0,
   Faster = 1
}</pre>
<p>&#160;</p>
<p>I created a method that retrieves the button from the ApplicationBar’s Buttons property, using an index and casting the result to be of type ApplicationBarIconButton.</p>
<pre class="brush: csharp; toolbar: false;"> public ApplicationBarIconButton GetButton(
       ButtonTypes whichButton )
 {
    return ApplicationBar.Buttons[(int) whichButton]
       as ApplicationBarIconButton;
 }</pre>
<p>Having retrieved the button, I could now set it to disabled if conditions were correct</p>
<pre class="brush: csharp; toolbar: false;">if ( currentTS &lt;= new TimeSpan( 0, 0, 0, 0, INCREMENT ) )
{
   GetButton( ButtonTypes.Faster ).IsEnabled = false;
}
else
{
   GetButton( ButtonTypes.Faster ).IsEnabled = true;
}</pre>
<p>Problem solved, and quickly, thanks to Bing and Laurent.&#160; </p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/03/28/application-bar-buttons-are-null/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Double Dutch Double Touch</title>
		<link>http://jesseliberty.com/2011/03/25/double-dutch-double-touch/</link>
		<comments>http://jesseliberty.com/2011/03/25/double-dutch-double-touch/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 12:50:46 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[Patterns & Skills]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/03/25/double-dutch-double-touch/</guid>
		<description><![CDATA[Windows Phone From Scratch #49 In my previous posting, I demonstrated how to register a touch (or tap) on Windows Phone. Today I will extend that to implement Double-Touch. To begin, I need to go back to the original Touch &#8230; <a href="http://jesseliberty.com/2011/03/25/double-dutch-double-touch/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #4</a>9</p>
<p>In my <a href="http://jesseliberty.com/2011/03/24/windows-phone-touch/">previous posting</a>, I demonstrated how to register a touch (or tap) on Windows <a href="http://jesseliberty.com/wp-content/uploads/2011/03/DoubleTouch.png"><img style="background-image: none; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; padding-top: 0px; border: 0px;" title="DoubleTouch" src="http://jesseliberty.com/wp-content/uploads/2011/03/DoubleTouch_thumb.png" border="0" alt="DoubleTouch" width="202" height="240" align="right" /></a> Phone. Today I will extend that to implement Double-Touch.</p>
<p>To begin, I need to go back to the original Touch class and make two changes: the OnTouch method needs to be changed to protected (from private) and needs to be marked virtual so that I can override it in a derived class.</p>
<p><span id="more-4494"></span></p>
<p>To get started, re-open the Toucher project, and make these two changes in TouchAction.cs.  Next, create a new class, DoubleTouchAction, that derives from TouchAction:</p>
<pre class="brush: csharp; toolbar: false;">using System;

namespace Toucher
{
   public class DoubleTouchAction : TouchAction</pre>
<p>Give your new class its own event (DoubleTouch) and a private nullable-DateTime object to hold the time of the initial touch. We’ll compare that time with the time of the second touch, and if it is within a second we’ll consider that to be a double-touch.</p>
<pre class="brush: csharp; toolbar: false;">public class DoubleTouchAction : TouchAction
{
   public event EventHandler DoubleTouch;
   const int INTERVAL = 1;

   private DateTime? TimeOfFirstTouch { get; set; }</pre>
<p>The heart of this class is in the overridden OnTouch method which begins by calling the base method (to pick up the Touch) and then compares the time of the touch with the time of the first touch.  If there is no time (the DateTime has no value) or if the time between touches exceeds one second then the time of the first touch is reset to the current time, otherwise the event is called.</p>
<pre class="brush: csharp; toolbar: false;">protected override void OnTouch( )
{
   base.OnTouch( );

   if ( TimeOfFirstTouch.HasValue &amp;&amp;
         DateTime.Now &lt; TimeOfFirstTouch +
         TimeSpan.FromSeconds( INTERVAL ) )
   {
      OnDoubleTouch( );
      TimeOfFirstTouch = null;
   }
   else
   {
      TimeOfFirstTouch = DateTime.Now;
   }
}</pre>
<p>The event just checks to make sure that someone has registered to receive the event and then calls the event on the AssociatedObject as you saw in the earlier version,</p>
<pre class="brush: csharp; toolbar: false;">private void OnDoubleTouch( )
{
   if ( DoubleTouch != null )
   {
      DoubleTouch( AssociatedObject, EventArgs.Empty );
   }
}</pre>
<p>&nbsp;</p>
<p>You can now return to Blend to wire up the behavior, or if you like,, open MainPage.xaml and just copy the form of the behavior from the existing one:</p>
<pre class="brush: csharp; toolbar: false;"> &lt;Custom:Interaction.Behaviors&gt;
    &lt;local:TouchAction
       x:Name="TouchActionBehavior"
       Touch="TouchActionBehavior_Touch" /&gt;
    &lt;local:DoubleTouchAction
       x:Name="DoubleTouchActionBehavior"
       DoubleTouch="DoubleTouchActionBehavior_DoubleTouch" /&gt;
 &lt;/Custom:Interaction.Behaviors&gt;</pre>
<p>&nbsp;</p>
<p>You can now go to the code behind file and add a handler for the DoubleTouch,</p>
<pre class="brush: csharp; toolbar: false;">private void TouchActionBehavior_Touch(
   object sender, System.EventArgs e )
{
   //System.Windows.MessageBox.Show(
   //   "You touched the panel!" );
}

private void DoubleTouchActionBehavior_DoubleTouch
   ( object sender, System.EventArgs e )
{
   System.Windows.MessageBox.Show(
      "You double-touched the panel!" );
}</pre>
<p>&nbsp;</p>
<p>While you need not comment out the message box on the first touch, you do have to be quick to register the second touch in under a second.  Commenting out the message box makes this easier.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/03/25/double-dutch-double-touch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Conway&#8217;s Life In the Marketplace</title>
		<link>http://jesseliberty.com/2011/03/23/conways-life-in-the-marketplace/</link>
		<comments>http://jesseliberty.com/2011/03/23/conways-life-in-the-marketplace/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 21:57:02 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[WindowsPhone]]></category>
		<category><![CDATA[Marketplace]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/03/23/conways-life-in-the-marketplace/</guid>
		<description><![CDATA[I’m pleased to report that the first iteration of Conway’s Life, documented here, is now in the marketplace.  [ Updated March 24 with Faster/Slower Buttons ] Following the conventional rules of Conway’s Game Of Life, the screen is divided into &#8230; <a href="http://jesseliberty.com/2011/03/23/conways-life-in-the-marketplace/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I’m pleased to report that the first iteration of <a href="http://social.zune.net/redirect?type=phoneApp&amp;id=5a08cc90-0b51-e011-854c-00237de2db9e">Conway’s Life</a>, documented <a href="http://jesseliberty.com/2011/03/18/coding-for-fun-conways-life/">here</a>, is now in the marketplace. <strong> [ Updated March 24 with Faster/Slower Buttons ]</strong></p>
<p>Following the conventional rules of <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway’s Game Of Life</a>, the screen is divided into cells. Each generation a cell dies of loneliness if it has fewer than 2 neighbors, or of overcrowding if it has more than 3 neighbors.  Live cells stay alive with 2-3 neighbors, and dead cells come to life with 3 neighbors.</p>
<p><a href="http://social.zune.net/redirect?type=phoneApp&amp;id=5a08cc90-0b51-e011-854c-00237de2db9e"><img style="background-image: none; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; padding-top: 0px; border: 0px;" title="wp7_278x92_green" src="http://jesseliberty.com/wp-content/uploads/2011/03/wp7_English_278x92_green.png" border="0" alt="wp7_278x92_green" width="278" height="92" align="right" /></a></p>
<p>Click on the image to download to your phone or to Zune. (Free)</p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/03/23/conways-life-in-the-marketplace/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Testing Network Availability</title>
		<link>http://jesseliberty.com/2011/03/10/testing-network-availability/</link>
		<comments>http://jesseliberty.com/2011/03/10/testing-network-availability/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 14:26:15 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Essentials]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[WindowsPhone]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/03/10/testing-network-availability/</guid>
		<description><![CDATA[Windows Phone From Scratch #42 &#160; We would like to live in a world in which any time you turn  your phone on the network is there, full strength.  We’d also like to live in a world of peace and &#8230; <a href="http://jesseliberty.com/2011/03/10/testing-network-availability/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h5><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #42</a></h5>
<p>&nbsp;</p>
<p>We would like to live in a world in which any time you turn  your phone on the <a href="http://jesseliberty.com/wp-content/uploads/2011/03/helloworld.jpg"><img style="background-image: none; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; padding-top: 0px; border-width: 0px;" title="helloworld" src="http://jesseliberty.com/wp-content/uploads/2011/03/helloworld_thumb.jpg" border="0" alt="helloworld" width="162" height="240" align="right" /></a> network is there, full strength.  We’d also like to live in a world of peace and harmony.</p>
<p>Until all of this is accomplished, however, you will need to test for network availability and handle those unfortunate moments when the network is not available.</p>
<p>To do so, you can call upon two useful features of the NetworkInformation namespace: the NetworkAddressChanged event and the GetIsNetworkAvailable method.</p>
<p><span id="more-4428"></span></p>
<p>To see these at work, create a new application that will consist of a TextBox centered in the content panel. Here’s the Xaml,</p>
<pre class="brush: csharp; toolbar: false; ">&lt;phone:PhoneApplicationPage
   x:Class="NetowrkAvailability.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"
   mc:Ignorable="d"
   d:DesignWidth="480"
   d:DesignHeight="768"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   SupportedOrientations="Portrait"
   Orientation="Portrait"
   shell:SystemTray.IsVisible="True"&gt;

  &lt;Grid
      x:Name="LayoutRoot"
      Background="Transparent"&gt;
      &lt;Grid.RowDefinitions&gt;
         &lt;RowDefinition
            Height="Auto" /&gt;
         &lt;RowDefinition
            Height="*" /&gt;
      &lt;/Grid.RowDefinitions&gt;

      &lt;StackPanel
         x:Name="TitlePanel"
         Grid.Row="0"
         Margin="12,17,0,28"&gt;
         &lt;TextBlock
            x:Name="ApplicationTitle"
            Text="Network Availability"
            Style="{StaticResource PhoneTextNormalStyle}" /&gt;
         &lt;TextBlock
            x:Name="PageTitle"
            Text="Hello, World?"
            Margin="9,-7,0,0"
            Style="{StaticResource PhoneTextTitle1Style}" /&gt;
      &lt;/StackPanel&gt;

       &lt;Grid
         x:Name="ContentPanel"
         Grid.Row="1"
         Margin="12,0,12,0"&gt;

         &lt;TextBox
            Name="Message"
            Background="Yellow"
            Text="Unknown"
            VerticalAlignment="Center"
            HorizontalAlignment="Center" /&gt;

      &lt;/Grid&gt;
   &lt;/Grid&gt;
&lt;/phone:PhoneApplicationPage&gt;</pre>
<p>&nbsp;</p>
<p>Our goal, of course, is to change the text and background color of the Textbox when the network status changes.  We’ve initialized it to yellow in case we can’t determine the status, but in the constructor we’ll immediately test whether or not we’re on line and set it accordingly.</p>
<p>We begin by setting up an event handler which will respond every time the network status changes,</p>
<pre class="brush: csharp; toolbar: false;">public MainPage( )
{
   InitializeComponent( );
   NetworkChange.NetworkAddressChanged +=
      new NetworkAddressChangedEventHandler(
           NetworkChange_NetworkAddressChanged );

}

private void NetworkChange_NetworkAddressChanged(
    object sender, EventArgs e )
{
   CheckNetworkAvailability( );
}</pre>
<p>We then create a method to check whether or not the network is available</p>
<pre class="brush: csharp; toolbar: false;"> private void CheckNetworkAvailability( )
 {
    networkIsAvailable =
       Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable( );
    SetNetworkIndication( );
 }</pre>
<p>Finally, we set the background color and the message on the TextBox to correspond to the current state.</p>
<pre class="brush: csharp; toolbar: false;"> private void SetNetworkIndication( )
 {
    if ( networkIsAvailable )
    {
       Message.Text = "Online";
       Message.Background =
          new SolidColorBrush( Colors.Green );
    }
    else
    {
       Message.Text = "Offline";
       Message.Background =
         new SolidColorBrush( Colors.Red );
    }
 }</pre>
<p>&nbsp;</p>
<p>Here is the complete source code, for context:</p>
<pre class="brush: csharp; toolbar: false; ">using System;
using System.Net.NetworkInformation;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace NetowrkAvailability
{
   public partial class MainPage : PhoneApplicationPage
   {
      private bool networkIsAvailable;

      public MainPage( )
      {
         InitializeComponent( );
         NetworkChange.NetworkAddressChanged +=
            new NetworkAddressChangedEventHandler( NetworkChange_NetworkAddressChanged );
         CheckNetworkAvailability( );
      }

      private void NetworkChange_NetworkAddressChanged( object sender, EventArgs e )
      {
         CheckNetworkAvailability( );
      }

      private void SetNetworkIndication( )
      {
         if ( networkIsAvailable )
         {
            Message.Text = "Online";
            Message.Background = new SolidColorBrush( Colors.Green );
         }
         else
         {
            Message.Text = "Offline";
            Message.Background = new SolidColorBrush( Colors.Red );
         }
      }

      private void CheckNetworkAvailability( )
      {
         networkIsAvailable =
            Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable( );
         SetNetworkIndication( );
      }
   }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/03/10/testing-network-availability/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Silverlight Unit Test For Phone</title>
		<link>http://jesseliberty.com/2011/03/08/silverlight-unit-test-for-phone/</link>
		<comments>http://jesseliberty.com/2011/03/08/silverlight-unit-test-for-phone/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 13:18:57 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Essentials]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[SL Unit Tests]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/03/08/silverlight-unit-test-for-phone/</guid>
		<description><![CDATA[Windows Phone From Scratch #41 &#160; There has been some confusion about how to make the Silverlight Unit Tests work on Windows Phone.&#160; The latest release of the Silverlight Unit Tests comes with the Silverlight Toolkit, and it targeted at &#8230; <a href="http://jesseliberty.com/2011/03/08/silverlight-unit-test-for-phone/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #41 </a></h3>
<p>&#160;</p>
<p>There has been some confusion about how to make the Silverlight Unit Tests work on <a href="http://jesseliberty.com/wp-content/uploads/2011/03/FAILEDUNITTEST.jpg"><img style="background-image: none; border-right-width: 0px; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="FAILEDUNITTEST" border="0" alt="FAILEDUNITTEST" align="right" src="http://jesseliberty.com/wp-content/uploads/2011/03/FAILEDUNITTEST_thumb.jpg" width="132" height="240" /></a>Windows Phone.&#160; The latest release of the <a href="http://archive.msdn.microsoft.com/silverlightut">Silverlight Unit Tests</a> comes with the <a href="http://silverlight.codeplex.com/">Silverlight Toolkit</a>, and it targeted at Silverlight 4.&#160; Windows Phone is based on an enhanced version of Silverlight 3 and cannot use these DLLs. </p>
<p>Fortunately, Jeff Willcox has made the right DLLs available <a href="http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/">on his web site</a>. </p>
<p><a href="http://media.jeff.wilcox.name/blog/ut/SL3_UTF_May.zip"><strong>Silverlight 3 binaries for the Silverlight Unit Test Framework</strong></a>     </p>
<p><span id="more-4415"></span>
<p>&#160;</p>
<p>You will need to ‘unblock’ the zip file before unpacking the files. These binaries are strong named, but are <em>not</em> Authenticode signed, <em>so they are not official</em></p>
<p>To get started, follow these steps:</p>
<ul>
<li>Make sure Visual Studio 2010 is installed </li>
<li>Download, unblock and install the Silverlight Unit Tests </li>
<li>Create a new Windows Phone project </li>
<li>Add references to the two DLLs
<ul>
<li>Microsoft.Silverlight.Testing </li>
<li>Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight </li>
</ul>
<ul>Be sure to put the unit tests inside the same project as the project you are testing, though it is good programming practice to isolate the tests in their own folder and namespace.</ul>
<ul>Be sure to add using statements in each file that must recognize the testing framework (certainly in mainpage.xaml.cs) for the two DLLs</ul>
<ul>
<pre class="brush: csharp; toolbar: false;">using Microsoft.Phone.Controls;
using Microsoft.Silverlight.Testing;</pre>
</ul>
<ul></ul>
<ul></ul>
<ul></ul>
<ul></ul>
</li>
</ul>
<p>&#160;</p>
<p>Jeff Willcox has provided the following excellent way to turn on and off the unit testing by flipping a boolean in MainPage.xaml.&#160; </p>
<p>&#160;</p>
<p><em></em></p>
<pre class="brush: csharp; toolbar: false;"> public MainPage( )
 {
    InitializeComponent( );

    const bool runUnitTests = true;

    if ( runUnitTests )
    {
       Content = UnitTestSystem.CreateTestPage( );
       IMobileTestPage imtp =
                Content as IMobileTestPage;

       if ( imtp != null )
       {
          BackKeyPress += ( x, xe ) =&gt; xe.Cancel =
                  imtp.NavigateBack( );
       }
    }
 }</pre>
<p>&#160;</p>
<p>In essence, if the boolean is true, then the unit tests become the content of the main page.&#160; </p>
<p>For an excellent step by step walk through on creating your first unit tests, I highly&#160; recommend David Gadd’s tutorial <em><a href="http://codingsolutions.blogspot.com/2010/03/windows-phone-7-tdd-kata-using-mvvm-and.html">Building a Windows Phone 7 app with MVVM pattern, using TDD and mock objects</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/03/08/silverlight-unit-test-for-phone/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Full Stack 8&#8211;Adding Search to the Phone Client</title>
		<link>http://jesseliberty.com/2011/02/25/the-full-stack-8adding-search-to-the-phone-client/</link>
		<comments>http://jesseliberty.com/2011/02/25/the-full-stack-8adding-search-to-the-phone-client/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 18:09:48 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Full Stack]]></category>
		<category><![CDATA[WindowsPhone]]></category>
		<category><![CDATA[FullStack]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/02/25/the-full-stack-8adding-search-to-the-phone-client/</guid>
		<description><![CDATA[Part 8 in the Full Stack series in which Jon and I are building an entire application from conception to delivery that includes MVC 3 ASP.NET, Silverlight and Windows Phone. Also available on Channel 9]]></description>
			<content:encoded><![CDATA[<p>Part 8 in the Full Stack series in which Jon and I are building an entire application from conception to delivery that includes MVC 3 ASP.NET, Silverlight and Windows Phone.</p>
<p> <object type="application/x-silverlight-2" data="data:application/x-silverlight-2," width="512" height="288"><param name="minRuntimeVersion" value="4.0.50401.0" /><param name="source" value="http://channel9.msdn.com/scripts/Channel9.xap?v=1.5" /><param name="initParams" value="mediaurl=http://files.ch9.ms/ch9/64ef/7a831c9c-5f1d-4166-91c1-9e94018264ef/TheFullStack8.ism/manifest,thumbnail=http://media.ch9.ms/ch9/64ef/7a831c9c-5f1d-4166-91c1-9e94018264ef/TheFullStack8_512_ch9.jpg,deliverymethod=adaptivestreaming,autoplay=false,entryid=7a831c9c5f1d416691c19e94018264ef" /></object>
<p>Also available on <a href="http://channel9.msdn.com/Series/The-Full-Stack">Channel 9</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/02/25/the-full-stack-8adding-search-to-the-phone-client/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sterling DB on top of Isolated Storage &#8211; 2</title>
		<link>http://jesseliberty.com/2011/02/24/sterling-db-on-top-of-isolated-storage-2/</link>
		<comments>http://jesseliberty.com/2011/02/24/sterling-db-on-top-of-isolated-storage-2/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 15:12:41 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Patterns & Skills]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/02/24/sterling-db-on-top-of-isolated-storage-2/</guid>
		<description><![CDATA[Windows Phone From Scratch #39 &#160; In yesterday’s posting we looked at the Sterling Database. and how to set up and initialize tables, store an retrieve data.&#160; Today we’ll build on that to set up the database in App.xaml so &#8230; <a href="http://jesseliberty.com/2011/02/24/sterling-db-on-top-of-isolated-storage-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #39</a></h3>
<p>&#160;</p>
<p>In yesterday’s posting we looked at the <a href="http://www.sterlingdatabase.com/">Sterling Database</a>. and how to set up and initialize tables, store an retrieve data.&#160; Today we’ll build on that to set up the database in App.xaml so that we can handle tombstoning.</p>
<p>  <span id="more-4390"></span>
<p>The key change to yesterday’s program is that rather than initializing the database in the main page, we’ll do so in App.xaml.&#160; To see this at work, create a new Windows Phone application.&#160; </p>
<p>We’ll use the exact same Xaml as we did yesterday, creating a text block and a button. This time, however, open App.xaml.cs to create the sret up code.&#160; We’ll start by creating two static member variables, one private and one public,</p>
<pre class="brush: csharp; toolbar: false;">private static ISterlingDatabaseInstance _database = null;
private static SterlingEngine _engine = null;</pre>
<p>We need a public static property to obtain the underlying database:</p>
<pre class="brush: csharp; toolbar: false;">public static ISterlingDatabaseInstance Database
{
   get
   {
      return _database;
   }
}</pre>
<p>Create&#160; private helper methods to activate and deactivate the database (yesterday we dispensed with deactivation to keep things simpler)</p>
<pre class="brush: csharp; toolbar: false;">private void _ActivateEngine( )
{
   _engine = new SterlingEngine( );
   _engine.Activate( );
   _database =
      _engine.SterlingDatabase.
      RegisterDatabase&lt;TestDB&gt;( );
}

private void _DeactivateEngine( )
{
   _engine.Dispose( );
   _database = null;
   _engine = null;
}</pre>
<p>This references the same database definition (TestDB) that you created yesterday.&#160; Note that Dispose (in _DeactiveEngine) also flushes to isolated storage.</p>
<p>Add a call to _ActivateEngine in both Application_Launching and Application_Activated, and a call to _DeactiveEngine in both Application_Deactivated and Application_Closing.</p>
<p>After re-creating the Customer class and TestDB, you can turn to MainPage.cs and remove all the initialization code, and change all the calls to the database itself to use the static property (e.g., </p>
<pre class="brush: csharp; toolbar: false;"> private void SaveCustomer( )
 {
    var key =
       App.Database.Save( cust );
    App.Database.Flush( );
 }</pre>
<p>&#160;</p>
<p>You end up with cleaner usage of the database, and the assurance that the database will be properly flushed on tombstoning and restored when the application resumes.</p>
<p>Nice.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/02/24/sterling-db-on-top-of-isolated-storage-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>When Isolated Storage Isn&#8217;t Enough</title>
		<link>http://jesseliberty.com/2011/02/23/when-isolated-storage-isnt-enough/</link>
		<comments>http://jesseliberty.com/2011/02/23/when-isolated-storage-isnt-enough/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 14:03:55 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Patterns & Skills]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Isolated Storage]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[Windows Phone]]></category>
		<category><![CDATA[WindowsPhone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/02/23/when-isolated-storage-isnt-enough/</guid>
		<description><![CDATA[Windows Phone From Scratch #38 When you wish to persist state across usages of your application, Isolated Storage allows you to write to the disk and stash away key-value pairs.  For state, this is usually sufficient, but if what you &#8230; <a href="http://jesseliberty.com/2011/02/23/when-isolated-storage-isnt-enough/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3><a href="http://jesseliberty.com/windows-from-scratchindex/">Windows Phone From Scratch #38</a></h3>
<p>When you wish to persist state across usages of your application, Isolated Storage allows you to write to the disk and stash away key-value pairs.  For state, this is usually sufficient, but if what you wish to persist is data, especially relational data, then Isolated Storage is a bit limiting.</p>
<p>To meet this need for a more robust data storage scheme, a number of libraries have been developed that work on top of isolated storage.  This posting is the first in a series that will examine these options; beginning with the <a href="http://www.sterlingdatabase.com/">Sterling Database</a>.</p>
<p><span id="more-4385"></span></p>
<p>The <a href="http://www.sterlingdatabase.com/">home page</a> for the Sterling Database states that the goal of Sterling is to be non-intrusive, lightweight, flexible and portable.  The list of features is extensive and there is very good documentation, though it isn’t always obvious (or it wasn’t to me) how to get your first database up and running.</p>
<p>To begin, download Sterling from <a href="http://sterling.codeplex.com/">Codeplex</a>.  There are two ways to install, just the dll’s or the entire source code.  If you use the source code, just include the project into your solution and put a reference in your main project to the Sterling project.</p>
<p>You can also install Sterling on a per-project basis using NuGet.  To do so, create a new Windows Phone 7 project and right click on the references and choose <em>Add Library Package Reference</em>. Click on On-Line and then in the search box write Sterling, as shown in the figure</p>
<p><a href="http://jesseliberty.com/wp-content/uploads/2011/02/NuGetSterling.jpg"><img style="background-image: none; margin: 10px 0px 10px 10px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="NuGetSterling" src="http://jesseliberty.com/wp-content/uploads/2011/02/NuGetSterling_thumb.jpg" border="0" alt="NuGetSterling" width="640" height="428" /></a></p>
<p>Remember that NuGet installs on a per-project basis.</p>
<p>Let’s create the simplest possible UI to demonstrate storage and retrieval of information. Here’s the complete Xaml:</p>
<pre class="brush: xml; toolbar: false;">&lt;phone:PhoneApplicationPage
&lt;!-- headers elided --&gt;
&gt;

   &lt;Grid
      x:Name="LayoutRoot"
      Background="Transparent"&gt;
      &lt;Grid.RowDefinitions&gt;
         &lt;RowDefinition
            Height="Auto" /&gt;
         &lt;RowDefinition
            Height="*" /&gt;
      &lt;/Grid.RowDefinitions&gt;

      &lt;StackPanel
         x:Name="TitlePanel"
         Grid.Row="0"
         Margin="12,17,0,28"&gt;
         &lt;TextBlock
            x:Name="ApplicationTitle"
            Text="Database Storage"
            Style="{StaticResource PhoneTextNormalStyle}" /&gt;
         &lt;TextBlock
            x:Name="PageTitle"
            Text="Sterling"
            Margin="9,-7,0,0"
            Style="{StaticResource PhoneTextTitle1Style}" /&gt;
      &lt;/StackPanel&gt;

      &lt;Grid
         x:Name="ContentPanel"
         Grid.Row="1"
         Margin="12,0,12,0"&gt;

         &lt;StackPanel&gt;
            &lt;TextBlock
               Name="Message"
               Text="Hello"
               HorizontalAlignment="Center"
               VerticalAlignment="Center" /&gt;
            &lt;Button
               Name="Test"
               Content="Test"
               Height="Auto"
               Width="100" /&gt;
         &lt;/StackPanel&gt;

      &lt;/Grid&gt;
   &lt;/Grid&gt;
&lt;/phone:PhoneApplicationPage&gt;</pre>
<p>Create three member variables at the top of your code-behidn page. The first two will be for registration of the Database engine and an instance of the database, and the third will be an instance of the Customer class that we’ll create,</p>
<pre class="brush: csharp; toolbar: false;">private SterlingEngine _engine;
private ISterlingDatabaseInstance _databaseInstance;
private Customer cust;</pre>
<p>The customer class will serve as the data we want to store. Its only requirement is that each instance of Customer have a unique ID,</p>
<pre class="brush: csharp; toolbar: false;">public class Customer
{
   public int CustomerID { get; set; }
   public string CustomerName { get; set; }
}</pre>
<p>You also need a class that derives from BaseDatabaseInstance. We’ll call our class TestDB.  The requirement is that you override the Name property and the _RegisterTables method.  The latter is where you will define each table for your database in terms of each class,</p>
<pre class="brush: csharp; toolbar: false;">public class TestDB : BaseDatabaseInstance
{
   public override string Name
   {
      get
      {
         return "TestDB";
      }
   }

   protected override List&lt;ITableDefinition&gt;
                         _RegisterTables( )
   {
      return new List&lt;ITableDefinition&gt;( )
      {
         CreateTableDefinition&lt;Customer, int&gt;(
                   k =&gt; k.CustomerID)
      };
   }
}</pre>
<p>CreateTableDefinition takes the name of the class and the type of the key. You pass in a lambda expression that resolves to the unique key.  It is also possible to define indices at this point, but to keep this first example simple, we’ll not implement anything unless it is absolutely required.</p>
<p>In the PageLoaded event we’ll register the click event, and call three methods. The first will start up the Sterling database, the second will create an instance of Customer and the third will store that instance in the database,</p>
<pre class="brush: csharp; toolbar: false; "> public MainPage( )
 {
    InitializeComponent( );
    Loaded +=
       new RoutedEventHandler( MainPage_Loaded );
 }

 private void MainPage_Loaded(
    object sender, RoutedEventArgs e )
 {
    Test.Click +=
       new System.Windows.RoutedEventHandler(
          Test_Click );
    StartSterling( );
    CreateCustomer( );
    SaveCustomer( );
 }</pre>
<p>StartSterling is boilerplate code for starting up the database,</p>
<pre class="brush: csharp; toolbar: false;">private void StartSterling( )
{
   _engine = new SterlingEngine( );
   _engine.Activate( );
   _databaseInstance =
      _engine
      .SterlingDatabase
      .RegisterDatabase&lt;TestDB&gt;( );
}</pre>
<p>Create Customer instantiates the Customer class we created earlier and assigns the instance to the member variable. Save customer calls _databaseInstance.Save passing in the customer, and we follow that call with a call to Flush() to flush the queue to storage.</p>
<pre class="brush: csharp; toolbar: false;">private void CreateCustomer( )
{
   cust = new Customer( )
   {
      CustomerID = 1,
      CustomerName = "John Doe"
   };
}

private void SaveCustomer( )
{
   var key =
      _databaseInstance.Save( cust );
   _databaseInstance.Flush( );
}</pre>
<p>Notice that all you do to save the data is call Save and Sterling takes care of the rest.  You do not interact with isolated storage directly at all.</p>
<p>We’ll wire up the button to call Load on the database instance, passing in the customer ID (in this case hard-wired) and then we’ll retrieve the Customer name from the loaded record and display that in the TextBlock,</p>
<pre class="brush: csharp; toolbar: false;">private void Test_Click(
   object sender,
   RoutedEventArgs e )
{
   var customer =
      _databaseInstance
      .Load&lt;Customer&gt;( 1 );
   var name = customer.CustomerName;
   Message.Text = name;
}</pre>
<p>The net effect is that when  you click the button the customer is retrieved from the database and the name is displayed.</p>
<p><em><span style="font-size: x-small;">Special thanks to Michael Washington and Jeremy Likness for their help in getting me started with Sterling.</span></em></p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/02/23/when-isolated-storage-isnt-enough/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Reactive Drag and Drop Part 2</title>
		<link>http://jesseliberty.com/2011/02/21/reactive-drag-and-drop-part-2/</link>
		<comments>http://jesseliberty.com/2011/02/21/reactive-drag-and-drop-part-2/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 12:22:00 +0000</pubDate>
		<dc:creator>Jesse Liberty</dc:creator>
				<category><![CDATA[Linq]]></category>
		<category><![CDATA[Mini-Tutorial]]></category>
		<category><![CDATA[Reactive]]></category>
		<category><![CDATA[WindowsPhone]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://jesseliberty.com/2011/02/21/reactive-drag-and-drop-part-2/</guid>
		<description><![CDATA[Reactive Programming, Posting # 7 In Part 1 of this 2 part posting we looked at capturing the mouse movements.&#160; The key code in Part 1 was, var q = from start in mousedown from pos in mousemove.StartWith( start ) &#8230; <a href="http://jesseliberty.com/2011/02/21/reactive-drag-and-drop-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong><em><a href="http://jesseliberty.com/reactive-extensions-rx/">Reactive Programming</a>, Posting # 7</em></strong></p>
<p>In <a href="http://jesseliberty.com/2011/02/11/reactive-drag-and-drop-part-1/">Part 1</a> of this 2 part posting we looked at capturing the mouse movements.&#160; The key code in Part 1 was,</p>
<pre class="brush: csharp; toolbar: false;">var q = from start in mousedown
        from pos in mousemove.StartWith( start )
        .TakeUntil( mouseup )
        select pos;</pre>
<p>Now, in part 2, rather than just getting the coordinates of the mouse, we want to find the delta so that we can move the image with the changes in the mouse position.&#160; </p>
<p><span id="more-4371"></span></p>
<table border="2" cellspacing="0" cellpadding="3" width="500">
<tbody>
<tr>
<td valign="top" width="500">Part 1 was written for WPF, but as was pointed out by Jim Wooley in a comment on part 1, the same code can be written for Silverlight or Windows Phone by modifying the MouseDown to MouseLeftButtonDown and MouseUp to MouseLeftButtonUp.</td>
</tr>
</tbody>
</table>
<p>For Windows Phone, make sure that you add a reference to <em>Microsoft Phone Reactive</em> and to <em>System Observable</em> and for ths program, you’ll need to ensure that you have using statements for <em>Microsoft.Phone.Reactive, System.Windows.Input, System.Windows.Controls </em>and <em>System.Linq</em>.</p>
<p>We’ll begin by redefining mouseDown and MouseUp</p>
<pre class="brush: csharp; toolbar: false;">var mousedown = from evt in Observable.FromEvent
                   &lt;MouseButtonEventArgs&gt;(
                   image, &quot;MouseLeftButtonDown&quot; )
                select evt.EventArgs.GetPosition( image );
var mouseup = from evt in Observable.FromEvent
                 &lt;MouseButtonEventArgs&gt;(
                 this, &quot;MouseLeftButtonUp&quot; )
              select evt.EventArgs.GetPosition(
              this );

var mousemove = from evt in Observable.FromEvent
                   &lt;MouseEventArgs&gt;(
                   this, &quot;MouseMove&quot; )
                select evt.EventArgs.GetPosition(
                   this );</pre>
<p>Notice that mousedown and mouseup use the MouseLeftButtonDown and MouseLeftButtonUp events, respectively and that mousedown sets the image as the source of the event</p>
<p>We are using a select statement on mouseup, but the truth is we don’t care about the mouse position, just the fact that the event was fired, so we can simplify this middle definition to</p>
<pre class="brush: csharp; toolbar: false;">var mouseup = Observable.FromEvent
        &lt;MouseButtonEventArgs&gt;(
        this, &quot;MouseLeftButtonUp&quot; );</pre>
<p>&#160;</p>
<p>Our query statement becomes one of finding the start position and end position&#160; (for each movement of the mouse while the button is down) and then subtracting the end from the start to get the change in position for the image. </p>
<pre class="brush: csharp; toolbar: false;">var q = from start in mousedown
        from end in mousemove.TakeUntil( mouseup )
        select new
        {
           X = end.X - start.X,
           Y = end.Y - start.Y
        };</pre>
<p>&#160;</p>
<p>We can then use that query to subscribe to the mouse as if it were an observable&#160; collection of points.&#160; </p>
<pre class="brush: csharp; toolbar: false;">q.Subscribe( value =&gt;
{
   Canvas.SetLeft( image, value.X );
   Canvas.SetTop( image, value.Y );
} );</pre>
<p>Note that <em>image</em> is the name of the Image object defined in Xaml.</p>
<p>&#160;</p>
<p>The net effect is that if you click on the image, you can drag it around the phone’s canvas until you release the mouse button.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesseliberty.com/2011/02/21/reactive-drag-and-drop-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

