<?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>Rob Garfoot&#039;s Blog</title>
	<atom:link href="http://garfoot.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://garfoot.com/blog</link>
	<description>Blogging technology and stuff</description>
	<lastBuildDate>Sat, 18 Feb 2017 13:12:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.7.3</generator>
	<item>
		<title>Enabling UEFI booting on a BIOS installed Windows</title>
		<link>http://garfoot.com/blog/2014/08/enabling-uefi-booting-on-a-bios-installed-windows/</link>
		<pubDate>Fri, 29 Aug 2014 16:33:16 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[EFI]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[UEFI]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=682</guid>
		<description><![CDATA[Just a short article this one. I just got a new motherboard that support UEFI after a long time with my old one. I didn&#8217;t want to reinstall Windows at this point and it did a great job of detecting all of the new devices and just booted no problems. However I would like to [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2009/09/ahci-ide-migration/" rel="bookmark" title="Activating AHCI mode after installing Windows on IDE mode">Activating AHCI mode after installing Windows on IDE mode </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Just a short article this one. I just got a new motherboard that support UEFI after a long time with my old one. I didn&#8217;t want to reinstall Windows at this point and it did a great job of detecting all of the new devices and just booted no problems.</p>
<p>However I would like to take advantage of Windows&#8217; ability to UEFI boot and use the Secure Boot feature on Windows 8. There is no supported way to migrate from BIOS booting to UEFI but it is possible to do it. This isn&#8217;t for the faint of heart and it&#8217;s always possible when messing around with things like this that it&#8217;ll leave you in an unsupported state or completely broken and require a rebuild.</p>
<p>It did work for me though. Check out this great article <a title="http://social.technet.microsoft.com/wiki/contents/articles/14286.converting-windows-bios-installation-to-uefi.aspx" href="http://social.technet.microsoft.com/wiki/contents/articles/14286.converting-windows-bios-installation-to-uefi.aspx" target="_blank">http://social.technet.microsoft.com/wiki/contents/articles/14286.converting-windows-bios-installation-to-uefi.aspx</a> for the instructions.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2009/09/ahci-ide-migration/" rel="bookmark" title="Activating AHCI mode after installing Windows on IDE mode">Activating AHCI mode after installing Windows on IDE mode </a></li>
</ol></p>
</div>
]]></content:encoded>
			</item>
		<item>
		<title>Function lock for the Microsoft Wedge keyboard</title>
		<link>http://garfoot.com/blog/2014/07/function-lock-for-the-microsoft-wedge-keyboard/</link>
		<pubDate>Sat, 05 Jul 2014 14:36:07 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Gadgets]]></category>
		<category><![CDATA[keyboard]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[tablet]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=622</guid>
		<description><![CDATA[I&#8217;ve just purchased a Microsoft Wedge keyboard for my Dell Venue 8 Pro. It&#8217;s a really nice keyboard but it has one big flaw for my use, the F keys are on a function shift (Fn) which means when programming I have to hit Fn-F2 to get F2 and not volume mute. Fortunately it&#8217;s a [&#8230;]<div class='yarpp-related-rss yarpp-related-none'>

No related posts.
</div>
]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve just purchased a Microsoft Wedge keyboard for my Dell Venue 8 Pro. It&#8217;s a really nice keyboard but it has one big flaw for my use, the F keys are on a function shift (Fn) which means when programming I have to hit Fn-F2 to get F2 and not volume mute.</p>
<p>Fortunately it&#8217;s a fairly easy fix thanks to a great bit of software called <a title="AutoHotkey" href="http://www.autohotkey.com/" target="_blank">AutoHotkey.</a> This software lets you remap keyboard keys to others, run macros, build basic UIs, hotstrings and much more, it&#8217;s rather nice.</p>
<p><span id="more-622"></span>In this case I built a script that has 3 modes, Media keys on, F keys on, programmer mode which just does F1-F8 and leave F9-F12 requiring Fn pressing. I did that last mode as Print Screen, Home, End and Page Up are on F9-F12 and I use Home/End/PgUp way more than F10 or F11 which I only use when debugging.</p>
<p>I can switch between the modes with Win-; as the hotkey I&#8217;ve set up. The last thing I did was drop this into MyDocuments as wedgekeyboard.ahk, added a #include %A_ScriptDir%\wedgekeyboard.ahk to the autohotkey.ahk in there and set AutoHotkey to run on login by dropping its shortcut into the startup folder for my user in explorer.</p>
<p>It&#8217;s not the prettiest script but here it is.</p>
<pre class="brush: plain; title: ; notranslate">
SetAllOff()

; Wedge keyboard remaps
Media_Play_Pause::F1
Volume_Mute::F2
Volume_Down::F3
Volume_Up::F4
&lt;+#F21::F5
&lt;!&lt;#F21::F6
&lt;^&lt;#F21::F7
&lt;#F21::F8
PrintScreen::F9
Home::F10
End::F11
PgUp::F12
F1::Media_Play_Pause
F2::Volume_Mute
F3::Volume_Down
F4::Volume_Up
F5::&lt;+#F21
F6::&lt;!&lt;#F21
F7::&lt;^&lt;#F21
F8::&lt;#F21
F9::PrintScreen
F10::Home
F11::End
F12::PgUp
#;::NextStatus()

NextStatus()
{
  static Remap = 0 ; 0 - off, 1 - All F keys, 2 - F1-F8 only
  Remap++

  if Remap &gt; 2
  {
    Remap := 0
  }

  if Remap = 0
  {
    SetAllOff()
  }

  if Remap = 1
  {
    SetAllOn()
  }
  
  if Remap = 2
  {
    SetProgramming()
  }
}


SetAllOff()
{
  TrayTip, Media keys on, Wedge keyboard, 1
  Hotkey, *Media_Play_Pause, off
  Hotkey, *Volume_Mute, off
  Hotkey, *Volume_Down, off
  Hotkey, *Volume_Up, off
  Hotkey, *&lt;+#F21, off
  Hotkey, *&lt;!&lt;#F21, off
  Hotkey, *&lt;^&lt;#F21, off
  Hotkey, *&lt;#F21, off
  Hotkey, *PrintScreen, off
  Hotkey, *Home, off
  Hotkey, *End, off
  Hotkey, *PgUp, off
  Hotkey, *F1, off
  Hotkey, *F2, off
  Hotkey, *F3, off
  Hotkey, *F4, off
  Hotkey, *F5, off
  Hotkey, *F6, off
  Hotkey, *F7, off
  Hotkey, *F8, off
  Hotkey, *F9, off
  Hotkey, *F10, off
  Hotkey, *F11, off
  Hotkey, *F12, off
  Hotkey, *Media_Play_Pause up, off
  Hotkey, *Volume_Mute up, off
  Hotkey, *Volume_Down up, off
  Hotkey, *Volume_Up up, off
  Hotkey, *&lt;+#F21 up, off
  Hotkey, *&lt;!&lt;#F21 up, off
  Hotkey, *&lt;^&lt;#F21 up, off
  Hotkey, *&lt;#F21 up, off
  Hotkey, *PrintScreen up, off
  Hotkey, *Home up, off
  Hotkey, *End up, off
  Hotkey, *PgUp up, off
  Hotkey, *F1 up, off
  Hotkey, *F2 up, off
  Hotkey, *F3 up, off
  Hotkey, *F4 up, off
  Hotkey, *F5 up, off
  Hotkey, *F6 up, off
  Hotkey, *F7 up, off
  Hotkey, *F8 up, off
  Hotkey, *F9 up, off
  Hotkey, *F10 up, off
  Hotkey, *F11 up, off
  Hotkey, *F12 up, off
}

SetAllOn()
{
  TrayTip, Function keys on, Wedge keyboard, 1
  Hotkey, *Media_Play_Pause, on
  Hotkey, *Volume_Mute, on
  Hotkey, *Volume_Down, on
  Hotkey, *Volume_Up, on
  Hotkey, *&lt;+#F21, on
  Hotkey, *&lt;!&lt;#F21, on
  Hotkey, *&lt;^&lt;#F21, on
  Hotkey, *&lt;#F21, on
  Hotkey, *PrintScreen, on
  Hotkey, *Home, on
  Hotkey, *End, on
  Hotkey, *PgUp, on
  Hotkey, *F1, on
  Hotkey, *F2, on
  Hotkey, *F3, on
  Hotkey, *F4, on
  Hotkey, *F5, on
  Hotkey, *F6, on
  Hotkey, *F7, on
  Hotkey, *F8, on
  Hotkey, *F9, on
  Hotkey, *F10, on
  Hotkey, *F11, on
  Hotkey, *F12, on
  Hotkey, *Media_Play_Pause up, on
  Hotkey, *Volume_Mute up, on
  Hotkey, *Volume_Down up, on
  Hotkey, *Volume_Up up, on
  Hotkey, *&lt;+#F21 up, on
  Hotkey, *&lt;!&lt;#F21 up, on
  Hotkey, *&lt;^&lt;#F21 up, on
  Hotkey, *&lt;#F21 up, on
  Hotkey, *PrintScreen up, on
  Hotkey, *Home up, on
  Hotkey, *End up, on
  Hotkey, *PgUp up, on
  Hotkey, *F1 up, on
  Hotkey, *F2 up, on
  Hotkey, *F3 up, on
  Hotkey, *F4 up, on
  Hotkey, *F5 up, on
  Hotkey, *F6 up, on
  Hotkey, *F7 up, on
  Hotkey, *F8 up, on
  Hotkey, *F9 up, on
  Hotkey, *F10 up, on
  Hotkey, *F11 up, on
  Hotkey, *F12 up, on
}

SetProgramming()
{
  TrayTip, Programmer mode on, Wedge keyboard, 1
  Hotkey, *Media_Play_Pause, on
  Hotkey, *Volume_Mute, on
  Hotkey, *Volume_Down, on
  Hotkey, *Volume_Up, on
  Hotkey, *&lt;+#F21, on
  Hotkey, *&lt;!&lt;#F21, on
  Hotkey, *&lt;^&lt;#F21, on
  Hotkey, *&lt;#F21, on
  Hotkey, *PrintScreen, off
  Hotkey, *Home, off
  Hotkey, *End, off
  Hotkey, *PgUp, off
  Hotkey, *F1, on
  Hotkey, *F2, on
  Hotkey, *F3, on
  Hotkey, *F4, on
  Hotkey, *F5, on
  Hotkey, *F6, on
  Hotkey, *F7, on
  Hotkey, *F8, on
  Hotkey, *F9, off
  Hotkey, *F10, off
  Hotkey, *F11, off
  Hotkey, *F12, off
  Hotkey, *Media_Play_Pause up, on
  Hotkey, *Volume_Mute up, on
  Hotkey, *Volume_Down up, on
  Hotkey, *Volume_Up up, on
  Hotkey, *&lt;+#F21 up, on
  Hotkey, *&lt;!&lt;#F21 up, on
  Hotkey, *&lt;^&lt;#F21 up, on
  Hotkey, *&lt;#F21 up, on
  Hotkey, *PrintScreen up, off
  Hotkey, *Home up, off
  Hotkey, *End up, off
  Hotkey, *PgUp up, off
  Hotkey, *F1 up, on
  Hotkey, *F2 up, on
  Hotkey, *F3 up, on
  Hotkey, *F4 up, on
  Hotkey, *F5 up, on
  Hotkey, *F6 up, on
  Hotkey, *F7 up, on
  Hotkey, *F8 up, on
  Hotkey, *F9 up, off
  Hotkey, *F10 up, off
  Hotkey, *F11 up, off
  Hotkey, *F12 up, off
}
</pre>
<div class='yarpp-related-rss yarpp-related-none'>
<p>No related posts.</p>
</div>
]]></content:encoded>
			</item>
		<item>
		<title>Using Grids with ItemsControl in XAML</title>
		<link>http://garfoot.com/blog/2013/09/using-grids-with-itemscontrol-in-xaml/</link>
		<comments>http://garfoot.com/blog/2013/09/using-grids-with-itemscontrol-in-xaml/#comments</comments>
		<pubDate>Tue, 17 Sep 2013 13:55:03 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[winRT]]></category>
		<category><![CDATA[wp7]]></category>
		<category><![CDATA[wp8]]></category>
		<category><![CDATA[wpf]]></category>
		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=432</guid>
		<description><![CDATA[ItemsControl in XAML is a useful control that allows you to bind against multiple items and have them displayed using a repeating template (or templates). It forms the basis of the ListBox and other controls but can be used on its own where extra behaviour such as selection is not needed. By default the ItemsControl [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/03/flexible-data-template-support-in-silverlight/" rel="bookmark" title="Flexible Data Template Support in Silverlight">Flexible Data Template Support in Silverlight </a></li>
<li><a href="http://garfoot.com/blog/2010/09/silverlight-navigation-with-the-mvvm-pattern/" rel="bookmark" title="Silverlight Navigation With the MVVM Pattern">Silverlight Navigation With the MVVM Pattern </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>ItemsControl in XAML is a useful control that allows you to bind against multiple items and have them displayed using a repeating template (or templates). It forms the basis of the ListBox and other controls but can be used on its own where extra behaviour such as selection is not needed.</p>
<p>By default the ItemsControl uses a vertically aligned StackPanel as the layout panel for its items but you can override this by providing a template. It&#8217;s quite common to override this for example to use a VirtualizingStackPanel but in this instance I wanted to use a Grid for layout.<br />
<span id="more-432"></span></p>
<h2>The Problem</h2>
<p>I have a set of items that I want to arrange in a grid, I want the items to size to fill the available space after specifying the number of columns and rows I would like for display. This means I can&#8217;t use a WrapPanel but will ideally use a Grid.</p>
<p>The XAML for this would look something like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ItemsControl ItemsSource=&quot;{Binding Data}&quot;&gt;
    &lt;ItemsControl.ItemsPanel&gt;
        &lt;ItemsPanelTemplate&gt;
            &lt;Grid/&gt;
        &lt;/ItemsPanelTemplate&gt;
    &lt;/ItemsControl.ItemsPanel&gt;
    &lt;ItemsControl.ItemTemplate&gt;
        &lt;DataTemplate&gt;
            &lt;Ellipse
                Grid.Row=&quot;{Binding X}&quot;
                Grid.Column=&quot;{Binding Y}&quot;
                Fill=&quot;Black&quot;
                HorizontalAlignment=&quot;Stretch&quot;
                VerticalAlignment=&quot;Stretch&quot;/&gt;
        &lt;/DataTemplate&gt;
    &lt;/ItemsControl.ItemTemplate&gt;
&lt;/ItemsControl&gt;
</pre>
<p>This should let me have a collection called &#8220;Data&#8221; with items that have X and Y properties that refer to the grid coordinates. The problem is that this doesn&#8217;t work. To understand why we need to look at how the Grid and ItemsControl work.</p>
<h3>The ContentPresenter</h3>
<p>During layout the Grid will look for attached properties Grid.Row and Grid.Column on child elements to place them in the correct cell. However, it only checks immediate children, this is important due to how the ItemsControl works.</p>
<p>When displaying items the ItemsControl will wrap the supplied item and its DataTemplate (if it has one) in a ContentPresenter. This means that if you add Grid.Row and Grid.Column attributes to the item in the DataTemplate then the Grid will not find them since the immediate child is a ContentPresenter, not the item in the DataTemplate.</p>
<h3>Dynamic Rows and Columns</h3>
<p>The other challenge we have is that the number of rows and columns cannot be databound, we have to specify them explicitly using RowDefinitions and ColumnDefinitions.</p>
<h2>The Solution</h2>
<p>After a bit of poking around on the internet I found a few solutions to the problem but having worked with the ItemsControl in the past I knew that there was probably a simpler solution than some of the ones I found.</p>
<p>I subclassed the ItemsControl into a GridAwareItemsControl and implemented the GetContainerForItemOverride method. This is the method that normally creates the container for the item, i.e. the ContentPresenter.</p>
<p>In this method I check to see if there is an ItemTemplate (DataTemplate) and then check to see if the content of it has Grid.Row and Grid.Column set. If they do I copy the bindings from them to the ContentPresenter. This code assumes there are bindings and not hardcoded values but hardcoding the values wouldn&#8217;t make sense for this.</p>
<pre class="brush: csharp; title: ; notranslate">
public class GridAwareItemsControl : ItemsControl
{
    protected override DependencyObject GetContainerForItemOverride()
    {
        ContentPresenter container = (ContentPresenter) base.GetContainerForItemOverride();
        if (ItemTemplate == null)
        {
            return container;
        }

        FrameworkElement content = (FrameworkElement)ItemTemplate.LoadContent();
        BindingExpression rowBinding = content.GetBindingExpression(Grid.RowProperty);
        BindingExpression columnBinding = content.GetBindingExpression(Grid.ColumnProperty);

        if (rowBinding != null)
        {
            container.SetBinding(Grid.RowProperty, rowBinding.ParentBinding);
        }

        if (columnBinding != null)
        {
            container.SetBinding(Grid.ColumnProperty, columnBinding.ParentBinding);
        }

        return container;
    }
}
</pre>
<p>The second part of the solution, dynamically creating the rows and columns, was solved using a couple of attached properties. These take int values and then programmatically create the RowDefinition and ColumnDefinition items on the Grid.</p>
<pre class="brush: csharp; title: ; notranslate">
public class GridAutoLayout
{
    public static int GetNumberOfColumns(DependencyObject obj)
    {
        return (int)obj.GetValue(NumberOfColumnsProperty);
    }

    public static void SetNumberOfColumns(DependencyObject obj, int value)
    {
        obj.SetValue(NumberOfColumnsProperty, value);
    }

    // Using a DependencyProperty as the backing store for NumberOfColumns.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty NumberOfColumnsProperty =
        DependencyProperty.RegisterAttached(&quot;NumberOfColumns&quot;, typeof(int), typeof(GridAutoLayout), new PropertyMetadata(1, NumberOfColumnsUpdated));

    public static int GetNumberOfRows(DependencyObject obj)
    {
        return (int)obj.GetValue(NumberOfRowsProperty);
    }

    public static void SetNumberOfRows(DependencyObject obj, int value)
    {
        obj.SetValue(NumberOfRowsProperty, value);
    }

    // Using a DependencyProperty as the backing store for NumberOfRows.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty NumberOfRowsProperty =
        DependencyProperty.RegisterAttached(&quot;NumberOfRows&quot;, typeof(int), typeof(GridAutoLayout), new PropertyMetadata(1, NumberOfRowsUpdated));

    private static void NumberOfRowsUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Grid grid = (Grid) d;

        grid.RowDefinitions.Clear();
        for (int i = 0; i &lt; (int)e.NewValue; i++)
        {
            grid.RowDefinitions.Add(new RowDefinition(){Height = new GridLength(1, GridUnitType.Star)});
        }
    }

    private static void NumberOfColumnsUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Grid grid = (Grid)d;

        grid.ColumnDefinitions.Clear();
        for (int i = 0; i &lt; (int)e.NewValue; i++)
        {
            grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
        }
    }
}
</pre>
<p>In all this results in XAML that looks like this and I think is a reasonably simple solution.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;controls:GridAwareItemsControl ItemsSource=&quot;{Binding Data}&quot;&gt;
    &lt;ItemsControl.ItemsPanel&gt;
        &lt;ItemsPanelTemplate&gt;
            &lt;Grid controls:GridAutoLayout.NumberOfRows=&quot;{Binding Rows}&quot;
                  controls:GridAutoLayout.NumberOfColumns=&quot;{Binding Columns}&quot;&gt;
            &lt;/Grid&gt;
        &lt;/ItemsPanelTemplate&gt;
    &lt;/ItemsControl.ItemsPanel&gt;
    &lt;ItemsControl.ItemTemplate&gt;
        &lt;DataTemplate&gt;
            &lt;Ellipse
                Grid.Row=&quot;{Binding X}&quot;
                Grid.Column=&quot;{Binding Y}&quot;
                Fill=&quot;Black&quot;
                HorizontalAlignment=&quot;Stretch&quot;
                VerticalAlignment=&quot;Stretch&quot;/&gt;
        &lt;/DataTemplate&gt;
    &lt;/ItemsControl.ItemTemplate&gt;
&lt;/controls:GridAwareItemsControl&gt;
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/03/flexible-data-template-support-in-silverlight/" rel="bookmark" title="Flexible Data Template Support in Silverlight">Flexible Data Template Support in Silverlight </a></li>
<li><a href="http://garfoot.com/blog/2010/09/silverlight-navigation-with-the-mvvm-pattern/" rel="bookmark" title="Silverlight Navigation With the MVVM Pattern">Silverlight Navigation With the MVVM Pattern </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://garfoot.com/blog/2013/09/using-grids-with-itemscontrol-in-xaml/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Securely extending Surface RT with an SD card and BitLocker</title>
		<link>http://garfoot.com/blog/2012/11/securely-extending-surface-rt-with-an-sd-card-and-bitlocker/</link>
		<comments>http://garfoot.com/blog/2012/11/securely-extending-surface-rt-with-an-sd-card-and-bitlocker/#comments</comments>
		<pubDate>Wed, 21 Nov 2012 17:22:14 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Gadgets]]></category>
		<category><![CDATA[surface]]></category>
		<category><![CDATA[windowsRT]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=365</guid>
		<description><![CDATA[I bought myself a Surface RT the other day and I&#8217;m loving it however one thing that I wanted to do is expand the built in storage using a SD card. Unfortunately this is one area where the Surface is a little less than helpful, I can happily plug in a micro SD however getting my [&#8230;]<div class='yarpp-related-rss yarpp-related-none'>

No related posts.
</div>
]]></description>
				<content:encoded><![CDATA[<p>I bought myself a Surface RT the other day and I&#8217;m loving it however one thing that I wanted to do is expand the built in storage using a SD card. Unfortunately this is one area where the Surface is a little less than helpful, I can happily plug in a micro SD however getting my content to automatically use it is another matter.</p>
<p><span id="more-365"></span></p>
<h2>Integrating SD cards with libraries</h2>
<p>The first challenge is getting the SD card to be seen by Windows as the default location for things and to allow apps to find content on it. In theory you can do this by adding the SD card into the Windows libraries for music, pictures etc.</p>
<p>However, you can&#8217;t add removable media to libraries. This is quite easy to work around thankfully and has been documented elsewhere. To save you going looking here is my solution.</p>
<p>First I reformatted my SD card with NTFS, you&#8217;ll need to do this to set permissions later.</p>
<p>Next I created top level folders for Public and Rob (myself), remember this is a multi user device so I want document isolation.</p>
<p>Inside each of these I created the folders for music, pictures, documents and videos.</p>
<p>I set the ACLs on each of the top level public and user folders to match those on the system drive in C:\Users, this took a while but had to be done for security. You could looking into using robocopy to copy the original folders and ACLs, that might save time.</p>
<p>Next I ran disk management (from search or win-x -&gt; computer management) and removed the drive letter from the SD card. I created a folder on C:\ called SD and then added a mount path to that location.</p>
<p>Once that was all done I was able to right click each library, go to properties and add the new locations to each library. I set the new public and rob folders as the defaults for public and current user respectively.</p>
<p>Job done, now I can move all my content from the C drive to the SD and apps will see it, since I changed the default any music I download etc. will save there by default. However, I&#8217;d suggest if you&#8217;re going to BitLocker the SD card you wait until after that before you start copying data over onto the SD, it&#8217;ll be quicker enabling BitLocker.</p>
<h2>Security</h2>
<p>I mentioned security above where I said I set up ACLs on the folders, however that&#8217;s only half of the story. This is a removable disk with my personal data on it, I really want it encrypted.</p>
<p>Luckily and mostly unknown to people the Surface has a TPM and comes with BitLocker enabled out of the box. Great, I can BitLocker by SD card.</p>
<p>Except Surface exposes no UI for it and as it turns out the manage-bde command won&#8217;t let you do it either, failing with the message that this version of the OS doesn&#8217;t support that when trying to encrypt. I have no idea why, it really should support encrypting removable (or in this case semi-permanent) storage, it has a TPM and seems quite arbitrary.</p>
<p>No worries though, I simply put the SD card into my desktop machine which is running Windows 8 Enterprise (or Pro will do), right clicked it and selected enable BitLocker. I set a password and backed up the key to a file.</p>
<p>Putting the SD back in the Surface didn&#8217;t auto unlock so I had to go the command line here.</p>
<p>I started an elevated command prompt (win-x) and then executed the following:</p>
<pre>manage-bde -unlock c:\sd -password</pre>
<p>I then entered my password and it was unlocked. Ideally though I want this to happen automatically at reboot.</p>
<h2>Automatic unlocking</h2>
<p>Again this is an area where things are missing, the -autounlock option on manage-bde doesn&#8217;t work on this version of Windows so I had to create an unlock script.</p>
<p>This was quite easy, I created a new .bat file on my C drive in my user documents folder on that disk, this script simply contains the above unlock command with a slight change, rather than using -password I use -rp to use a recovery password. This let&#8217;s you specify it in the command line. You ne to get the recovery password from the file saved out when you BitLockered the SD, its the big long number at the end of the text file. Just put that after the -rp option.</p>
<p>It looks something like this, where the xxxxxx-xxxxxx bit is your recovery key. Some people in the comments have had success with -rk instead of -rp but -rp works for me.</p>
<pre>manage-bde -unlock c:\sd -rp xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx</pre>
<p>Next I used the Windows task scheduler which you can get to from computer management (win-x) to create a new task. This task was set to run as me, with max permissions (needs elevation) and triggered to run at startup. The action for the task was to run my .bat file.</p>
<p>Now when I reboot my machine automatically unlocks my SD but I&#8217;m safe in the knowledge that someone needs a logon to my Surface to access it and if they remove it they need the password for the SD to unlock it.</p>
<h2>The final step</h2>
<p>This one&#8217;s optional but if like me you&#8217;re not planning on removing the SD (which I&#8217;d really recommend once you&#8217;ve added it to your libraries, things gets upset if you do), then you might want to enable write caching on the SD.</p>
<p>Just run up device manager, again win-x is your friend, expand Disk Drives and go to Properties on the SD Memory Card. Select Policies and &#8220;Better performance&#8221;. Note that with write caching enabled you *must* use the safely remove hardware feature on the notification area on the desktop before ejecting the SD card. If you don&#8217;t you might lose data which hasn&#8217;t been flushed from memory to the SD.</p>
<div class='yarpp-related-rss yarpp-related-none'>
<p>No related posts.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://garfoot.com/blog/2012/11/securely-extending-surface-rt-with-an-sd-card-and-bitlocker/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Dynamic SQL scripting on Windows Phone 7 with LINQ</title>
		<link>http://garfoot.com/blog/2012/02/dynamic-sql-scripting-on-windows-phone-7-with-linq/</link>
		<comments>http://garfoot.com/blog/2012/02/dynamic-sql-scripting-on-windows-phone-7-with-linq/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 12:13:41 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=353</guid>
		<description><![CDATA[I recently had cause to look into running dynamic SQL on WP7 for a customer. On a desktop this is easy, you just run some SQL statements through ADO.NET and you&#8217;re sorted. On Windows Phone 7 it&#8217;s a little trickier. This is because WP7 only exposes LINQ to SQL and it doesn&#8217;t support arbitrary SQL [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2012/01/connecting-to-sharepoint-on-office-365-with-windows-phone-7/" rel="bookmark" title="Connecting to SharePoint on Office 365 with Windows Phone 7">Connecting to SharePoint on Office 365 with Windows Phone 7 </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I recently had cause to look into running dynamic SQL on WP7 for a customer. On a desktop this is easy, you just run some SQL statements through ADO.NET and you&#8217;re sorted. On Windows Phone 7 it&#8217;s a little trickier. This is because WP7 only exposes LINQ to SQL and it doesn&#8217;t support arbitrary SQL execution against your SQL CE databases.</p>
<p>So how to handle it when you have a corrupt DB and want to send a fix to a remote device or you just want to update the DB with some new data.<br />
<span id="more-353"></span></p>
<h2>DB Operations</h2>
<p>The first thing I decided was what operations I wanted to support, I limited this to supporting create, update and delete operations since those are the ones we are really look at here. I also limited it to each operation only operating against a single entity type at a time, it just made it easier and that covers most of the scenarios I needed at the time.</p>
<h2>Command Serialization</h2>
<p>The first problem I needed to tackle was getting the commands down to the phone application, how am I going to script this? I chose to create an object model of <strong>DatabaseInstruction</strong> objects which represent the serialized format of one of the above operations. I then used JSON as the format for my script as it&#8217;s nice and easy to then return that object model from a server to the client and it&#8217;s more compact than XML. Of course you can always change the serialization format by creating a new <strong>IDatabaseInstructionParser</strong> to process different serialization formats into the object model.</p>
<p>I used the excellent <a title="JSON.Net" href="http://json.codeplex.com/">JSON.Net</a> library to handle the serialization for me.</p>
<h2>Database Commands</h2>
<p>Once I&#8217;ve gotten a list of <strong>DatabaseInstruction</strong> objects I convert them into <strong>DbCommand</strong> objects, these are the objects that do the actual work of talking to the database using LINQ to SQL. That&#8217;s handled by calling <strong>CreateCommand</strong> against each instruction. If you&#8217;d like to reuse the same <strong>DatabaseInstruction</strong> classes in the server component to build the script then I suggest refactoring this to separate the command creation out. I started doing that with the <strong>CommandBuilder</strong> class but never finished it, currently that class is incomplete and unused.</p>
<h2>Parsing</h2>
<p>So far so simple. The next challenge was filtering the data in the instructions, in order to do that I needed to pass in predicates in my scripts to apply changes to certain rows or to delete specific items. I downloaded and slightly modified the <a title="Dynamic LINQ" href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">Dynamic LINQ</a> sample from Scott Guthrie&#8217;s blog. This almost worked on the phone out of the box but not quite, I had to chop out support for &#8216;new&#8217; since the phone can&#8217;t do the dynamic code gen bits that the sample uses and I didn&#8217;t need the operator for what I was doing.</p>
<p>In the commands I then use the <strong>DynamicExpression.ParseLamba()</strong> method to create an <strong>Expression</strong> predicate from the predicate from the script. This can then be used in my command execution with a custom <strong>Where</strong> implementation that takes an <strong>Expression</strong> object.</p>
<h2>And finally&#8230;</h2>
<p>Using the library is fairly easy, I&#8217;ve put together a sample WP7 app that creates a database and then provides 2 buttons, one runs an JSON script to insert data, the other runs a JSON script to update the data and delete a row. The scripts are in the Content folder in the project and I just use the <strong>DatabaseInstructions.Execute()</strong> method to run the script. This can either take a <strong>TextReader</strong> or an <strong>IEnumerable&lt;DatabaseInstruction&gt;</strong> if you&#8217;d prefer to handle parsing yourself.</p>
<p>As usual the normal disclaimers about demo code apply, use at your own risk. To build the sample just download the <a href="http://garfoot.com/wordpress/wp-content/uploads/2012/02/DynamicLinq.zip">DynamicLinq sample code</a> and load it in Visual Studio 2010. It uses NuGet to pull down the JSON.Net bits so just build the solution and it&#8217;ll do that automatically.</p>
<p>Enjoy.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2012/01/connecting-to-sharepoint-on-office-365-with-windows-phone-7/" rel="bookmark" title="Connecting to SharePoint on Office 365 with Windows Phone 7">Connecting to SharePoint on Office 365 with Windows Phone 7 </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://garfoot.com/blog/2012/02/dynamic-sql-scripting-on-windows-phone-7-with-linq/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Connecting to SharePoint on Office 365 with Windows Phone 7</title>
		<link>http://garfoot.com/blog/2012/01/connecting-to-sharepoint-on-office-365-with-windows-phone-7/</link>
		<comments>http://garfoot.com/blog/2012/01/connecting-to-sharepoint-on-office-365-with-windows-phone-7/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 13:18:36 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Office365]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=341</guid>
		<description><![CDATA[One of my colleagues recently asked me to look into connecting to a SharePoint site running on Office 365 from a Windows Phone 7 application. Now this is something that the phone has native support for but in this case he wanted to be able to build an application that had added functionality and then [&#8230;]<div class='yarpp-related-rss yarpp-related-none'>

No related posts.
</div>
]]></description>
				<content:encoded><![CDATA[<p>One of my colleagues recently asked me to look into connecting to a SharePoint site running on Office 365 from a Windows Phone 7 application. Now this is something that the phone has native support for but in this case he wanted to be able to build an application that had added functionality and then called into the SharePoint web service APIs to extract data from SharePoint.<br />
<span id="more-341"></span></p>
<h2>Attempt number 1</h2>
<p>At first I thought this would be really easy, add a reference to the web service, call the Logon API and then we&#8217;re away. Unfortunately that isn&#8217;t the case.</p>
<p>I found this <a title="Developing Windows Phone 7 Applications For SharePoint 2010" href="http://blogs.msdn.com/b/pstubbs/archive/2010/10/04/developing-windows-phone-7-applications-for-sharepoint-2010.aspx">blog article</a> by Paul Stubbs which was a good starting point.</p>
<p>When I implemented this against Office 365 it all seemed good until I actually tried to logon, I kept getting a logon failure and couldn&#8217;t figure out why. Eventually I twigged, Office 365 uses federated identity. As a result the SharePoint logon APIs don&#8217;t recognise your credentials, it knows nothing about them.</p>
<h2>Attempt number 2</h2>
<p>I then traced out the flow of an actual logon and found that Office 365 uses login.microsoftonline.com to authenticate against. At least this is the case on my Office 365 site, if you federate with a different provider then you&#8217;ll have to adapt this solution appropriately.</p>
<p>Now the flow here is a fairly standard WS-Trust flow, you hit the SharePoint site, that redirects a couple of times internally and then goes off to microsoftonline.com passing it a bit of security information. This asks you for your username and password in a web page and then redirects you back to Office 365 with some more security information.</p>
<p>SharePoint then writes out a cookie with a security token in, as long as web service API requests pass this cookie they&#8217;ll work.</p>
<p>So this is simple, I pop up a web browser, hit SharePoint go through the logon flow, grab the cookie once it comes back to SharePoint and we&#8217;re good to go.</p>
<p>Except we&#8217;re not, the cookie gets written with HttpOnly which means that you cannot programatically get the cookie.</p>
<h2>Enter the hack</h2>
<p>The solution I came up with is a little brittle but it works ok for now for me. If you look at how the WS-Trust flow works as implemented by this secure token service (STS) after log on it writes out a form with POST data on it containing the WS-Trust security data, then it uses JavaScript to post this back to SharePoint.</p>
<p>So what I do is roughly this:</p>
<ol>
<li>Check if not logged on</li>
<li>Pop up a web browser control</li>
<li>Navigate to the SharePoint site home page which will redirect to the STS</li>
<li>User enters credentials</li>
<li>I hook up navigation events from the browser control and when I spot a navigate to the page with the POST data from the STS&#8230;</li>
<li>Capture the security information from the form from the browser control</li>
<li>Programatically POST the form back to SharePoint using a new CookieContainer and HttpWebRequest</li>
<li>SharePoint completes the WS-Trust flow and issues the SP security cookie which goes into the new CookieContainer</li>
<li>Attach the new CookieContainer to all web service API calls and it&#8217;s sorted</li>
</ol>
<p>Now as mentioned this is a little brittle as if the STS changes how it works a bit then it&#8217;ll break but most of the time that&#8217;s unlikely, especially if you are running you own STS to federate your corporate logons, you&#8217;ll control it&#8217;s appearance.</p>
<p>I&#8217;ve included some sample code that does this, usual caveats apply. The DefaultSettings class has the SharePoint site address and SSL settings in there, change this to point at your site.</p>
<p>I&#8217;ve wrapped the CookieContainer in a SharepointServerContext class to isolate the using code from this. This class also contains other information about the connection the server such as it&#8217;s address etc. All of the web service API calls are executed by my own ISharepointCommand classes, these commands all take a SharepointServerContext so they know which server to talk to and can get to the CookieContainer for authentication.</p>
<p>Most of the logon flow code is in the code behind for the LogonView since it needs access to the browser control.</p>
<h2>Next steps</h2>
<p>There are bugs in the code, things are not complete, this is a work in progress but it does demonstrate the flow mentioned above. Currently if you authenticate and tick remember me it&#8217;ll break the next time you run since the flow will be different, it doesn&#8217;t cache cookies yet as that&#8217;s something else I need to work out so this is not a perfect approach. But hopefully it&#8217;ll help as a starting point for people looking at this.</p>
<p>You can download the sample project from here <a href="http://garfoot.com/wordpress/wp-content/uploads/2012/01/SharePointConnector.zip">SharePointConnector</a>. Good luck.</p>
<h2>Update</h2>
<p>After a little bit of investigation with the help of Rob de Beir (see comments below) we&#8217;ve discovered that the solution as posted only actually works on E1 Office 365 deployments, if you&#8217;re running P1 then it doesn&#8217;t work.</p>
<p>This is down to 4 things;</p>
<ol>
<li>P1 SOAP APIs only work over HTTP, E1 work over HTTPS</li>
<li>There was a bug in the code (gasp) that meant setting SSL = false didn&#8217;t work</li>
<li>The logon view didn&#8217;t process the POST address from the STS, it was hardcoded</li>
<li>P1 sites have a path</li>
</ol>
<p>Fortunately this is an easy fix, disable SSL in the DefaultSettings.cs, fix the bug (shown below) and make sure you set the host in the DefaultSettings.cs to have the path too e.g. mysite.sharepoint.com/teamsite.</p>
<p>To fix the bug simply find the line of code in GetListItems.cs where the BasicHttpBinding is created and change it to read;</p>
<pre class="brush: csharp; title: ; notranslate">
new BasicHttpBinding(ServerContext.UseSsl ?
 BasicHttpSecurityMode.Transport :
 BasicHttpSecurityMode.None),
</pre>
<p>There is another bit that needs to change in the LogonView.xaml.cs file too. Replace the OnBrowserNavigated method with this one in order to correctly parse out the return address from the STS.</p>
<pre class="brush: csharp; title: ; notranslate">
private void OnBrowserNavigated(object sender, NavigationEventArgs e)
{
    if (!IsLastPage(e.Uri))
        return;

    string content = Browser.SaveToString();
    Regex actionRegex = new Regex(&quot;&lt;FORM .* action=(?'action'.*?) target.*&quot;,
                                  RegexOptions.Multiline |
                                  RegexOptions.IgnoreCase);
    Regex tokenRegex = new Regex(&quot;name=t value=(?'token'.*?) type=&quot;,
                                 RegexOptions.Multiline |
                                 RegexOptions.IgnoreCase);

    Group tokenMatch = tokenRegex.Match(content).Groups[&quot;token&quot;];
    Group actionMatch = actionRegex.Match(content).Groups[&quot;action&quot;];

    if (tokenMatch.Success &amp;&amp; actionMatch.Success)
    {
        _token = tokenMatch.Value;
        _action = actionMatch.Value;

        Browser.Navigated -= OnBrowserNavigated;
        Browser.NavigateToString(Strings.LogonPageLoadingMessage);
        Logon();
    }
}
</pre>
<p>Add a backing field for the action.</p>
<pre class="brush: csharp; title: ; notranslate">
private string _action;
</pre>
<p>And finally update Logon() to use the new action.</p>
<pre class="brush: csharp; title: ; notranslate">
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_action);
</pre>
<p>That should fix it all to work on E1 as well as P1. Thanks to Rob for his help in debugging this, I&#8217;ll try and get updated source up soon.</p>
<pre></pre>
<div class='yarpp-related-rss yarpp-related-none'>
<p>No related posts.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://garfoot.com/blog/2012/01/connecting-to-sharepoint-on-office-365-with-windows-phone-7/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>TechEd GadgetVote source code</title>
		<link>http://garfoot.com/blog/2010/11/teched-gadgetvote-source-code/</link>
		<pubDate>Fri, 12 Nov 2010 10:48:07 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[teched]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=331</guid>
		<description><![CDATA[For those people that attended my TechEd Europe session on end to end development in WP7, here is the source code for my demos. In order to run the demo code you will need VS2010, WP7 SDK, Azure SDK. Running for the first time Run VS2010 elevated (needed for Azure) and build the project. Run [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/11/teched-code-coming-soon/" rel="bookmark" title="TechEd code coming soon">TechEd code coming soon </a></li>
<li><a href="http://garfoot.com/blog/2010/10/simulated-push-notifications-on-windows-phone-7/" rel="bookmark" title="Simulated Push Notifications on Windows Phone 7">Simulated Push Notifications on Windows Phone 7 </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>For those people that attended my TechEd Europe session on end to end development in WP7, here is the <a href="http://garfoot.com/samples/GadgetVote.zip">source code</a> for my demos.</p>
<p>In order to run the demo code you will need VS2010, WP7 SDK, Azure SDK.</p>
<p><span id="more-331"></span></p>
<h2>Running for the first time</h2>
<p>Run VS2010 elevated (needed for Azure) and build the project. Run using the GadgetVote.Client and GadgetVote.Server projects as startup projects.</p>
<p>Once running you will need to go to settings in the client and change the address of the server to localhost:81 (or whatever port your Azure service is running on in DevFabric). You can also choose to use the proper WP7 push notifications service by leaving the check box ticked or use the Azure based stub service by unticking the box. You will need to restart the client app after changing this setting.</p>
<h2>It&#8217;s a demo project!</h2>
<p>It&#8217;s a demo project, it will crash and break if you don&#8217;t do things just right. If the Azure service hasn&#8217;t started by the time the phone app starts then you&#8217;ll get an exception from the client app. Just hit F5 and carry on, once the Azure services have started you can go to settings and hit OK and it should register again with the Azure service and work.</p>
<h2>Who am I?</h2>
<p>You will want to go to settings and add a username for yourself, this is name@domain, I usually use something like rob@emulator or rob@phone1 etc.</p>
<h2>I do have friends, honest</h2>
<p>Next you&#8217;ll need to hit the + button and add a friend, you can just add yourself for now, the name doesn&#8217;t matter but the second field must match the name entered in settings.</p>
<h2>Adding a gadget</h2>
<p>You can then add a gadget by clicking the camera. Check the table storage on your Azure instance though first, the clients must all have registered themselves with push notification endpoints before doing this or you&#8217;ll get a crash! You can goto settings and hit OK to force it to re-register.</p>
<h2>Multiple clients</h2>
<p>You will need to run multiple machines to do this with an emulator on each. If you have phones then you can use those. Azure DevFabric only allows connections from the local machine though, to get around this I run a reverse proxy using IIS and the <a href="http://www.iis.net/download/ApplicationRequestRouting">ARR plugin</a>. Configure a proxy with a URL rewrite rule for something like /azure to map to localhost:81. Then you can use ip/azure for the host name in the client settings on the WP7 app and it&#8217;ll work remotely.</p>
<p>Usual caveats apply, this is demo code, it&#8217;ll explode if you prod it wrong and don&#8217;t use in production.</p>
<p>Enjoy!!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/11/teched-code-coming-soon/" rel="bookmark" title="TechEd code coming soon">TechEd code coming soon </a></li>
<li><a href="http://garfoot.com/blog/2010/10/simulated-push-notifications-on-windows-phone-7/" rel="bookmark" title="Simulated Push Notifications on Windows Phone 7">Simulated Push Notifications on Windows Phone 7 </a></li>
</ol></p>
</div>
]]></content:encoded>
			</item>
		<item>
		<title>TechEd code coming soon</title>
		<link>http://garfoot.com/blog/2010/11/teched-code-coming-soon/</link>
		<pubDate>Fri, 12 Nov 2010 09:27:04 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[teched]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=329</guid>
		<description><![CDATA[Just a quick note to say I&#8217;ll get the code from my TechEd session uploaded within the next few days so check back next week.<div class='yarpp-related-rss yarpp-related-none'>

No related posts.
</div>
]]></description>
				<content:encoded><![CDATA[<p>Just a quick note to say I&#8217;ll get the code from my TechEd session uploaded within the next few days so check back next week.</p>
<div class='yarpp-related-rss yarpp-related-none'>
<p>No related posts.</p>
</div>
]]></content:encoded>
			</item>
		<item>
		<title>Simulated Push Notifications on Windows Phone 7</title>
		<link>http://garfoot.com/blog/2010/10/simulated-push-notifications-on-windows-phone-7/</link>
		<pubDate>Tue, 05 Oct 2010 15:07:00 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=321</guid>
		<description><![CDATA[I’m currently prepping for my TechEd Europe WP7 session and I like to prepare for the worst. My demo relies on some cloud services and also on WP7 push notifications. Push notifications are nice but they have one drawback for demos, I need an internet connection. Now in the real world my application would indeed [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2008/06/transferring-large-files-using-wcf/" rel="bookmark" title="Transferring large files using WCF">Transferring large files using WCF </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I’m currently prepping for my TechEd Europe WP7 session and I like to prepare for the worst. My demo relies on some cloud services and also on WP7 push notifications. Push notifications are nice but they have one drawback for demos, I need an internet connection.</p>
<p>Now in the real world my application would indeed need an internet connection or it would actually be kind of useless, but in demoland I don’t need one as I can run the cloud services portion in the Azure DevFabric which is nice in case the internet connectivity in the demo room goes down, I have a backup.</p>
<p>The same isn’t true of push notifications, they are managed by Microsoft and if I can’t get to them I can run my demo even though my own cloud services are running locally. In order to get around this I wrote a simple WCF service that also runs in my Azure DevFabric along with my other services that can act as a push notification endpoint. It’s not totally seamless but it works quite nicely for me as I now have a fallback for push notifications as well as for my own cloud services.<span id="more-321"></span></p>
<h2>The Service</h2>
<p>The service is a REST based WCF service that has two methods on it’s rather simple interface.</p>
<pre class="brush: csharp; title: ; notranslate">
[ServiceContract]
public interface INotifications
{
    [OperationContract]
    [WebInvoke(Method=&quot;POST&quot;, UriTemplate = &quot;Notify&quot;,
        BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)]
    void Notify(Message message);

    [OperationContract]
    [WebInvoke(Method = &quot;GET&quot;, UriTemplate = &quot;Notifications/{id}&quot;)]
    Message GetNotifications(string id);
}
</pre>
<p>The service then queues any incoming messages until the client gets them. The notify endpoint will quite happily take push notification requests from my existing Azure services without modification.</p>
<pre class="brush: csharp; title: ; notranslate">
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
                    ConcurrencyMode = ConcurrencyMode.Multiple)]
public class NotificationsService : INotifications
{
    private class NotificationMessage
    {
        public string MessageContentBase64 { get; set; }
    }

    private ConcurrentDictionary&lt;string, ConcurrentQueue&lt;NotificationMessage&gt;&gt; _messages;

    public NotificationsService()
    {
        _messages = new ConcurrentDictionary&lt;string, ConcurrentQueue&lt;NotificationMessage&gt;&gt;();
    }

    public void Notify(Message message)
    {
        // Grab the notification from the message body
        var queryParams = ParseQueryString(message.Headers.To.Query);
        var body = message.GetReaderAtBodyContents();

        XElement data = XElement.Load(body);

        var queue = _messages.GetOrAdd(queryParams[&quot;id&quot;], key =&gt; new ConcurrentQueue&lt;NotificationMessage&gt;());

        queue.Enqueue(new NotificationMessage
                        {
                            MessageContentBase64 = (string)data,
                        });

        Log.Default.TraceInformation(&quot;Notification from: {0}&quot;, queryParams[&quot;id&quot;]);
    }

    private static IDictionary&lt;string, string&gt; ParseQueryString(string queryString)
    {
        var queryItems = new Dictionary&lt;string, string&gt;(StringComparer.InvariantCultureIgnoreCase);

        queryString = queryString.TrimStart('?');
        string[] strings = queryString.Split('&amp;');

        foreach(string queryItem in strings)
        {
            int equalsIndex = queryItem.IndexOf('=');
            if (equalsIndex &gt;= 0)
            {
                queryItems.Add(queryItem.Substring(0, equalsIndex),
                                queryItem.Substring(equalsIndex + 1));
            }
            else
            {
                queryItems.Add(queryItem, null);
            }
        }

        return queryItems;
    }

    public Message GetNotifications(string id)
    {
        XElement response = new XElement(&quot;notifications&quot;);
        ConcurrentQueue&lt;NotificationMessage&gt; queue;

        Log.Default.TraceInformation(&quot;Checking notifications for: {0}&quot;, id);

        if (_messages.TryGetValue(id, out queue))
        {
            NotificationMessage message;
            while (queue.TryDequeue(out message))
            {
                response.Add(new XElement(&quot;notification&quot;, message.MessageContentBase64));

                Log.Default.TraceInformation(&quot;De-queued notification for: {0}&quot;, id);
            }
        }

        WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.CacheControl] = &quot;no-cache&quot;;
        return WebOperationContext.Current.CreateXmlResponse(response);
    }
}
</pre>
<h2>The Client</h2>
<p>The WP7 application isn’t quite as lucky. I could probably have done something that faked getting the notifications a little better but the simplest solution was to just have a background timer that polls my service and gets the notifications. It then processes these using the normal code path for push notifications in my application.</p>
<p>I really should probably use the reactive extensions (RX) to manage my push notifications in the client as that would make them nice and mockable too but for now this works as a solution and keeps the client code reasonably understandable for demo purposes.</p>
<p>All in all it works quite nicely and means I don’t have to have an internet connection to now demo my application, even with push notifications.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2008/06/transferring-large-files-using-wcf/" rel="bookmark" title="Transferring large files using WCF">Transferring large files using WCF </a></li>
</ol></p>
</div>
]]></content:encoded>
			</item>
		<item>
		<title>Silverlight Navigation With the MVVM Pattern</title>
		<link>http://garfoot.com/blog/2010/09/silverlight-navigation-with-the-mvvm-pattern/</link>
		<comments>http://garfoot.com/blog/2010/09/silverlight-navigation-with-the-mvvm-pattern/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 14:36:28 +0000</pubDate>
		<dc:creator><![CDATA[Robert Garfoot]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[mvvm]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://garfoot.com/blog/?p=304</guid>
		<description><![CDATA[I recently had a query from a customer that was one of those ones that you think “Aha! That’s easy, you just do this”. Then you think a bit more about it and realise that if you want to do it properly it’s not quite as simple as you first thought. This particular query related [&#8230;]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/03/flexible-data-template-support-in-silverlight/" rel="bookmark" title="Flexible Data Template Support in Silverlight">Flexible Data Template Support in Silverlight </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I recently had a query from a customer that was one of those ones that you think “Aha! That’s easy, you just do this”. Then you think a bit more about it and realise that if you want to do it properly it’s not quite as simple as you first thought.</p>
<p>This particular query related to how to use the navigation framework introduced in Silverlight 3 with the MVVM pattern. For those that don’t know the Model-View-ViewModel pattern is a common pattern often used to build Silverlight and WPF applications since it has strong support for databound UIs and provides good abstraction for unit testing and keeping your view logic separate from the view and the model.</p>
<p><span id="more-304"></span></p>
<h2>Enter the Silverlight Navigation Framework</h2>
<p>Handling the page style navigation that we’ve all become used to on the web can be a real pain in RIAs written using Silverlight, Flash or AJAX involving lots of tracking of page clicks using HTML bookmarks and some liberal use of JavaScript. Fortunately Silverlight 3 added a navigation framework to help with this.</p>
<p>This framework works by you adding a Frame element to your root XAML and then creating many Page derived classes. These classes can then navigate between each other by calling into a NavigationService instance that each page inherits from it’s base class.</p>
<p>The issue with MVVM is that page navigation is a view logic, that means that it should sit inside the ViewModel, however the NavigationService is only on the Page class which the ViewModel doesn’t have access to.</p>
<p>Solving this problem is simple, just pass the NavigationService instance to the ViewModel, job done! Well ok, that works if you hate unit testing. If you like unit testing though you may find you have problems then when it comes to testing your ViewModel as you won’t have a NavigationService instance to pass it.</p>
<p>Additionally since many pages are likely to want to do this I’d like to have a reusable approach that doesn’t take much code to reuse.</p>
<h2>The Solution</h2>
<p>The solution I came up with is one of a few different ways you could implement this but this works for me at the moment. Feel free to point out any glaring errors in my design though.</p>
<h3>Wrapping the NavigationService</h3>
<p>First I need to make the NavigationService mockable so I can use it in unit tests. To do this I created a new interface INavigationService that exposes the methods and properties of the NavigationService. This sample version only exposes Navigate() but you could easily expose more as needed.</p>
<pre class="brush: csharp; title: ; notranslate">
    public interface INavigationService
    {
        void Navigate(string url);
    }
</pre>
<p>Not the most complex interface ever devised you’ll agree.</p>
<p>Next I created a class that implemented the interface and took a reference to a System.Windows.Navigation.NavigationService on it’s constructor.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class NavigationService : INavigationService
    {
        private readonly System.Windows.Navigation.NavigationService _navigationService;

        public NavigationService(System.Windows.Navigation.NavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public void Navigate(string url)
        {
            _navigationService.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
        }
    }
</pre>
<h3>Supporting INavigationService in the ViewModel</h3>
<p>Now I had an abstraction I needed to pass the INavigationService to the ViewModel. I wanted to do this in a standard way. I could have made it a constructor argument but I couldn’t always guarantee I’d be there at construction. The best way seemed to be to add a property. I decided to put that property on an interface so I had a defined contract that ViewModels could support.</p>
<p>INavigable.</p>
<pre class="brush: csharp; title: ; notranslate">
    public interface INavigable
    {
        INavigationService NavigationService { get; set; }
    }
</pre>
<p>This interface provides a single property that a ViewModel can implement that will contain a reference to the INavigationService that the ViewModel should use to perform navigation when it needs to.</p>
<h3>Passing the INavigationService to the ViewModel</h3>
<p>Next I need to create an instance of the NavigationService that wraps the System.Windows.Navigation.NavigationService in the Page class and pass that to the ViewModel. I’d like this to be reusable code and if possible I don’t want any code behind in my View.</p>
<p>This is a perfect use for an attached behaviour. What’s one of those? It’s simply an attached property with a property changed handler on it that hooks up code to the DependencyObject that the property gets attached to. It’s simpler than it sounds and is a nice way of making reusable logic that you want to attach to objects in XAML.</p>
<p>The Navigator.</p>
<pre class="brush: csharp; title: ; notranslate">
    public static class Navigator
    {
        public static INavigable GetSource(DependencyObject obj)
        {
            return (INavigable)obj.GetValue(SourceProperty);
        }

        public static void SetSource(DependencyObject obj, INavigable value)
        {
            obj.SetValue(SourceProperty, value);
        }

       public static readonly DependencyProperty SourceProperty =
            DependencyProperty.RegisterAttached(&quot;Source&quot;, typeof(INavigable), typeof(Navigator), new PropertyMetadata(OnSourceChanged));

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Page page = (Page) d;

            page.Loaded += PageLoaded;
        }

        private static void PageLoaded(object sender, RoutedEventArgs e)
        {
            Page page = (Page)sender;

            INavigable navSource = GetSource(page);

            if (navSource != null)
            {
                navSource.NavigationService = new NavigationService(page.NavigationService);
            }
        }
    }
</pre>
<p>This class provides a single attached property definition of the type INavigable. This property has a handler that when invoked grabs the DependencyObject you are attaching the property to and hooks up it’s Loaded event.</p>
<p>So when you attach this property to a Page instance in XAML it will fire off the PageLoaded method when the Page you attach it to loads. In the page load handler I then query the Page instance for the Source attached property. Remember that this property is of type INavigable. If the source supports INavigable I then create a new instance of the NavigationService, wrapping the Page’s instance and set it on the source using the INavigable.NavigationService property.</p>
<p>And there we have it, a reusable way of attaching the navigation service instance for a Page to the Page&#8217;s view model.</p>
<h3>The View XAML</h3>
<p>And finally using the attached property is a case of assigning the ViewModel to the DataContext of the Page as normal and then doing this.</p>
<pre class="brush: xml; highlight: [8,11]; title: ; notranslate">
&lt;navigation:Page x:Class=&quot;SLNavigation.Page1&quot;
           xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
           xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
           xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
           xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
           mc:Ignorable=&quot;d&quot;
           xmlns:navigation=&quot;clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation&quot;
           xmlns:SLNavigation=&quot;clr-namespace:SLNavigation&quot;
           d:DesignWidth=&quot;640&quot; d:DesignHeight=&quot;480&quot;
           Title=&quot;Page1 Page&quot;
           SLNavigation:Navigator.Source=&quot;{Binding}&quot;
    &gt;
</pre>
<h2>Summary</h2>
<p>So that’s it, my solution. I think it’s reasonable, it minimised the amount of code needed in the View code behind to nil, makes the only code you need on the ViewModel is to derive from and implement INavigable which is one property and to put an attached property on the Page in the XAML. It keeps a good separate of concerns as the ViewModel is still unit testable but it can now support navigation.</p>
<p>Let me know what you think.</p>
<p>Sample code: <a href="http://garfoot.com/samples/NavigationSample.zip">NavigationSample</a></p>
<p><strong>*edit*</strong> Added a sample</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="http://garfoot.com/blog/2010/03/flexible-data-template-support-in-silverlight/" rel="bookmark" title="Flexible Data Template Support in Silverlight">Flexible Data Template Support in Silverlight </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://garfoot.com/blog/2010/09/silverlight-navigation-with-the-mvvm-pattern/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>
