<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Andy Wigley</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/andy_wigley/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/andy_wigley/feed.xml</link>
    <description>Mobile App development and more...</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:14:24 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Windows Apps JumpStart Publish Hack</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/windows-apps-jumpstart-publish-hack</link>
      <pubDate>Wed, 10 Sep 2014 17:29:36 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2014/09/10/windows-apps-jumpstart-publish-hack/</guid>
      <description><![CDATA[Don&rsquo;t forget, if you can get to London on Saturday September 20th, come to our Publish Hack at...]]></description>
      <content:encoded><![CDATA[Don&rsquo;t forget, if you can get to London on Saturday September 20th, come to our Publish Hack at Microsoft&rsquo;s Cardinal Place offices near Victoria Station and get your app published to store! Our goal for this day is to make it a fun, informal day where you can overcome those last blockers and issues that are preventing you getting over those last yards to publication. There will be fun, and pizza, and beer&hellip;.oh, yes &ndash; and prizes!

We will have experts from Microsoft and from the developer community there to help you, including elite Windows App engineers from our App Consult program.

Did I mention prizes? Yes, as if the fun of taking part wasn&rsquo;t enough, we&rsquo;re going to give you additional incentive to take part by offering prizes, including:

<strong>- Nokia Lumia 1020 phones</strong>

<strong>- Nokia Lumia 1520 phablets</strong>

<strong>- Nokia Contactless Charging units</strong>

<strong>- Arc Mice </strong>

<strong>- Arc Keyboards </strong>

<strong>- A Goodie bag for every single developer that publishes an app on the day!</strong>

The prizes will be awarded for quality, progress made and for good old-fashioned sweat and tears.

Details and registration page:

<b>Windows Apps JumpStart Publish Hack     <br></b>Saturday 20 Sep - 9AM - 9PM     <br><a href="https://aka.ms/winappspublishhack">https://aka.ms/winappspublishhack</a>&nbsp;

<p>Hope you can come along!</p>]]></content:encoded>
    </item>
    <item>
      <title>Windows Apps JumpStart LIVE Events Series</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/windows-apps-jumpstart-live-events-series</link>
      <pubDate>Tue, 12 Aug 2014 01:32:44 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2014/08/12/windows-apps-jumpstart-live-events-series/</guid>
      <description><![CDATA[We&rsquo;re starting a new series of events for UK developers that will help you on the journey from...]]></description>
      <content:encoded><![CDATA[We&rsquo;re starting a new series of events for UK developers that will help you on the journey from initial interest in developing apps for Windows 8 and Windows Phone right the way through to publishing an app to the Windows Store. You can join into the series at whichever point makes sense to you, so whether you&rsquo;ve never opened Visual Studio before or written a line of C#, or you&rsquo;re a developer who has already written software using out tools and languages but are new to apps, we can help you get to that point where you&rsquo;re publishing your first app into our store. And we&rsquo;re going to repeat the series of events every quarter, so you can jump on and off the series and attend events at whatever pace makes sense to you.

We start with two one-hour webinars run back-to-back:

<b><u>Webinar 1: Windows Apps JumpStart LIVE Series - Kick Starter Webinar for the non C#/XAML developer:</u> </b>This one hour webinar is aimed at developers who are completely new to Visual Studio, XAML, C# and .NET. This will give you what they need to get started with downloading Visual Studio, a little bit of knowledge of C# and the structure of a XAML-based app.

<b><u>Webinar 2: Windows Apps JumpStart LIVE Series - JumpStart Webinar: Building Apps with C# and XAML: </u></b>This one hour webinar follows on straight away after the previous one. It is aimed at developers who are new to Windows Store app development, but who have some experience of developing software using .NET, or for those who have attended the previous webinar.<b><u></u></b>

Following on from the webinars, we have a one-day dev camp:

<b><u>Dev camp: Windows Apps JumpStart LIVE Series: Windows Apps Dev Workshop        <br></u></b>This one day event will be help at Microsoft&rsquo;s offices near Victoria Station, London, running 9:30 &ndash; 18:00. At this workshop, you will learn how to program Windows and Windows Phone apps, including universal apps that run on both. There will be Hands-on Labs available, and you can get tips and advice from Microsoft experts and from peers in the developer community.

And following on from that, we have a one-day Publish hackathon:

<b><u>Publish event: Windows Apps JumpStart LIVE Series: Publish Hackathon        <br></u></b>This informal one-day event will also be held at Microsoft&rsquo;s building in London, running 9:00 &ndash; 21:00 on a Saturday. This is a fun 12 hour event encouraging developers to bring their existing projects (apps/cloud projects) to polish and publish through to the last mile with help from Microsoft and community experts. 

<p>First events are coming up fast!:</p><ul>   <li><strong>Webinar 1</strong>: Thursday 21<sup>st</sup> August, 10:00 &ndash; 11:00       <br>Registration: <a href="https://aka.ms/winappswebinar1">https://aka.ms/winappswebinar1</a></li>    <li><strong>Webinar 2</strong>: Thursday 21<sup>st</sup> August 11:00 &ndash; 12:00       <br>Registration: <a href="https://aka.ms/winappswebinar2">https://aka.ms/winappswebinar2</a></li>    <li><strong>Dev camp</strong>: Date to be announced soon&hellip;      <br>Registration: *tbd* </li>    <li><strong>Publish hackathon</strong>: Saturday September 20<sup>th</sup> 9:00 &ndash; 21:00       <br>Registration: <a href="https://aka.ms/winappspublishhack">https://aka.ms/winappspublishhack</a></li> </ul><p>Come along and join us &ndash; and if not this quarter, remember we are repeating these events throughout the year so you can join us when you can!</p>]]></content:encoded>
    </item>
    <item>
      <title>SQLiteWinRT: Opening databases shipped as app content or from an SD Card</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/sqlitewinrt-opening-databases-shipped-as-app-content-or-from-an-sd-card</link>
      <pubDate>Wed, 11 Dec 2013 10:27:05 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/12/11/sqlitewinrt-opening-databases-shipped-as-app-content-or-from-an-sd-card/</guid>
      <description><![CDATA[Recently, I was asked about opening a database file inserted into a device on an SD card. I had to...]]></description>
      <content:encoded><![CDATA[<p>Recently, I was asked about opening a database file inserted into a device on an SD card. I had to make a slight change to the SQLWinRT wrapper to enable it, so this post explains how, and also looks at opening databases shipped in the app package as content.</p>  <h2>Opening databases shipped as content</h2>  <p>You can include a prepopulated SQLite database in your Windows 8.x or Windows Phone app package. When the user installs the app, the database file ends up in the App Install folder where you can open it from your code – but only in a read-only fashion:</p>  <pre class="code"><span style="background: white; color: blue;">public static async void </span><span style="background: white; color: black;">LoadDatabase()
{
    </span><span style="background: white; color: green;">// Get a reference to the SQLite database
    </span><span style="background: white; color: black;">db = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: black;">SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">Database</span><span style="background: white; color: black;">(
        Windows.ApplicationModel.</span><span style="background: white; color: rgb(43, 145, 175);">Package</span><span style="background: white; color: black;">.Current.InstalledLocation, 
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;customers.sqlite&quot;</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.OpenAsync(SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">SqliteOpenMode</span><span style="background: white; color: black;">.OpenRead);

    </span><span style="background: white; color: green;">// PRAGMA temp_files=2 causes temporary files to be created in memory
    // rather than in a physicalfile in the same folder as the database
    // Note that temp files only really get used if you are going to do 
    // complicated JOINs etc
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;PRAGMA temp_files=2&quot;</span><span style="background: white; color: black;">);
}</span></pre>

<p>If you want to have read-write access to the database, you must copy it from the install folder to the local folder first.</p>

<pre class="code"><span style="background: white; color: blue;">async </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">CopyDatabaseAsync()
{
    </span><span style="background: white; color: green;">// Has the database been copied already?
    </span><span style="background: white; color: blue;">try
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">await </span><span style="background: white; color: rgb(43, 145, 175);">ApplicationData</span><span style="background: white; color: black;">.Current.LocalFolder.GetFileAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;customers.sqlite&quot;</span><span style="background: white; color: black;">);
        </span><span style="background: white; color: green;">// No exception? It exists...
        </span><span style="background: white; color: blue;">return</span><span style="background: white; color: black;">;
    }
    </span><span style="background: white; color: blue;">catch </span><span style="background: white; color: black;">(System.IO.</span><span style="background: white; color: rgb(43, 145, 175);">FileNotFoundException</span><span style="background: white; color: black;">)
    {   </span><span style="background: white; color: green;">// Expected response - no-op 
    </span><span style="background: white; color: black;">}

    </span><span style="background: white; color: rgb(43, 145, 175);">StorageFile </span><span style="background: white; color: black;">dbfile = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: rgb(43, 145, 175);">StorageFile</span><span style="background: white; color: black;">.GetFileFromApplicationUriAsync(
        </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">Uri</span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;ms-appx:///customers.sqlite&quot;</span><span style="background: white; color: black;">));
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">dbfile.CopyAsync(</span><span style="background: white; color: rgb(43, 145, 175);">ApplicationData</span><span style="background: white; color: black;">.Current.LocalFolder);
}</span></pre>

<h2>Opening a Database on an SD Card</h2>

<p>A database file that you open from an SD Card is related to the previous case in that it is read-only. You cannot write to any file on an SD Card from any app in Windows Phone 8. </p>

<p>I haven’t researched it thoroughly, but you should be able to open a database file on removable storage in a Windows 8.x Store app. You will have to request the Removable Storage capability in the app manifest, and declare the file extensions you want to access in the app manifest as well. Then you should be able to get a StorageFile reference to the database file using techniques similar to those discussed here: <a title="http://lunarfrog.com/blog/2012/10/27/external-storage-devices/" href="http://lunarfrog.com/blog/2012/10/27/external-storage-devices/">http://lunarfrog.com/blog/2012/10/27/external-storage-devices/</a>&#160;&#160; . When I’ve tried it, I’ll update this post!</p>

<p>What I have tried though, is doing this on a Windows Phone 8 device that has an SD card slot, such as the Nokia Lumia 820. As with Windows 8, you have to declare the file extensions you want to access in the manifest. For example, add the following after the closing <strong>&lt;/Tokens&gt;</strong> tag:</p>

<pre class="code"><span style="background: white; color: blue;">    &lt;</span><span style="background: white; color: rgb(163, 21, 21);">Extensions</span><span style="background: white; color: blue;">&gt;
      &lt;</span><span style="background: white; color: rgb(163, 21, 21);">FileTypeAssociation </span><span style="background: white; color: red;">Name</span><span style="background: white; color: blue;">=</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">sqlite</span><span style="background: white; color: black;">&quot; </span><span style="background: white; color: red;">TaskID</span><span style="background: white; color: blue;">=</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">_default</span><span style="background: white; color: black;">&quot; </span><span style="background: white; color: red;">NavUriFragment</span><span style="background: white; color: blue;">=</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">fileToken=%s</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">&gt;
        &lt;</span><span style="background: white; color: rgb(163, 21, 21);">SupportedFileTypes</span><span style="background: white; color: blue;">&gt;
          &lt;</span><span style="background: white; color: rgb(163, 21, 21);">FileType </span><span style="background: white; color: red;">ContentType</span><span style="background: white; color: blue;">=</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">application/sqlite</span><span style="background: white; color: black;">&quot;</span><span style="background: white; color: blue;">&gt;</span><span style="background: white; color: black;">.sqlite</span><span style="background: white; color: blue;">&lt;/</span><span style="background: white; color: rgb(163, 21, 21);">FileType</span><span style="background: white; color: blue;">&gt;
        &lt;/</span><span style="background: white; color: rgb(163, 21, 21);">SupportedFileTypes</span><span style="background: white; color: blue;">&gt;
      &lt;/</span><span style="background: white; color: rgb(163, 21, 21);">FileTypeAssociation</span><span style="background: white; color: blue;">&gt;
    &lt;/</span><span style="background: white; color: rgb(163, 21, 21);">Extensions</span><span style="background: white; color: blue;">&gt;</span></pre>

<p>Then in your code, you can open a read-only connection to the database as follows:</p>

<pre class="code"><span style="background: white; color: blue;">public static async void </span><span style="background: white; color: black;">LoadDatabase()
{
    </span><span style="background: white; color: green;">// Get a reference to the SQLite database
    </span><span style="background: white; color: rgb(43, 145, 175);">ExternalStorageDevice </span><span style="background: white; color: black;">_sdCard = 
        (</span><span style="background: white; color: blue;">await </span><span style="background: white; color: rgb(43, 145, 175);">ExternalStorage</span><span style="background: white; color: black;">.GetExternalStorageDevicesAsync())
        .FirstOrDefault();

    </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(_sdCard == </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">)
    {
        </span><span style="background: white; color: rgb(43, 145, 175);">MessageBox</span><span style="background: white; color: black;">.Show(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;No SD Cards found&quot;</span><span style="background: white; color: black;">);
        </span><span style="background: white; color: blue;">return</span><span style="background: white; color: black;">;
    }
    </span><span style="background: white; color: blue;">else
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: rgb(43, 145, 175);">ExternalStorageFile </span><span style="background: white; color: black;">dbStoragefile = 
            </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">_sdCard.GetFileAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;customers.sqlite&quot;</span><span style="background: white; color: black;">);
        db = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: black;">SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">Database</span><span style="background: white; color: black;">(dbStoragefile.Path);
    }

    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.OpenAsync(SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">SqliteOpenMode</span><span style="background: white; color: black;">.OpenRead);

    </span><span style="background: white; color: green;">// PRAGMA temp_files=2 causes temporary files to be created in memory
    // rather than in a physicalfile in the same folder as the database 
    // Note that temp files only really get used if you are going to do 
    // complicated JOINs etc
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;PRAGMA temp_files=2&quot;</span><span style="background: white; color: black;">);
}</span></pre>

<p><strong>Important</strong>: I had to modify the wrapper code posted up on <a href="http://sqlwinrt.codeplex.com">http://sqlwinrt.codeplex.com</a> in order to enable this usage. I added a new override of the <strong>Database</strong> object constructor that just takes the path to the database file as a string. Earlier versions had one override of the constructor that took a <strong>Windows.Storage.StorageFile</strong> parameter and another that took a <strong>Windows.Storage.StorageFolder</strong> and the filename as string, but neither of those were usable since the <strong>ExternalStorageFile</strong> object is not as you might expect a derivative of Windows.Storage.StorageFile, but is instead in the <strong>Microsoft.Phone.Storage</strong> namespace – hence I had to create a new constructor.</p>

<p>Download the latest version of the wrapper code from <a href="http://sqlwinrt.codeplex.com/">http://sqlwinrt.codeplex.com</a> to get this update – note that this is built against SQLite version 3.8.2 – make sure you update to this version using the Visual Studio – Tools – Extensions and Updates wizard.</p>

<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:f2d39330-5bd4-4848-b9dd-7cd684ecdaa3" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p>Download the <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/6746.SQLiteReadOnlyDemo_23618A8D.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/6746.SQLiteReadOnlyDemo_5F00_23618A8D.zip" target="_blank">sample project here</a></p></div>

<p>Note that it covers both scenarios covered in this post. At the top of app.xaml.cs there is a compile time symbol <strong>#define USE_SDCARD</strong> – comment this out to test the ‘database shipped as content’, or leave it in to test the SD card access. You’ll need a real device for the latter and before testing the app use your PC to copy the customers.sqlite file from the project onto the sd card and insert into your phone. Sadly, the emulator does not emulate a removable storage card!</p>]]></content:encoded>
    </item>
    <item>
      <title>NDC London 2013</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/ndc-london-2013</link>
      <pubDate>Fri, 06 Dec 2013 08:34:28 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/12/06/ndc-london-2013/</guid>
      <description><![CDATA[I just spent 3 enjoyable days at the NDC conference in London. NDC usually stands for Norwegian...]]></description>
      <content:encoded><![CDATA[<p>I just spent 3 enjoyable days at the NDC conference in London. NDC usually stands for Norwegian Developer Conference which happens every June in Oslo, Norway and which is a popular conference – I really hope that I can speak there next June! The organisers of that, NDC Conferences, decided to bring their show to London – hence this weeks’ show – with NDC modified slightly to stand for ‘New Developer’s Conference’</p>  <p>And what a show! – great speakers, great food, large, comfortable venue, loads of sessions and an awesome party. Congratulations to NDC for putting on a great event, and I look forward to supporting them in future years.</p>  <p>My own contribution was two sessions: Windows Phone Networking Toolkit which was an update of a session I gave at TechEd this year, and which works through various topics related to effective network programming on Windows Phone, and Creating Killer Windows Phone Apps, a brand new session looking at ways to improve the quality of your apps. That went well and I look forward to repeating it somewhere soon. It looks at correct use of the animations in the Windows Phone Toolkit, programming Push Notifications using Windows Azure Notifications Hubs, localizing your app with the Multilingual Toolkit and reducing your memory footprint to improve your apps performance on low memory devices.</p>  <p>The slides for the sessions are available here:</p>  <div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:bdb780fc-bf38-46f9-af83-8f2413b5e64e" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/0741.WindowsPhoneNetworking-Wigley_53BE0DF2.pdf" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/0741.WindowsPhoneNetworking_2D00_Wigley_5F00_53BE0DF2.pdf" target="_blank">Windows Phone Networking Toolkit</a></p></div>  <div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:094a06b3-70c0-4eb2-8dad-8d052a8f7194" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/6445.KillerWindowsPhoneApps-Wigley_1D2FA107.pdf" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/6445.KillerWindowsPhoneApps_2D00_Wigley_5F00_1D2FA107.pdf" target="_blank">Creating Killer Windows Phone Apps</a></p></div>]]></content:encoded>
    </item>
    <item>
      <title>How to massively improve SQLite Performance (using SqlWinRT)</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/how-to-massively-improve-sqlite-performance-using-sqlwinrt</link>
      <pubDate>Thu, 21 Nov 2013 14:29:15 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/11/21/how-to-massively-improve-sqlite-performance-using-sqlwinrt/</guid>
      <description><![CDATA[Use ConfigureAwait(false) on calls to SqlWinRT async methods to improve INSERT performance up to 145...]]></description>
      <content:encoded><![CDATA[<p><em>Use ConfigureAwait(false) on calls to SqlWinRT async methods to improve INSERT performance up to 145 times, and SELECT performance up to 80 times</em>&#160;</p>  <div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:2e361a7e-626d-4c75-89be-792877d5d9bc" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p>Sample project: <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/2063.SQLitePerformance_4B258A3D.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/2063.SQLitePerformance_5F00_4B258A3D.zip" target="_blank">SQLitePerformance.zip</a></p></div>  <p>I have been seeing a few comments by people complaining of poor performance when executing SELECT statements against a SQLite database using <a href="http://sqlwinrt.codeplex.com">the SQLWinRT wrapper</a>, or when adding new records using multiple consecutive INSERT statements.</p>  <p>With many relational databases, poor performance on INSERT can often be rectified just by wrapping all your operations within a single transaction. If you don’t explicitly declare a transaction when programming against SQLite, the database engine creates an implicit transaction for each statement execution and that has an overhead associated with it, so by wrapping all your INSERTs inside a single transaction, you would expect a performance boost.</p>  <p>With SELECT operations, poor performance is often just down to not having the correct keys defined. If you have a statement such as SELECT * FROM CUSTOMER WHERE NAME = ‘CONTOSO’ and you execute it on a database where you have not defined a key on the NAME column, the only way the database engine can find the required record is to start at the first record and read sequentially down the table until it reaches the end in order to select the rows to return (called a ‘Table Scan’). If you simply want to select all the records in a table (SELECT * FROM CUSTOMER), then you can’t avoid the Table Scan – in fact that’s what you want – so you would expect that there wasn’t very much you could do to improve performance in that case.</p>  <p>Well – that’s the theory. I set about building a simple demo to demonstrate these points, but it didn’t turn out quite how I expected! It turns out that, important though the points already mentioned are, the most important factor <strong><u>BY FAR</u></strong> is how you call the async methods of the SQLWinRT API! Read on…</p>  <h2>The Test Program</h2>  <p>For my test program, I was inspired by this post on Stack Overflow: <a href="http://stackoverflow.com/questions/1711631/how-do-i-improve-the-performance-of-sqlite">How do I improve the performance of SQLite</a>. That post is quite old and is talking about C++ dev, so not directly relevant to Windows Phone or Windows Store app development using managed code, but I liked the test case, which was to take a large dataset from the City of Toronto’s publically available transportation data. Unfortunately, the exact same dataset used in the original post isn’t available anymore, so I couldn’t do a direct comparison, but they did have the Transportation Trips dataset, containing 128982 records that we can first insert into a SQLite database, and then select them out again.</p>  <h2>SQLite Bulk Insert</h2>  <p>The dataset is in the form of a CSV text file, representing 128982 rows, each containing 8 columns. The code to read the file and extract the values&#160; looks like this:</p>  <pre class="code"><span style="background: white; color: black;">SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">Database </span><span style="background: white; color: black;">db;

</span><span style="background: white; color: blue;">private async void </span><span style="background: white; color: black;">Button_Start_Click(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">RoutedEventArgs </span><span style="background: white; color: black;">e)
{
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Route_ID;
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Service_ID;
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Trip_ID;
    </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">Trip_Headsign;
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Direction_ID;
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Block_ID;
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">Shape_ID;
    </span><span style="background: white; color: blue;">bool </span><span style="background: white; color: black;">Wheelchair_Accessible;

    Button_Start.IsEnabled = </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">;

    </span><span style="background: white; color: green;">/*********************************************/
    /* Open the Database and create the Schema */
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">LoadDatabase();

    </span><span style="background: white; color: rgb(43, 145, 175);">Stopwatch </span><span style="background: white; color: black;">sw = </span><span style="background: white; color: rgb(43, 145, 175);">Stopwatch</span><span style="background: white; color: black;">.StartNew();
    </span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">n = 0;

    </span><span style="background: white; color: green;">// Prepare statement
    </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">statement = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.PrepareStatementAsync(
        </span><span style="background: white; color: rgb(163, 21, 21);">@&quot;INSERT INTO TTC (id, Route_ID, Service_ID, Trip_ID, 
                           Trip_Headsign, Direction_ID, Block_ID, 
                           Shape_ID, Wheelchair_Accessible) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;</span><span style="background: white; color: black;">))
    {
        </span><span style="background: white; color: green;">// Start transaction
        </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;BEGIN TRANSACTION&quot;</span><span style="background: white; color: black;">);

        </span><span style="background: white; color: green;">/*********************************************/
        /* Open input file and import into Database*/
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">inputfile = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">Windows.ApplicationModel.</span><span style="background: white; color: rgb(43, 145, 175);">Package</span><span style="background: white; color: black;">.Current.
            InstalledLocation.GetFileAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;trips.txt&quot;</span><span style="background: white; color: black;">);
        </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">inputStream = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">inputfile.OpenSequentialReadAsync())
        {
            </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(43, 145, 175);">StreamReader </span><span style="background: white; color: black;">rdr = 
                </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">StreamReader</span><span style="background: white; color: black;">(inputStream.AsStreamForRead()))
            {
                </span><span style="background: white; color: blue;">while </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">)
                {
                    </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">inputline = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">rdr.ReadLineAsync();
                    </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(inputline == </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">)
                        </span><span style="background: white; color: blue;">break</span><span style="background: white; color: black;">;

                    </span><span style="background: white; color: green;">// Discard line 0 - header line
                    </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(n &gt; 0)
                    {
                        </span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">[] fields = inputline.Split(</span><span style="background: white; color: blue;">new char</span><span style="background: white; color: black;">[] { </span><span style="background: white; color: rgb(163, 21, 21);">',' </span><span style="background: white; color: black;">});

                        Route_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[0]); ;
                        Service_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[1]);
                        Trip_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[2]);
                        Trip_Headsign = fields[3];
                        Direction_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[4]);
                        Block_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[5]);
                        Shape_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[6]);
                        Wheelchair_Accessible = fields[7] == </span><span style="background: white; color: rgb(163, 21, 21);">&quot;1&quot; </span><span style="background: white; color: black;">? </span><span style="background: white; color: blue;">true </span><span style="background: white; color: black;">: </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">;

                        </span><span style="background: white; color: green;">/* Bind parameter values and Insert */
                        </span><span style="background: white; color: black;">statement.Reset();
                        statement.BindIntParameterAt(1, n);
                        statement.BindIntParameterAt(2, Route_ID);
                        statement.BindIntParameterAt(3, Service_ID);
                        statement.BindIntParameterAt(4, Trip_ID);
                        statement.BindTextParameterAt(5, Trip_Headsign);
                        statement.BindIntParameterAt(6, Direction_ID);
                        statement.BindIntParameterAt(7, Block_ID);
                        statement.BindIntParameterAt(8, Shape_ID);
                        statement.BindIntParameterAt(9, Wheelchair_Accessible ? 1 : 0);

                        </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">statement.StepAsync();
                    }

                    n++;

                    </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(n % 100 == 0)
                    {
                        progressBar.Value = n;
                    }
                }
            }
        }

        </span><span style="background: white; color: green;">// Commit transaction
        </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;COMMIT TRANSACTION&quot;</span><span style="background: white; color: black;">);
    }

    db.Dispose();
    db = </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">;

    </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">report = </span><span style="background: white; color: rgb(43, 145, 175);">String</span><span style="background: white; color: black;">.Format(
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Inserted {0:d} records in {1:0.00} seconds&quot;</span><span style="background: white; color: black;">, 
        n - 1, 
        (</span><span style="background: white; color: blue;">double</span><span style="background: white; color: black;">)sw.ElapsedMilliseconds / 1000);
    </span><span style="background: white; color: rgb(43, 145, 175);">MessageBox</span><span style="background: white; color: black;">.Show(report);

    Button_Start.IsEnabled = </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">;
}

</span><span style="background: white; color: blue;">private async </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">LoadDatabase()
{
    db = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: black;">SQLiteWinRT.</span><span style="background: white; color: rgb(43, 145, 175);">Database</span><span style="background: white; color: black;">(
        </span><span style="background: white; color: rgb(43, 145, 175);">ApplicationData</span><span style="background: white; color: black;">.Current.LocalFolder, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;sqliteperf.db&quot;</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.OpenAsync();

    </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">sql = </span><span style="background: white; color: rgb(163, 21, 21);">@&quot;
        CREATE TABLE IF NOT EXISTS TTC 
            (id INTEGER PRIMARY KEY, 
                Route_ID INTEGER, 
                Service_ID INTEGER, 
                Trip_ID INTEGER, 
                Trip_Headsign TEXT,
                Direction_ID INTEGER, 
                Block_ID INTEGER, 
                Shape_ID INTEGER, 
                Wheelchair_Accessible BOOL)&quot;</span><span style="background: white; color: black;">;

    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(sql);
}</span></pre>


<p>Using this code, and by commenting out lines here and there as appropriate, we can test three scenarios:</p>

<ul>
  <li>Processing the input file but not inserting records in the database (this just gives us the time for the file processing) </li>

  <li>Uncomment the call to StepAsync() to Insert each record into the database individually </li>

  <li>Uncomment the lines executing the BEGIN TRANSACTION, END TRANSACTION statements so all records are inserted inside a single transaction</li>
</ul>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/3681.testrunner_65F440FA.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/3681.testrunner_5F00_65F440FA.png"><img title="testrunner" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="testrunner" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/0042.testrunner_thumb_6C3B1788.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/0042.testrunner_5F00_thumb_5F00_6C3B1788.png" width="222" height="367" /></a>&#160; <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4744.Transaction_40F68081.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4744.Transaction_5F00_40F68081.png"><img title="Transaction" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="Transaction" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5153.Transaction_thumb_19BC374C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5153.Transaction_5F00_thumb_5F00_19BC374C.png" width="223" height="369" /></a></p>

<p>And the results? Well, not great, to be honest:</p>

<table cellspacing="0" cellpadding="2" width="626" border="0"><tbody>
    <tr>
      <td valign="top" width="342"><strong>Test</strong></td>

      <td valign="top" width="159"><strong>Total Time (seconds) – 128982 records</strong></td>

      <td valign="top" width="123"><strong>Insert Time per record (ms)</strong></td>
    </tr>

    <tr>
      <td valign="top" width="342">Process records – no insert</td>

      <td valign="top" width="159">7</td>

      <td valign="top" width="123">-</td>
    </tr>

    <tr>
      <td valign="top" width="342">Insert records individually</td>

      <td valign="top" width="160">6307</td>

      <td valign="top" width="123">49</td>
    </tr>

    <tr>
      <td valign="top" width="340">Insert records within a containing transaction</td>

      <td valign="top" width="175">3177</td>

      <td valign="top" width="145">25</td>
    </tr>
  </tbody></table>

<p>Although wrapping all the inserts into a single transaction halves the time it takes to insert the 128982 records compared to separate operations (where the database engine will activate an implicit transaction for every insert), we are still only getting 25ms per insert, or 40 operations per second. That’s not too impressive.</p>

<h3>Trying ConfigureAwait(false)</h3>

<p>Those performance figures are disappointing and make bulk insert operations in a Windows Phone or Windows Store app impractical. However, look what happens when we make a subtle change to the main loop of code:</p>

<pre class="code"><span style="background: white; color: rgb(43, 145, 175);">Stopwatch </span><span style="background: white; color: black;">sw = </span><span style="background: white; color: rgb(43, 145, 175);">Stopwatch</span><span style="background: white; color: black;">.StartNew();
</span><span style="background: white; color: blue;">int </span><span style="background: white; color: black;">n = 0;

</span><span style="background: white; color: green;">// Prepare statement
</span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">statement = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.PrepareStatementAsync(
    </span><span style="background: white; color: rgb(163, 21, 21);">@&quot;INSERT INTO TTC (id, Route_ID, Service_ID, Trip_ID, Trip_Headsign, 
                        Direction_ID, Block_ID, Shape_ID, Wheelchair_Accessible) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;</span><span style="background: white; color: black;">))
{
    </span><span style="background: white; color: green;">// Start transaction
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;BEGIN TRANSACTION&quot;</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: green;">/*********************************************/
    /* Open input file and import into Database*/
    </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">inputfile = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">Windows.ApplicationModel.</span><span style="background: white; color: rgb(43, 145, 175);">Package</span><span style="background: white; color: black;">.Current.
        InstalledLocation.GetFileAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;trips.txt&quot;</span><span style="background: white; color: black;">);
    </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">inputStream = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">inputfile.OpenSequentialReadAsync())
    {
        </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(43, 145, 175);">StreamReader </span><span style="background: white; color: black;">rdr = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">StreamReader</span><span style="background: white; color: black;">(inputStream.AsStreamForRead()))
        {
            </span><span style="background: white; color: blue;">while </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">)
            {
                </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">inputline = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">rdr.ReadLineAsync();
                </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(inputline == </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">)
                    </span><span style="background: white; color: blue;">break</span><span style="background: white; color: black;">;

                </span><span style="background: white; color: green;">// Discard line 0 - header line
                </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(n &gt; 0)
                {
                    </span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">[] fields = inputline.Split(</span><span style="background: white; color: blue;">new char</span><span style="background: white; color: black;">[] { </span><span style="background: white; color: rgb(163, 21, 21);">',' </span><span style="background: white; color: black;">});

                    Route_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[0]); ;
                    Service_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[1]);
                    Trip_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[2]);
                    Trip_Headsign = fields[3];
                    Direction_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[4]);
                    Block_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[5]);
                    Shape_ID = </span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.Parse(fields[6]);
                    Wheelchair_Accessible = fields[7] == </span><span style="background: white; color: rgb(163, 21, 21);">&quot;1&quot; </span><span style="background: white; color: black;">? </span><span style="background: white; color: blue;">true </span><span style="background: white; color: black;">: </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">;

                    </span><span style="background: white; color: green;">/* Bind parameter values and Insert */
                    </span><span style="background: white; color: black;">statement.Reset();
                    statement.BindIntParameterAt(1, n);
                    statement.BindIntParameterAt(2, Route_ID);
                    statement.BindIntParameterAt(3, Service_ID);
                    statement.BindIntParameterAt(4, Trip_ID);
                    statement.BindTextParameterAt(5, Trip_Headsign);
                    statement.BindIntParameterAt(6, Direction_ID);
                    statement.BindIntParameterAt(7, Block_ID);
                    statement.BindIntParameterAt(8, Shape_ID);
                    statement.BindIntParameterAt(9, Wheelchair_Accessible ? 1 : 0);

                    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">statement.StepAsync().AsTask().ConfigureAwait(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">);
                }

                n++;
                </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(n % 100 == 0)
                {
                    Dispatcher.BeginInvoke(()=&gt;progressBar.Value = n);
                }
            }
        }
    }

    </span><span style="background: white; color: green;">// Commit transaction
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;COMMIT TRANSACTION&quot;</span><span style="background: white; color: black;">);
}

db.Dispose();
db = </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">;

Dispatcher.BeginInvoke(() =&gt;
    {
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">report = </span><span style="background: white; color: rgb(43, 145, 175);">String</span><span style="background: white; color: black;">.Format(
            </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Inserted {0:d} records in {1:0.00} seconds&quot;</span><span style="background: white; color: black;">, 
            n - 1, (</span><span style="background: white; color: blue;">double</span><span style="background: white; color: black;">)sw.ElapsedMilliseconds / 1000);
        </span><span style="background: white; color: rgb(43, 145, 175);">MessageBox</span><span style="background: white; color: black;">.Show(report);

        Button_Start.IsEnabled = </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">;
    });
}</span></pre>


<p>The main – and significant change above – is that the StepAsync() method is now called in a different way:</p>

<pre class="code"><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">statement.StepAsync().AsTask().ConfigureAwait(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">);</span></pre>

<p>In addition, the code that ‘touches’ the UI, such as the MessageBox.Show() call, and the code setting the ProgressBar is now called using Dispatcher.BeginInvoke(Action a). This is necessary because the change to how StepAsync() is called has a knock-on effect of causing the code to end up executing on a background thread – I will explain more on this shortly.</p>

<p>What does this do to the timings?:</p>

<table cellspacing="0" cellpadding="2" width="626" border="0"><tbody>
    <tr>
      <td valign="top" width="353"><strong>Test</strong></td>

      <td valign="top" width="158"><strong>Total Time (seconds) – 128982 records</strong></td>

      <td valign="top" width="113"><strong>Insert Time per record (ms)</strong></td>
    </tr>

    <tr>
      <td valign="top" width="353">Process records – no insert</td>

      <td valign="top" width="158">7</td>

      <td valign="top" width="113">-</td>
    </tr>

    <tr>
      <td valign="top" width="353">Insert records individually</td>

      <td valign="top" width="158">6307</td>

      <td valign="top" width="113">49</td>
    </tr>

    <tr>
      <td valign="top" width="353">Insert records within a containing transaction</td>

      <td valign="top" width="158">3206</td>

      <td valign="top" width="113">25</td>
    </tr>

    <tr>
      <td valign="top" width="353">Insert individually <strong>with ConfigureAwait(false)</strong></td>

      <td valign="top" width="158">2791</td>

      <td valign="top" width="113">21</td>
    </tr>

    <tr>
      <td valign="top" width="353">Insert within a transaction <strong>with ConfigureAwait(false)</strong></td>

      <td valign="top" width="158">55</td>

      <td valign="top" width="113">0.43</td>
    </tr>
  </tbody></table>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/8308.TransactionWithConfigureAwait_6E77A044.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/8308.TransactionWithConfigureAwait_5F00_6E77A044.png"><img title="TransactionWithConfigureAwait" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="TransactionWithConfigureAwait" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4111.TransactionWithConfigureAwait_thumb_5C2ED982.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4111.TransactionWithConfigureAwait_5F00_thumb_5F00_5C2ED982.png" width="212" height="351" /></a></p>

<p>WHOA! What happened there? If you insert records within a transaction and use <font face="Consolas">ConfigureAwait(false)</font>, you can achieve insert performance of one insert every 0.43 ms, or <strong>2345 records per second</strong>. Now we’re talking! That means the performance of inserting records individually without using <font face="Consolas">ConfigureAwait(false)</font> is more than 144 times slower than the best case.</p>

<p>Why such a dramatic improvement? Well, the <font face="Consolas">Task.ConfigureAwait(bool continueOnCapturedContext)</font> method is used to configure the awaiter used to await the result of the asynchronous operation. An awaiter is an object you don’t see or program directly as a developer, but simply by using the <strong>await</strong> keyword when calling an asynchronous method, the compiler will generate code that uses an awaiter to handle the suspension and reactivation of your calling method while it waits for some asynchronous operation to complete. When the asynchronous method has completed, the awaiter resumes execution of your code which by default happens on the same context (think ‘thread’) you were on when you called the async method. But if you set <font face="Consolas">ConfigureAwait(false),</font> it doesn’t do that but instead continues on whatever context the async method executed on. There’s a performance advantage to this, which is why the advice to authors of library code is that you should always make async calls <strong>within</strong> your library code using <font face="Consolas">ConfigureAwait(false)</font> – the caller of your library method can then make the decision on whether to return to their original context by choosing whether or not to use <font face="Consolas">ConfigureAwait(false) </font>on the call to your async library method.</p>

<p>Which is what we are doing here – by setting <font face="Consolas">ConfigureAwait(false) </font>on our call to <font face="Consolas">SqlWinRT:Statement.StepAsync()</font> we are saying “don’t bother continue on the originating context, stay on whatever context you are executing on”. And as you can see, the performance gain is spectacular! To be honest, I was very surprised just how spectacular the performance improvement is. Normally, you would expect a modest performance gain, but I guess that because this call is happening between managed code and a WinRT component, the overhead of <font face="Consolas">ConfigureAwait(true) </font>- the default – is particularly significant.</p>

<p>One consequence of using <font face="Consolas">ConfigureAwait(false) </font>is that our code after the await call resumes on a background thread, so when we want to interact with the UI, such as to set the ProgressBar or to display the message at the end, we have to use the Dispatcher to make sure the code that touches the UI executes back on the UI thread:</p>

<pre class="code"><span style="background: white; color: black;">Dispatcher.BeginInvoke(() =&gt;
    {
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">report = </span><span style="background: white; color: rgb(43, 145, 175);">String</span><span style="background: white; color: black;">.Format(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Inserted {0:d} records in {1:0.00} seconds&quot;</span><span style="background: white; color: black;">, 
            n, (</span><span style="background: white; color: blue;">double</span><span style="background: white; color: black;">)sw.ElapsedMilliseconds / 1000);
        </span><span style="background: white; color: rgb(43, 145, 175);">MessageBox</span><span style="background: white; color: black;">.Show(report);

        Button_Start.IsEnabled = </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">;
    });</span></pre>

<p>If we don’t do that, you get an exception.</p>

<h2>SELECT Performance</h2>

<p>What about the performance of reading records out of the database? The warnings I gave in the introduction to this piece about having appropriate keys configured if you are doing a SELECT with a filter on a column that is not the primary key are still valid. But even if you are simply reading all the records out of a table, whether you use <font face="Consolas">ConfigureAwait(false) </font>again has a huge impact.</p>

<p>Here’s the code you would probably write to read all the rows in our table and to load them into in-memory objects in an ObservableCollection&lt;T&gt; ready to display on the UI:</p>

<pre class="csharpcode"><span class="kwrd">private</span> async <span class="kwrd">void</span> Button_Select_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">if</span> (db == <span class="kwrd">null</span>)
    {
        db = <span class="kwrd">new</span> SQLiteWinRT.Database(
            ApplicationData.Current.LocalFolder, <span class="str">&quot;sqliteperf.db&quot;</span>);

        await db.OpenAsync();
    }


    Stopwatch sw = Stopwatch.StartNew();
    <span class="kwrd">int</span> n = 0;
    Button_Select.IsEnabled = <span class="kwrd">false</span>;

    <span class="kwrd">string</span> sql = <span class="str">@&quot;
        SELECT
            id , 
                Route_ID , 
                Service_ID, 
                Trip_ID, 
                Trip_Headsign,
                Direction_ID, 
                Block_ID, 
                Shape_ID, 
                Wheelchair_Accessible
            FROM TTC&quot;</span>;
    var stmt = await db.PrepareStatementAsync(sql);

    ObservableCollection&lt;TransportationTrip&gt; tripCollection =
        <span class="kwrd">new</span> ObservableCollection&lt;TransportationTrip&gt;();

    <span class="kwrd">while</span> (await stmt.StepAsync())
    {
        var trip = <span class="kwrd">new</span> TransportationTrip()
        {
            ID = stmt.GetIntAt(0),
            RouteID = stmt.GetIntAt(1),
            ServiceID = stmt.GetIntAt(2),
            TripID = stmt.GetIntAt(3),
            TripHeadsign = stmt.GetTextAt(4),
            DirectionID = stmt.GetIntAt(5),
            BlockID = stmt.GetIntAt(6),
            ShapeID = stmt.GetIntAt(7),
            WheelchairAccessible = 
                stmt.GetIntAt(8) == 1 ? <span class="kwrd">true</span> : <span class="kwrd">false</span>,
        };

        tripCollection.Add(trip);
        n++;
    }

    var report = String.Format(<span class="str">&quot;Selected {0:d} records in {1:0.00} seconds&quot;</span>,
        n, (<span class="kwrd">double</span>)sw.ElapsedMilliseconds / 1000);
    MessageBox.Show(report);

    Button_Select.IsEnabled = <span class="kwrd">true</span>;
}</pre>


<p>Running this gives the following result:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/8814.SELECT-no-Await_6E0B6D4F.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/8814.SELECT_2D00_no_2D00_Await_5F00_6E0B6D4F.png"><img title="SELECT-no-Await" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="SELECT-no-Await" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/2541.SELECT-no-Await_thumb_70B4).png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/2541.SELECT_2D00_no_2D00_Await_5F00_thumb_5F00_70B42900.png" width="200" height="331" /></a></p>

<p>2838 seconds! That sucks – big time. </p>

<p>Then do it again, but make these subtle changes:</p>

<pre class="code"><span style="background: white; color: blue;">while </span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">stmt.StepAsync().AsTask().ConfigureAwait(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">))
{
    </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">trip = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">TransportationTrip</span><span style="background: white; color: black;">()
    {
        ID = stmt.GetIntAt(0),
        RouteID = stmt.GetIntAt(1),
        ServiceID = stmt.GetIntAt(2),
        TripID = stmt.GetIntAt(3),
        TripHeadsign = stmt.GetTextAt(4),
        DirectionID = stmt.GetIntAt(5),
        BlockID = stmt.GetIntAt(6),
        ShapeID = stmt.GetIntAt(7),
        WheelchairAccessible = stmt.GetIntAt(8) == 1 ? </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">:</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">,
    };

    tripCollection.Add(trip);
    n++;
}

Dispatcher.BeginInvoke(() =&gt;
    {
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">report = </span><span style="background: white; color: rgb(43, 145, 175);">String</span><span style="background: white; color: black;">.Format(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Selected {0:d} records in {1:0.00} seconds&quot;</span><span style="background: white; color: black;">, 
            n, (</span><span style="background: white; color: blue;">double</span><span style="background: white; color: black;">)sw.ElapsedMilliseconds / 1000);
        </span><span style="background: white; color: rgb(43, 145, 175);">MessageBox</span><span style="background: white; color: black;">.Show(report);

        Button_Select.IsEnabled = </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">;
    });</span></pre>

<p>Which gives this result:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5287.SELECT-await_17823F41.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5287.SELECT_2D00_await_5F00_17823F41.png"><img title="SELECT-await" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="SELECT-await" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4201.SELECT-await_thumb_3E505581.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4201.SELECT_2D00_await_5F00_thumb_5F00_3E505581.png" width="209" height="346" /></a></p>

<p>That’s some improvement! Comparing the two:</p>

<table cellspacing="0" cellpadding="2" width="625" border="0"><tbody>
    <tr>
      <td valign="top" width="263"><strong>Test</strong></td>

      <td valign="top" width="147"><strong>Total Time (seconds) – SELECT 128981 records</strong></td>

      <td valign="top" width="122"><strong>SELECT Time per record (ms)</strong></td>

      <td valign="top" width="91"><strong>Records per second</strong></td>
    </tr>

    <tr>
      <td valign="top" width="263">SELECT </td>

      <td valign="top" width="147">2838</td>

      <td valign="top" width="123">22</td>

      <td valign="top" width="91">45</td>
    </tr>

    <tr>
      <td valign="top" width="263">SELECT with ConfigureAwait(false)</td>

      <td valign="top" width="158">32.4</td>

      <td valign="top" width="135">0.25</td>

      <td valign="top" width="108">3980</td>
    </tr>
  </tbody></table>

<p>That’s a huge improvement!</p>

<p>[<strong>WARNING</strong>: The timings quoted here are for running on the emulator. You should expect times on a real device to be very substantially slower.]</p>

<h1>Conclusions</h1>

<p>Some golden rules emerge from this:</p>

<ol>
  <li>Use <strong>ConfigureAwait(false)</strong> when calling SqlWinRT async methods, particularly within repetitive looping such as INSERT or SELECT of a significant number of records. Remember that when you do so, your code will not resume on the same context it started on, so take appropriate measures to handle this. </li>

  <li>In addition to using ConfigureAwait(false), wrap large numbers of INSERTs in a single transaction to get the best performance. </li>
</ol>

<p>The last learning from this is not specific to SqlWinRT: if you call async methods on a WinRT component, there is a significant overhead in switching back to the originating context. Try calling such a component using ConfigureAwait(false) - it may yield significant performance benefits.</p>

<p>Lastly – this was a test program. If you ever find yourself trying to read 128000 records into memory, I would suggest you have another think about your app design and whether you really need all those objects in memory <img class="wlEmoticon wlEmoticon-smile" style="style" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/1376.wlEmoticon-smile_37311909.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/1376.wlEmoticon_2D00_smile_5F00_37311909.png" /> .</p>]]></content:encoded>
    </item>
    <item>
      <title>Push Notifications made easy: Using Windows Azure Notification Hubs with Windows Phone</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/push-notifications-made-easy-using-windows-azure-notification-hubs-with-windows-phone</link>
      <pubDate>Thu, 22 Aug 2013 07:42:17 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/08/22/push-notifications-made-easy-using-windows-azure-notification-hubs-with-windows-phone/</guid>
      <description><![CDATA[When I built the Windows Phone 8 Jump Start training, one of the sessions was on Push Notifications....]]></description>
      <content:encoded><![CDATA[<p>When I built the Windows Phone 8 Jump Start training, <a href="https://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-Jump-Start/Building-Apps-for-Windows-Phone-8-Jump-Start-08-Push-Notifications">one of the sessions</a> was on Push Notifications. The <a href="http://code.msdn.microsoft.com/Windows-Phone-8-JumpStart-ab6c839a/view/Reviews">demo app</a> I used was an update of an old favourite, a Weather app which first saw the light of day a few years ago with the initial demos built for Windows Phone 7.0. In the demo, you have a phone app and there is also a WPF desktop app. </p>  <p>The WPF desktop app allows the ‘operator’ to select a city, temperature and weather conditions and then generate tile, toast and raw notification messages to communicate the weather forecast to the phone. The WPF app does rather more than that and in addition implements two other key parts of a push notifications scenario, as it also hosts a WCF service and maintains a list of subscribers, simulating the cloud service that you would build for a real Push Notifications solution.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/0044.PushBasics_41E01851.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/0044.PushBasics_5F00_41E01851.jpg"><img title="PushBasics" style="display: inline; background-image: none;" border="0" alt="PushBasics" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/3835.PushBasics_thumb_5C7C8E9D.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/3835.PushBasics_5F00_thumb_5F00_5C7C8E9D.jpg" width="828" height="488" /></a></p>  <p>In summary, the phone registers for push notifications<sup>1</sup> and receives a unique URI (the channel URI) which it then sends off to your cloud service<sup>2</sup> (the WCF service) and the cloud service maintains a list of all subscribers for this app. Then the backend logic (the WPF UI in this demo) reads the list of subscriber channel URIs when it has something to communicate to the phone and sends the tile/toast/raw payloads to the subscriber URIs<sup>3</sup>. The subscriber URIs are actually endpoints hosted on MPNS (Microsoft Push Notification Services), so MPNS actually takes care of delivering the payloads to the phone<sup>4</sup>.</p>  <p>Fine – except that sample is difficult to setup and run, since you have to run Visual Studio as administrator otherwise the WCF self-hosting doesn’t work, you have to open port 8000 in your firewall because that is the port the WCF service listens on, and you have to edit the phone app code to set the correct hostname of the PC where the WCF service is running. Those are all implementation difficulties, but the real crime of this demo is that it’s too simplistic a demo and gives the impression that writing a Push Notifications solution is easier than it really is. In a real world app, when you post to MPNS you get back a response that gives you information about the state of the phone app subscription. There’s a whole page in the documentation about what you might get back: <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff941100(v=vs.105).aspx/css">Push Notification Service response codes for Windows Phone</a> and even if you ignore most of that, at the very least you should be removing subscribers from your list if you get a 404 Not Found response back, indicating that the subscription channel URI you posted to is no longer valid.</p>  <p>In fact, writing backend logic to send push notifications and correctly react to the Push Notification Service response codes is hard. And if you want to send push notifications to more than one client platform, such as Windows 8, iOS and Android, it’s incredibly hard.</p>  <p>That is – unless you use Windows Azure Notification Hubs <img class="wlEmoticon wlEmoticon-smile" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/6505.wlEmoticon-smile_77F16AD3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/6505.wlEmoticon_2D00_smile_5F00_77F16AD3.png" /></p>  <h1>Windows Azure Notification Hubs</h1>  <p>Windows Azure Notification Hubs is a service running in Windows Azure that makes it really easy to send push notifications to mobile clients. You can read an overview <a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj891130.aspx">here</a>, but in essence what it does is remove the need to manage the subscriber list and create your own subscription WCF service from your backend logic and provide an easy to program API for sending notifications – and not only to Windows Phone, but to Windows 8, iOS and Android clients too.</p>  <p>But the benefits of Notification Hubs are not only for those building a cross-platform solution. Even if you are building a push notifications app for a single type of client, using this technology will greatly ease the creation of your solution.</p>  <p>I thought it would be interesting to do a new version of the Weather sample, but using Windows Azure Notification Hubs to make a comparison between the two ways of doing it, so for the rest of this post, I will walk you through what I did (download the sample code from the link at the bottom of this post).</p>  <p>From an architectural point of view, the main thing is that the custom WCF service and subscriber list disappears completely. Great, no need to build and host a custom web service in order to build a push solution! Instead, the notification hub fulfils that purpose and acts as a gateway between your backend logic and MPNS.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/2185.PushNotificationsWithWANH_173411A7.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/2185.PushNotificationsWithWANH_5F00_173411A7.jpg"><img title="PushNotificationsWithWANH" style="display: inline; background-image: none;" border="0" alt="PushNotificationsWithWANH" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/1030.PushNotificationsWithWANH_thumb_3E5E350F.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/1030.PushNotificationsWithWANH_5F00_thumb_5F00_3E5E350F.jpg" width="819" height="541" /></a></p>  <h2>Configuring the Notification Hub</h2>  <p>First stage in building this is to configure the notification hub in Windows Azure, which is all done using the portal. You need to have a Windows Azure account and then go to the portal at <a href="http://manage.windowsazure.com">http://manage.windowsazure.com</a>.</p>  <ol>   <li>Click +NEW at the bottom of the screen. </li>    <li>Click App Services, then Service Bus, then Notification Hub, then Quick Create. </li>    <li>Type a name for your notification hub – I chose <em>weathernotificationhub</em>, select your desired region – West Europe for me, then click Create a new Notification Hub.       <br /><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4130.WANHcreate_0C36E4C5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4130.WANHcreate_5F00_0C36E4C5.png"><img title="WANHcreate" style="display: inline; background-image: none;" border="0" alt="WANHcreate" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/1300.WANHcreate_thumb_78995F56.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/1300.WANHcreate_5F00_thumb_5F00_78995F56.png" width="539" height="336" /></a>       <br /></li>    <li>You will now see the Service Bus namespace created screen.      <br /><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/8475.NotificationHubCreated_59933BB8.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/8475.NotificationHubCreated_5F00_59933BB8.png"><img title="NotificationHubCreated" style="display: inline; background-image: none;" border="0" alt="NotificationHubCreated" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/7220.NotificationHubCreated_thumb_46CE1C34.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/7220.NotificationHubCreated_5F00_thumb_5F00_46CE1C34.png" width="541" height="337" /></a>       <br />      <br />Now, before you leave this screen, click on the <strong>Install the Windows Azure SDK (includes Service Bus client libraries)</strong> link to make sure you’ve got the client libraries installed in Visual Studio that you will need in both the phone app and also the desktop app.       <br /></li>    <li>Click <strong>Connection Information</strong> at the bottom. Take note of the two connection strings – you will need them in a moment.       <br /><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5432.AccessConnectionInformation_62AF2B5F.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5432.AccessConnectionInformation_5F00_62AF2B5F.png"><img title="AccessConnectionInformation" style="display: inline; background-image: none;" border="0" alt="AccessConnectionInformation" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4265.AccessConnectionInformation_thumb_6F0D28BB.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4265.AccessConnectionInformation_5F00_thumb_5F00_6F0D28BB.png" width="541" height="337" /></a></li> </ol>  <p>That’s it. Your Windows Azure Notification Hub is configured and ready to go.</p>  <h2>Connecting the Phone App to Windows Azure Notification Hubs</h2>  <p>Now let’s turn to the phone app. There aren’t many changes we need to make from the phone app we used in pre-notification hubs days. It still needs to register for push notifications using <strong>Microsoft.Phone.Notifications.HttpNotificationChannel</strong> and register for toast, tile and/or raw notifications. And when the app opens the channel, it will get a new Channel Uri reported to it when the <strong>ChannelUriUpdated</strong> event fires.</p>  <p>In the original app, it was at this point that you sent the channel Uri off to the WCF service hosted in the Weather Service desktop app, but instead we now send that off to our Windows Azure Notification Hub. To do this, you need to add a reference to the client libraries using the <a href="http://nuget.org/packages/WindowsAzure.Messaging.Managed/">WindowsAzure.Messaging.Managed NuGet package</a>. </p>  <p>In the Visual Studio menu, click <strong>Tools</strong>, then <strong>Library Package Manager</strong>, then <strong>Package Manager Console</strong>. Then, in the console window type:</p>  <pre>Install-Package WindowsAzure.Messaging.Managed</pre>

<p>and press Enter. </p>

<p>Now in the phone app, in MainPage.xaml.cs, we add the <font face="Courier New">using Microsoft.WindowsAzure.Messaging</font> using statement at the top, and then modify the ChennelUriUpdated event handler as follows:</p>

<pre class="code"><span style="background: white; color: blue;">async void </span><span style="background: white; color: black;">httpChannel_ChannelUriUpdated(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">NotificationChannelUriEventArgs </span><span style="background: white; color: black;">e)
{
    Trace(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Channel opened. Got Uri:\n&quot; </span><span style="background: white; color: black;">+ httpChannel.ChannelUri.ToString());
    Dispatcher.BeginInvoke(() =&gt; SaveChannelInfo());

    Trace(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Subscribing to channel events&quot;</span><span style="background: white; color: black;">);
    </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">SubscribeToServiceAsync();
    SubscribeToNotifications();

    Dispatcher.BeginInvoke(() =&gt; UpdateStatus(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Channel created successfully&quot;</span><span style="background: white; color: black;">));
}</span></pre>

<p>The SubscribeToServiceAsync() method is a new version of SubscribeToService() in the original demo. Instead of calling the WCF service (the commented out code), it now instantiates a <a href="http://msdn.microsoft.com/en-us/library/windowsazure/microsoft.windowsazure.messaging.notificationhub.aspx">Microsoft.WindowsAzure.Messaging.NotificationHub</a> instance, which takes two arguments: the name of my notification hub (weathernotificationhub) and the connection string called <strong>DefaultListenSharedAccessSignature</strong> that you get from the Connection Strings display in the portal (step 5 in the previous section).</p>

<pre class="code"><span style="background: white; color: blue;">private async </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">SubscribeToServiceAsync()
{
    </span><span style="background: white; color: blue;">try
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">hub = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">NotificationHub</span><span style="background: white; color: black;">(
            </span><span style="background: white; color: rgb(163, 21, 21);">&quot;weathernotificationhub&quot;</span><span style="background: white; color: black;">,
            </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Endpoint=sb://weathernotificationhub-ns.servicebus.windows.net...[your value] ...&quot;</span><span style="background: white; color: black;">);

        </span><span style="background: white; color: rgb(43, 145, 175);">Registration </span><span style="background: white; color: black;">registration = 
            </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">hub.RegisterNativeAsync(httpChannel.ChannelUri.ToString());
        Trace(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Registered with Azure Notification Hub, Registration Id:&quot; 
            </span><span style="background: white; color: black;">+ registration.RegistrationId);

        Dispatcher.BeginInvoke(() =&gt; 
            UpdateStatus(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Registered with Windows Azure Notification Hub&quot;</span><span style="background: white; color: black;">));
    }
    </span><span style="background: white; color: blue;">catch </span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(43, 145, 175);">RegistrationAuthorizationException </span><span style="background: white; color: black;">rEx)
    {
        Trace(rEx.Message);
        </span><span style="background: white; color: blue;">throw</span><span style="background: white; color: black;">;
    }
}</span></pre>

<p>That’s it as far as the phone client goes. Everything else stays the same: push notifications are delivered by the notifications infrastructure and handled in exactly the same way. Windows Azure Notification Hubs simply replaces your own subscription service, as far as the phone client goes.</p>

<h2>Sending Notifications From Your Backend Logic</h2>

<p>This is where the true benefit of Windows Azure Notification Hubs shines through. You no longer have to create your own web service with table storage to receive the channel URIs from your phone client subscribers, nor do you have to write logic to examine the status returns you get back from MPNS when you post notification messages and prune out stale registrations from the subscriber lists. You don’t need to write logic to post to each subscriber channel URI individually, just one call to the notification hub will cause the message to be sent out to all your clients. And if your backend logic needs to support Windows 8, iOS or Android clients as well as Windows Phone, the benefits of&#160; Windows Azure Notification Hubs multiplies a hundred-fold.</p>

<h3>Getting Registration Details from the Hub</h3>

<p>In the Weather app, I started by deleting everything to do with the WCF registration service that we used in the previous version. Then fixed up the UI where it used to display things like “Waiting for connection…”. One thing the original did, was show the current count of registrations to the registration service. To do the same with Notification Hubs, you can call the <strong>NotificationHubClient.GetAllRegistrationsAsync(int32 top)</strong> method which returns details of all registrations limited to the top ‘n’ by the value you pass in the argument. In order to use the NotificationHubClient object, you need to add a reference to the client libraries using the <a href="http://nuget.org/packages/WindowsAzure.Messaging.Managed/">WindowsAzure.Messaging.Managed NuGet package</a> just the same as we did with the phone app.</p>

<p>After adding the NuGet package to my sample app, we show the number of clients on the screen using the following method:</p>

<pre class="code"><p><span style="background: white; color: blue;">private async </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">UpdateRegistrationsCountAsync()
{
    </span><span style="background: white; color: rgb(43, 145, 175);">NotificationHubClient </span><span style="background: white; color: black;">hub = </span><span style="background: white; color: rgb(43, 145, 175);">NotificationHubClient</span><span style="background: white; color: black;">.CreateClientFromConnectionString(
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Endpoint=sb://weathernotificationhub-ns.servicebus.windows.net/;…&quot;</span><span style="background: white; color: black;">,
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;weathernotificationhub&quot;</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">registrationsCount = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">hub.GetAllRegistrationsAsync(</span><span style="background: white; color: rgb(43, 145, 175);">Int32</span><span style="background: white; color: black;">.MaxValue);</span></p><span style="background: white; color: black;"></span><span style="background: white; color: blue;">    await </span><span style="background: white; color: black;">Dispatcher.BeginInvoke((</span><span style="background: white; color: rgb(43, 145, 175);">Action</span><span style="background: white; color: black;">)(() =&gt; <br />      { txtRegistrationsCount.Text = registrationsCount.Count().ToString(); }) <br />    );<br /></span>}</pre>

<p>The <span style="background: white; color: rgb(43, 145, 175);">NotificationHubClient </span>constructor takes two arguments: the first is the connection string you get from the Notification Hub Connection Strings page in the Windows Azure portal, but unlike the phone client which used the DefaultListenSharedAccessSignature, this time you need the <strong>DefaultFullSharedAccessSignature</strong> as this app is doing full interaction with the notification hub, such as posting notifications. The second arg is the name of your notification hub.</p>

<h3>Sending Toast and Tile Push Notifications</h3>

<p>Now to the main purpose of the app. Most of the logic around formatting and sending notification messages is encapsulated into the NotificationSenderUtility class in my sample. For example, this contains the following method to format the XML to send for a Windows Phone Toast notification:</p>

<pre class="code"><span style="background: white; color: blue;">private static string </span><span style="background: white; color: black;">prepareToastPayload(</span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">text1, </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">text2)
{
    </span><span style="background: white; color: green;">// Create encoding manually in order to prevent
    // creation of leading BOM (Byte Order Mark) xFEFF at start
    // of string created from the XML
    </span><span style="background: white; color: rgb(43, 145, 175);">Encoding </span><span style="background: white; color: black;">Utf8 = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">UTF8Encoding</span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">); </span><span style="background: white; color: green;">// Prevents creation of BOM
    </span><span style="background: white; color: rgb(43, 145, 175);">MemoryStream </span><span style="background: white; color: black;">stream = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">MemoryStream</span><span style="background: white; color: black;">();
    </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriterSettings </span><span style="background: white; color: black;">settings = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriterSettings</span><span style="background: white; color: black;">() 
                { 
                    Indent = </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">,
                </span><span style="background: white; color: green;">//   Encoding = Encoding.UTF8    !!NO-&gt; adds Unicode BOM to start
                    </span><span style="background: white; color: black;">Encoding = Utf8,    </span><span style="background: white; color: green;">// Use manually created UTF8 encoding
                </span><span style="background: white; color: black;">};
    </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriter </span><span style="background: white; color: black;">writer = </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriter</span><span style="background: white; color: black;">.Create(stream, settings);
    writer.WriteStartDocument();
    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;wp&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Notification&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;WPNotification&quot;</span><span style="background: white; color: black;">);
    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;wp&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Toast&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;WPNotification&quot;</span><span style="background: white; color: black;">);
    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;wp&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Text1&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;WPNotification&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(text1);
    writer.WriteEndElement();
    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;wp&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Text2&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;WPNotification&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(text2);
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Close();

    </span><span style="background: white; color: blue;">return  </span><span style="background: white; color: rgb(43, 145, 175);">Encoding</span><span style="background: white; color: black;">.UTF8.GetString(stream.ToArray());
}</span></pre>

<p>WARNING: While building this, I discovered that Windows Azure Notification Hubs are quite a bit fussier about the XML you send it than MPNS actually is. The original version of the code used the standard Encoding.UTF8 in the XmlWriterSettings (commented out in the code above) which results in an invisible Byte Order Mark (BOM) character being inserted at the front of the string, which causes Windows Azure Notification Hubs to barf when you send it that. The code above creates the XML without the BOM at the front which works fine. To read more about this, see my blog post <a href="http://andywigley.com/2013/08/19/bombin-the-l-aka-wierd-errors-with-xmlwriter/">BOMbin’ the L (aka Wierd Errors with XmlWriter)</a>.</p>

<p>Having prepared the payload, to send a Toast or Tile is simply a case of calling the NotificationHubClient.SendMpnsNativeNotificationAsync(string payload) method. The implementation in the attached sample is slightly more complex than this, but essentially it’s the following:</p>

<pre class="code"><span style="background: white; color: black;">    </span><span style="background: white; color: rgb(43, 145, 175);">NotificationHubClient </span><span style="background: white; color: black;">hub = </span><span style="background: white; color: rgb(43, 145, 175);">NotificationHubClient</span><span style="background: white; color: black;">.CreateClientFromConnectionString(
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Endpoint=sb://weathernotificationhub-ns.servicebus.windows.net/;...&quot;</span><span style="background: white; color: black;">,
        </span><span style="background: white; color: rgb(163, 21, 21);">&quot;weathernotificationhub&quot;</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: rgb(43, 145, 175);">NotificationOutcome </span><span style="background: white; color: black;">outcome = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">hub.SendMpnsNativeNotificationAsync(payload);</span></pre>

<h3>Sending Raw Notifications</h3>

<p>The other thing the original sample does is send raw notifications directly to the app (if it happens to be running of course). The body of a raw payload is entirely up to the app developer, since unlike toast and tile notifications that may be processed by the Push Notifications handler in the phone OS, raw notifications are only ever handled by the app. So in the new version of this sample, the code building the raw notification payload is almost the same as before:</p>

<pre class="code"><span style="background: white; color: blue;">private static string </span><span style="background: white; color: black;">prepareRAWPayload(</span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">location, </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">temperature, </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">weatherType)
{
    </span><span style="background: white; color: green;">// Create encoding manually in order to prevent
    // creation of leading BOM (Byte Order Mark) xFEFF at start
    // of string created from the XML
    </span><span style="background: white; color: rgb(43, 145, 175);">Encoding </span><span style="background: white; color: black;">Utf8 = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">UTF8Encoding</span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">); </span><span style="background: white; color: green;">// Prevents creation of BOM
    </span><span style="background: white; color: rgb(43, 145, 175);">MemoryStream </span><span style="background: white; color: black;">stream = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">MemoryStream</span><span style="background: white; color: black;">();
    </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriterSettings </span><span style="background: white; color: black;">settings = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriterSettings</span><span style="background: white; color: black;">()
    {
        Indent = </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">,
        </span><span style="background: white; color: green;">//   Encoding = Encoding.UTF8    !!NO-&gt; adds Unicode BOM to start
        </span><span style="background: white; color: black;">Encoding = Utf8,    </span><span style="background: white; color: green;">// Use manually created UTF8 encoding
    </span><span style="background: white; color: black;">};
    </span><span style="background: white; color: rgb(43, 145, 175);">XmlWriter </span><span style="background: white; color: black;">writer = </span><span style="background: white; color: rgb(43, 145, 175);">XmlTextWriter</span><span style="background: white; color: black;">.Create(stream, settings);

    writer.WriteStartDocument();
    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;WeatherUpdate&quot;</span><span style="background: white; color: black;">);

    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Location&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(location);
    writer.WriteEndElement();

    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;Temperature&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(temperature);
    writer.WriteEndElement();

    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;WeatherType&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(weatherType);
    writer.WriteEndElement();

    writer.WriteStartElement(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;LastUpdated&quot;</span><span style="background: white; color: black;">);
    writer.WriteValue(</span><span style="background: white; color: rgb(43, 145, 175);">DateTime</span><span style="background: white; color: black;">.Now.ToString());
    writer.WriteEndElement();

    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Close();

    </span><span style="background: white; color: blue;">return </span><span style="background: white; color: rgb(43, 145, 175);">Encoding</span><span style="background: white; color: black;">.UTF8.GetString(stream.ToArray());
}</span></pre>

<p>I then had to do a bit of digging to figure out how to send this raw notification via Windows Azure Notification Hubs. One of the many methods of <strong>NotificationHubClient</strong> is <strong>SendNotificationAsync(Notification notification)</strong> which is a more generic Send* method than <strong>SendMpnsNativeNotificationAsync</strong> that we used before. It has the advantage that we can add HTTP headers to the request we send to MPNS, so we can define the X-NOTIFICATION header that a raw notification requires:</p>

<pre class="code"><span style="background: white; color: black;">        </span><span style="background: white; color: green;">// For raw notifications, have to use the more generic SendNotificationAsync() method
        </span><span style="background: white; color: rgb(43, 145, 175);">Notification </span><span style="background: white; color: black;">notification = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">MpnsNotification</span><span style="background: white; color: black;">(payload);
        notification.Headers.Add(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;X-NotificationClass&quot;</span><span style="background: white; color: black;">, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;3&quot;</span><span style="background: white; color: black;">); </span><span style="background: white; color: green;">// Required header for RAW
        </span><span style="background: white; color: black;">outcome = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">hub.SendNotificationAsync(notification);</span></pre>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5861.push-end_0030E092.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5861.push_2D00_end_5F00_0030E092.png"><img title="push end" style="display: inline; background-image: none;" border="0" alt="push end" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/6675.push-end_thumb_3E560D11.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/6675.push_2D00_end_5F00_thumb_5F00_3E560D11.png" width="818" height="411" /></a></p>

<h1>Summary</h1>

<p>Hopefully this has given you an introduction to building a push notification solution using Windows Azure Notification Hubs. There is plenty more to discover as I have only scratched the surface. For example, this sample sends notifications to all subscribers, but you can send to only a subset of subscribers using Tags. And of course, you can also send to Windows 8, iOS and Android clients, formatting the payloads for each client family yourself and then calling the SendWNSNativeNotificationAsync, SendAPSNativeNotificationAsync or SendGCMNativeNotificationAsync methods. An even easier way to do this, is to use the Templates feature, which is a neat way of sending a single generic message from your backend logic and allowing Windows Azure Notification Hubs to format the native message payload for each platform for you.</p>

<p>Here are some useful resources to allow you to dig deeper into Windows Azure Notification Hubs:</p>

<ul><!--StartFragment-->
  <li><a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj927170.aspx#BKMK_NH5">Windows Azure Notification Hubs Overview</a> </li>

  <li><a href="http://www.windowsazure.com/en-us/manage/services/notification-hubs/get-started-notification-hubs-wp8/">Get started with Notification Hubs – Windows Phone</a> </li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj927172.aspx">How To: Windows Azure Notification Hubs (Windows Store Apps)</a> </li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windowsazure/jj927168.aspx">How To: Windows Azure Notification Hubs (iOS Apps)</a> </li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windowsazure/dn282661.aspx">How To: Windows Azure Notification Hubs (Android Apps)</a> </li>

  <li><a href="http://www.windowsazure.com/en-us/manage/services/notification-hubs/breaking-news-dotnet/">Use Notification Hubs to send breaking news</a> (shows how to use tags to send push notifications to different groups of subscribers)</li>
</ul>

<p>You should also be aware that <a href="http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started/">Windows Azure Mobile Services</a> uses Notification Hubs to send push notifications.</p>

<p>You can download the sample code described here yourself using the link at the bottom of this post. You will have to create your own notification hub and plug in your own hub name and connection strings, both in MainPage.xaml.cs in the phone project, and in MainWindows.xaml.cs in the desktop app – you should be able to find where easily enough.</p>

<p>IMPORTANT: In Visual Studio, go to Tools – Options – Package Manager and check <strong>Allow NuGet to download missing packages during build</strong>. After you open the solution, right-click on the project and then click Manage NuGet Packages. When the package manager window opens, you will see a bar across the top saying that some NuGet packages are missing – click the Restore button to download the required NuGet packages.</p>

<p>Download sample code: <a href="http://sdrv.ms/185SpAL">Windows Azure Notifications Hubs Weather Demo</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Now easier than ever to developer unlock a handset to get started building apps for Windows Phone!</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/now-easier-than-ever-to-developer-unlock-a-handset-to-get-started-building-apps-for-windows-phone</link>
      <pubDate>Wed, 07 Aug 2013 07:42:07 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/08/07/now-easier-than-ever-to-developer-unlock-a-handset-to-get-started-building-apps-for-windows-phone/</guid>
      <description><![CDATA[Great news reported in the latest Windows Phone Developer Blog post, Making it easier to get started...]]></description>
      <content:encoded><![CDATA[Great news reported in the latest Windows Phone Developer Blog post, <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/08/06/making-it-easier-to-get-started-with-windows-phone-app-studio-beta-simplified-phone-registration-support-options-amp-more-payout-markets.aspx">Making it easier to get started with Windows Phone App Studio beta, simplified phone registration, support options &amp; more payout markets</a>. There you can read about a great new tool, <a href="http://apps.windowsstore.com/default.htm">Windows Phone App Studio</a>, that can help people without coding skills to create a phone app using a free, web-based app creation tool. Even experienced devs will find it useful to build out the basic structure of an app, but since you can download the code for the project the tool creates, you can then modify it to add more functionality.

Interesting though Windows Phone App Studio is, the best news announced in that post is the new simplified phone registration. This is fantastic news, as it removes one blocker we&rsquo;ve had with people trying to get started building for Windows Phone.

<p>The dev tools have always been free (download the Windows Phone 8.0 SDK for free from <a href="http://dev.windowsphone.com">http://dev.windowsphone.com</a>), but if you wanted to test your app on the emulator, you had to have a PC with a Core i3/i5/i7 processor and have Windows 8 Pro or Enterprise, which are the editions that include the necessary Hyper-V support. So if you couldn&rsquo;t meet those hardware and OS specs, your only option was to run your app on a real phone &ndash; but to use a real phone you had to have registered for a developer account at <a href="http://dev.windowsphone.com">http://dev.windowsphone.com</a> so you could unlock it, which is normally $99/year (although that is currently on special offer at $19 until August 26th). At this point, the &lsquo;mildly curious developer&rsquo;, faced with the prospect of having to part with money to try out their new app, can lose interest and of course we&rsquo;ve lost a potential convert to our developer community.</p><h4>Any dev can unlock one phone for testing without a registration fee</h4><p>Now, anyone can unlock one phone to test their apps without needing a dev account, and can install up to two &lsquo;work in progress&rsquo; apps onto the phone at any one time. Fantastic! So now you can get started with Windows Phone dev using *<b>any</b>* PC running Windows 8 (any edition) at no charge (well, you need a handset obviously ). Only caveat is that your PC and Windows 8 OS still needs to be 64 bit, as that is a requirement of the SDK.</p>]]></content:encoded>
    </item>
    <item>
      <title>Beware the perils of async/await in application lifecycle event handlers (in fact in *any* event handlers)</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/beware-the-perils-of-asyncawait-in-application-lifecycle-event-handlers-in-fact-in-any-event-handlers</link>
      <pubDate>Wed, 31 Jul 2013 10:32:11 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/07/31/beware-the-perils-of-asyncawait-in-application-lifecycle-event-handlers-in-fact-in-any-event-handlers/</guid>
      <description><![CDATA[Many developers are, quite rightly, adopting the use of async and await when writing Windows Phone...]]></description>
      <content:encoded><![CDATA[<p>Many developers are, quite rightly, adopting the use of async and await when writing Windows Phone and Windows 8 Store apps. It’s the right thing to do, as it allows long-running operations such as network calls and file i/o to complete efficiently without any risk of inadvertently locking up the UI thread and creating a poor user experience by freezing the screen responsiveness. In fact, in Windows 8 Store apps, it’s the *only* way to do these operations because in the .NET API for Windows Store apps, the old synchronous methods have been removed and only the new async versions are available. On Windows Phone 8, the developer has the choice of using the old Window Phone 7-style APIs, or in many cases newer async alternatives, such as the WinRT Windows.Storage APIs for file operations.</p>  <p>However, we’re seeing a lot of postings in the forums saying that their app only works intermittently, or works fine in debug but then fails intermittently when deployed. Quite often, the reason for this is that the developer has inadvertently called some async methods in a ‘fire and forget’ fashion, and what they are seeing is a synchronization problem; they assume that some async code has completed, and some code elsewhere is trying to use the result value from the async method before the async method has completed. The result, a null reference exception or incorrect behaviour because some object is not fully populated.</p>  <h2>The problem with async/await in Application_Launching and Application_Activated</h2>  <p>I accidently encountered this problem when I was building a simple demo for the last Windows Phone 8 JumpStart video series. OK, it was a dumb demo, but demos are often dumb because you want to keep them simple so as not to distract from the main point you are trying to make. This demo was to show how to program with the new Windows.Storage apis, so in my App class <strong>Application_Launching</strong> event handler I had code that read some data out of a file and saved the string into a public property called <strong>LogData</strong>:</p>  <pre class="code"><span style="background: white; color: black;">    </span><span style="background: white; color: blue;">public partial class </span><span style="background: white; color: rgb(43, 145, 175);">App </span><span style="background: white; color: black;">: </span><span style="background: white; color: rgb(43, 145, 175);">Application
    </span><span style="background: white; color: black;">{
        ...

        </span><span style="background: white; color: green;">// This is shared amongst all the pages
        // It is the contents of the log itself, as a large string
        </span><span style="background: white; color: blue;">public string </span><span style="background: white; color: black;">LogData;

        </span><span style="background: white; color: green;">// Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        </span><span style="background: white; color: blue;">private async void </span><span style="background: white; color: black;">Application_Launching(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">LaunchingEventArgs </span><span style="background: white; color: black;">e)
        {            
            </span><span style="background: white; color: green;">// Warning - this async method may not complete before this event handler <br />            // </span><span style="background: white; color: green;">method completes and other events fire. 
            </span><span style="background: white; color: blue;">this</span><span style="background: white; color: black;">.LogData = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">LoadFromLocalFolderAsync();
        }

        </span><span style="background: white; color: blue;">public async static </span><span style="background: white; color: rgb(43, 145, 175);">Task</span><span style="background: white; color: black;">&lt;</span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">&gt; LoadFromLocalFolderAsync()
        {
            </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">theData = </span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">.Empty;

            </span><span style="background: white; color: green;">// There's no FileExists method in WinRT, so have to try to get a reference to it
            // and catch the exception instead
            </span><span style="background: white; color: rgb(43, 145, 175);">StorageFile </span><span style="background: white; color: black;">storageFile = </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">;
            </span><span style="background: white; color: blue;">bool </span><span style="background: white; color: black;">fileExists = </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">;
            </span><span style="background: white; color: blue;">try
            </span><span style="background: white; color: black;">{
                </span><span style="background: white; color: green;">// See if file exists
                </span><span style="background: white; color: black;">storageFile = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">Windows.Storage.</span><span style="background: white; color: rgb(43, 145, 175);">StorageFile</span><span style="background: white; color: black;">.GetFileFromApplicationUriAsync(
                    </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">Uri</span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;ms-appdata:///local/CaptainsLog.store&quot;</span><span style="background: white; color: black;">));
                fileExists = </span><span style="background: white; color: blue;">true</span><span style="background: white; color: black;">;
            }
            </span><span style="background: white; color: blue;">catch </span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(43, 145, 175);">FileNotFoundException</span><span style="background: white; color: black;">)
            {
                </span><span style="background: white; color: green;">// File doesn't exist
                </span><span style="background: white; color: black;">fileExists = </span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">;
            }

            </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(!fileExists)
            {
                </span><span style="background: white; color: green;">// Initialise the return data
                </span><span style="background: white; color: black;">theData = </span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">.Empty;
            }
            </span><span style="background: white; color: blue;">else
            </span><span style="background: white; color: black;">{
                </span><span style="background: white; color: green;">// File does exist, so open it and read the contents
                </span><span style="background: white; color: rgb(43, 145, 175);">Stream </span><span style="background: white; color: black;">readStream = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">storageFile.OpenStreamForReadAsync();
                </span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">(</span><span style="background: white; color: rgb(43, 145, 175);">StreamReader </span><span style="background: white; color: black;">reader = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">StreamReader</span><span style="background: white; color: black;">(readStream))
                {
                    theData = </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">reader.ReadToEndAsync();
                }
            }

            </span><span style="background: white; color: blue;">return </span><span style="background: white; color: black;">theData;
        }</span></pre>

<p>And in MainPage.xaml.cs, OnNavigatedTo, the code gets the value of LogData from the App class and sets the Text property of a TextBlock to the string to show the contents of the file on the screen. Logic elsewhere in the app writes content into the file, so on startup you should always see the current contents of the file shown on the screen on application launch.</p>

<pre class="code"><span style="background: white; color: black;">        </span><span style="background: white; color: blue;">protected override void  </span><span style="background: white; color: black;">OnNavigatedTo(System.Windows.Navigation.</span><span style="background: white; color: rgb(43, 145, 175);">NavigationEventArgs </span><span style="background: white; color: black;">e)
        {
             </span><span style="background: white; color: blue;">base</span><span style="background: white; color: black;">.OnNavigatedTo(e);
            
            </span><span style="background: white; color: green;">// When we navigate to the page - put the log text into the display
            </span><span style="background: white; color: black;">completeLogTextBlock.Text = ((</span><span style="background: white; color: rgb(43, 145, 175);">App</span><span style="background: white; color: black;">)</span><span style="background: white; color: rgb(43, 145, 175);">App</span><span style="background: white; color: black;">.Current).LogData;
        }</span></pre>

<p>What could possibly go wrong? Well, plenty as it turns out! The first time you run this app, the screen is empty which is to be expected because the file is empty. But then you use the app to enter some text which is written to the file, then close the app. Launch again, and where you would expect to see some text displayed, the screen is still empty! What gives?</p>

<h2>Exploring execution of Async methods</h2>

<p>To show why this went wrong, let’s look at a simple console app to explore the two ways you can execute an async method.</p>

<pre class="code"><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">System;
</span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">System.Threading.Tasks;

</span><span style="background: white; color: blue;">namespace </span><span style="background: white; color: black;">AsyncSynchronizationProblem
{
    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">Program
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">static void </span><span style="background: white; color: black;">Main(</span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">[] args)
        {
            </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">TheClassThatDoesWork</span><span style="background: white; color: black;">().DoTheWork();

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.ReadKey();
        }
    }

    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">TheClassThatDoesWork
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">public async void </span><span style="background: white; color: black;">DoTheWork()
        {
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Calling SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);
            </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">SomeLongProcedureAsync();
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Returned from SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine();

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Calling SomeLongProcedure Fire and forget&quot;</span><span style="background: white; color: black;">);
            SomeLongProcedureAsync();
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Returned SomeLongProcedure Fire and forget&quot;</span><span style="background: white; color: black;">);
        }

        </span><span style="background: white; color: blue;">private </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">SomeLongProcedureAsync()
        {
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">task = </span><span style="background: white; color: rgb(43, 145, 175);">Task</span><span style="background: white; color: black;">.Run(() =&gt;
                {
                    </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Starting SomeLongProcedure work&quot;</span><span style="background: white; color: black;">);
                    System.Threading.</span><span style="background: white; color: rgb(43, 145, 175);">Thread</span><span style="background: white; color: black;">.Sleep(1000); </span><span style="background: white; color: green;">// Simulate long running op
                    </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Completed SomeLongProcedure work&quot;</span><span style="background: white; color: black;">);
                });

            </span><span style="background: white; color: blue;">return </span><span style="background: white; color: black;">task;
        }
    }
}
</span></pre>

<p>When you run this app, you see the following console output:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/3817.asyncdemo1_4CF58A5A.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/3817.asyncdemo1_5F00_4CF58A5A.jpg"><img title="asyncdemo1" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="asyncdemo1" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/1581.asyncdemo1_thumb_5CD4A951.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/1581.asyncdemo1_5F00_thumb_5F00_5CD4A951.jpg" width="605" height="397" /></a></p>

<p>In this sample, the long running method, <strong>Task SomeLongProcedureAsync()</strong> simply sleeps for 1s to simulate executing some lengthy code. In the method <strong>DoTheWork()</strong>, we just call the async method twice, once using <strong>await</strong> and once without. We write to the console output to show what is happening. I’m sure it is no surprise to most of you, that when we call using await, the caller waits until the long-running work has completed before continuing execution itself:</p>

<p><font face="Consolas">TRACE Calling SomeLongProcedure Async 
    <br />TRACE Starting SomeLongProcedure work 

    <br />TRACE Completed SomeLongProcedure work 

    <br />TRACE Returned from SomeLongProcedure Async</font></p>

<p>and when we call without using await, it works in a fire-and-forget fashion, and the caller continues execution without waiting for the task to complete:</p>

<p><font face="Consolas">TRACE Calling SomeLongProcedure Fire and forget 
    <br /><font face="Consolas">TRACE Starting SomeLongProcedure work 
      <br /></font>TRACE Returned from SomeLongProcedure Fire and forget</font><font face="Consolas"> 
    <br />TRACE Completed SomeLongProcedure work</font></p>

<p>This is pretty basic stuff about calling async methods. So why is this relevant?</p>

<h2>Dangers of making event handlers async</h2>

<p>Let’s look at another example. This one is still a console app, but has four classes, <strong>Program</strong> which just hosts the Main method of the console app, <strong>App</strong>, <strong>PhoneApplicationService</strong> and <strong>MainPage</strong> – I have named the last three the same as key classes in a Windows Phone app for reasons which hopefully will become obvious.</p>

<pre class="code"><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">System;
</span><span style="background: white; color: blue;">using </span><span style="background: white; color: black;">System.Threading.Tasks;

</span><span style="background: white; color: blue;">namespace </span><span style="background: white; color: black;">AsyncSynchronizationProblemWithEvents
{
    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">Program
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">static void </span><span style="background: white; color: black;">Main(</span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">[] args)
        {
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">phoneAppService = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">PhoneApplicationService</span><span style="background: white; color: black;">();
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">app = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">App</span><span style="background: white; color: black;">(phoneAppService);
            
            phoneAppService.DoTheWork();

            </span><span style="background: white; color: green;">// When the PhoneApplicationService has completed, construct a MainPage instance
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">mainPage = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">MainPage</span><span style="background: white; color: black;">();
            </span><span style="background: white; color: green;">// Call methods on it
            </span><span style="background: white; color: black;">mainPage.OnNavigatedTo();

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.ReadKey();
        }
    }

    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">App
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">private </span><span style="background: white; color: rgb(43, 145, 175);">PhoneApplicationService </span><span style="background: white; color: black;">appService;

        </span><span style="background: white; color: blue;">public </span><span style="background: white; color: black;">App(</span><span style="background: white; color: rgb(43, 145, 175);">PhoneApplicationService </span><span style="background: white; color: black;">applicationService)
        {
            appService = applicationService;
            </span><span style="background: white; color: green;">// Subscribe to the PhoneApplicationService lifetime event(s)
            </span><span style="background: white; color: black;">appService.ApplicationLaunching += Application_Launching;
        }

        </span><span style="background: white; color: blue;">async void </span><span style="background: white; color: black;">Application_Launching(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">EventArgs </span><span style="background: white; color: black;">e)
        {
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(<br />                </span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Event handler - Calling SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);
            </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">SomeLongProcedureAsync();
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(<br />                </span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Event handler - Returned from SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);
        }

        </span><span style="background: white; color: blue;">private </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">SomeLongProcedureAsync()
        {
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">task = </span><span style="background: white; color: rgb(43, 145, 175);">Task</span><span style="background: white; color: black;">.Run(() =&gt;
            {
                </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Starting SomeLongProcedure work&quot;</span><span style="background: white; color: black;">);
                System.Threading.</span><span style="background: white; color: rgb(43, 145, 175);">Thread</span><span style="background: white; color: black;">.Sleep(1000); </span><span style="background: white; color: green;">// Simulate long running op
                </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Completed SomeLongProcedure work&quot;</span><span style="background: white; color: black;">);
            });

            </span><span style="background: white; color: blue;">return </span><span style="background: white; color: black;">task;
        }
    }

    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">PhoneApplicationService
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">public event </span><span style="background: white; color: rgb(43, 145, 175);">EventHandler </span><span style="background: white; color: black;">ApplicationLaunching;

        </span><span style="background: white; color: blue;">public void </span><span style="background: white; color: black;">DoTheWork()
        {
            </span><span style="background: white; color: green;">// Here we do some stuff...

            // Call any subscribers to our event(s)
            </span><span style="background: white; color: blue;">if </span><span style="background: white; color: black;">(ApplicationLaunching != </span><span style="background: white; color: blue;">null</span><span style="background: white; color: black;">)
            {
                ApplicationLaunching(</span><span style="background: white; color: blue;">this</span><span style="background: white; color: black;">, </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">EventArgs</span><span style="background: white; color: black;">());
            }
        }
    }

    </span><span style="background: white; color: blue;">class </span><span style="background: white; color: rgb(43, 145, 175);">MainPage
    </span><span style="background: white; color: black;">{
        </span><span style="background: white; color: blue;">public void </span><span style="background: white; color: black;">OnNavigatedTo()
        {
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Starting MainPage OnNavigatedTo&quot;</span><span style="background: white; color: black;">);

            </span><span style="background: white; color: green;">// Do some work here too...

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(</span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Completed MainPage OnNavigatedTo&quot;</span><span style="background: white; color: black;">);
        }
    }
}
</span></pre>

<p>If you study this app, you will see that the Main method creates instances of PhoneApplicationService, creates an instance of App and passes the PhoneApplicationService instance into its constructor, and finally creates an instance of MainPage and calls its OnNavigatedTo method. This is, of course, exactly what happens when you start a Windows Phone app. When you run it, the output looks like this:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/3482.asyncdemo2_726EE1EE.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/3482.asyncdemo2_5F00_726EE1EE.jpg"><img title="asyncdemo2" style="border: 0px currentcolor; padding-top: 0px; padding-right: 0px; padding-left: 0px; display: inline; background-image: none;" border="0" alt="asyncdemo2" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/0184.asyncdemo2_thumb_26072880.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/0184.asyncdemo2_5F00_thumb_5F00_26072880.jpg" width="617" height="405" /></a></p>

<p>There is clearly something odd going on here: the trace messages from the execution of SomeLongProcedure are output, but right in the middle, the calls to MainPage OnNavigatedTo appear. What’s going on?</p>

<p>Inside the <strong>App</strong> constructor, we hook the <strong>ApplicationLaunching</strong> event of the PhoneApplicationService instance so that in the event handler we can do some setup work when the app launches, and this of course is where we call the long-running async method:</p>

<pre class="code"><span style="background: white; color: black;">        </span><span style="background: white; color: blue;">async void </span><span style="background: white; color: black;">Application_Launching(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">EventArgs </span><span style="background: white; color: black;">e)
        {
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(<br />                </span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Event handler - Calling SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);
            </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">SomeLongProcedureAsync();
            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.WriteLine(<br />                </span><span style="background: white; color: rgb(163, 21, 21);">&quot;TRACE Event handler - Returned from SomeLongProcedure Async&quot;</span><span style="background: white; color: black;">);
        }</span></pre>

<p>We are using the <strong>await</strong> keyword inside this event handler, so of course we mark it with the <strong>async</strong> modifier as normal. So at first glance, the developer expects this code to execute and for the event handler code to wait for completion of SomeLongProcedureAsync() before continuing execution, which in this case is simply to write a message to the console. If we look at the output, that is indeed what happens:</p>

<p><font face="Consolas"><strong>TRACE Event handler - Calling SomeLongProcedure Async 
      <br />TRACE Starting SomeLongProcedure work</strong> 

    <br /><font color="#ff0000">TRACE Starting MainPage OnNavigatedTo 
      <br />TRACE Completed MainPage OnNavigatedTo</font> 

    <br /><strong>TRACE Completed SomeLongProcedure work 
      <br />TRACE Event handler - Returned from SomeLongProcedure Async</strong></font></p>

<p>But as you can see from the trace output, the MainPage OnNavigatedTo method is executed before the Application_Launching event handler has completed, even though it was clearly invoked by the Main function <strong>after</strong> the PhoneApplicationService.DoWork() method was invoked, which is the method that fires the Application_Launching event:</p>

<pre class="code"><span style="background: white; color: black;">        </span><span style="background: white; color: blue;">static void </span><span style="background: white; color: black;">Main(</span><span style="background: white; color: blue;">string</span><span style="background: white; color: black;">[] args)
        {
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">phoneAppService = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">PhoneApplicationService</span><span style="background: white; color: black;">();
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">app = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">App</span><span style="background: white; color: black;">(phoneAppService);
            
            phoneAppService.DoTheWork();

            </span><span style="background: white; color: green;">// When the PhoneApplicationService has completed, construct a MainPage
            </span><span style="background: white; color: blue;">var </span><span style="background: white; color: black;">mainPage = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">MainPage</span><span style="background: white; color: black;">();
            </span><span style="background: white; color: green;">// Call methods on it
            </span><span style="background: white; color: black;">mainPage.OnNavigatedTo();

            </span><span style="background: white; color: rgb(43, 145, 175);">Console</span><span style="background: white; color: black;">.ReadKey();
        }</span></pre>

<p>The problem of course, is that there is no way of awaiting the completion of an event handler, so when the DoWork() method fires the Application_Launching event, it does so in a fire and forget fashion, just the same as in the calling of SomeLongProcedureAsync() without using the await keyword, as we demonstrated in the first example. During execution, code executes sequentially until we hit the await keyword inside the Application_Launching event handler, at which point the wonders of the Task Parallel Library ensure that execution of the Task continues without blocking the original context and control returns immediately to the caller (PhoneApplicationService.DoTheWork() in this case).&#160; </p>

<p>If the Application_Launching event handler had returned <strong>async Task</strong> instead of <strong>async void:</strong>&#160; </p>

<p><font face="Consolas"><font color="#0000ff">async</font> <font color="#4bacc6">Task</font> Application_Launching(<font color="#0000ff">object</font> sender, <font color="#0000ff">EventArgs</font> e)</font></p>

<p>(which is not possible with event handlers) <u>and</u> if it had been called using the await keyword, then&#160; DoWork() would have awaited completion of the Application_Launching event handler logic before continuing, in which case, MainPage.OnNavigatedTo() would not have been called before the Application_Launching logic had completed. You can only await completion of methods that return <strong>Task</strong> or <strong>Task&lt;T&gt;</strong> and since this is impossible with event handlers, you can never await their completion. Hence there is every chance that your MainPage OnNavigatedTo logic will execute before your Application_Launching or Application_Activated logic has completed, although it is actually hit or miss, which is why so many developers report intermittent failures.</p>

<h2>The Solution?</h2>

<p>Of course, this is not a new problem. Any time you execute code asynchronously from your application lifecycle event handlers, whether using async/await or other asynchronous programming techniques, there is a real chance that you will have to implement some kind of synchronisation logic to ensure that your page logic does not try to access objects before your startup logic has set them up. Using older async coding technologies, this was perhaps a little more obvious to the developer, but many devs use the new Task-based async methods without thinking too deeply about it. It just works – or at least seems to until you hit a timing-related problem such as the one I’ve described here.</p>

<p>In the simple demo I described at the beginning of this article, the solution was simple. Instead of exposing the data fro the app in a public property of the App class, I created a new ViewModel class to host it and used XAML databinding to bind the TextBlock on MainPage to a property of the ViewModel. When the Application_Launching logic completed, it updated the ViewModel instance, and through the wonders of INotifyPropertyChanged, the MainPage UI updated with the correct data.</p>

<p>For other solutions, you may need to implement some other mechanism. One example was shown me by Peter Torr of the Windows Phone Product Group and is shown in the sample app which you can download from my post on SQLite:&#160; <a href="http://andywigley.com/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/">SQLite-WinRT: Database programming on Windows Phone and Windows 8</a> . That sample opens (and the first time, creates) the SQLite database in Application_Launching and when resuming from tombstoning in Application_Activated. That sample used an old-fashioned synchronisation primitive, a <strong>ManualResetEvent</strong>, as a flag that is only set when the application lifecycle logic has finished:</p>

<pre class="code"><span style="background: white; color: black;">  </span><span style="background: white; color: blue;">public partial class </span><span style="background: white; color: rgb(43, 145, 175);">App </span><span style="background: white; color: black;">: </span><span style="background: white; color: rgb(43, 145, 175);">Application
  </span><span style="background: white; color: black;">{
    </span><span style="background: white; color: blue;">static </span><span style="background: white; color: black;">SQLiteWinRTPhone.</span><span style="background: white; color: rgb(43, 145, 175);">Database </span><span style="background: white; color: black;">db;
    </span><span style="background: white; color: blue;">static </span><span style="background: white; color: rgb(43, 145, 175);">ManualResetEvent </span><span style="background: white; color: black;">DBLoaded = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: rgb(43, 145, 175);">ManualResetEvent</span><span style="background: white; color: black;">(</span><span style="background: white; color: blue;">false</span><span style="background: white; color: black;">);

    </span><span style="background: white; color: blue;">public static </span><span style="background: white; color: rgb(43, 145, 175);">Task</span><span style="background: white; color: black;">&lt;SQLiteWinRTPhone.</span><span style="background: white; color: rgb(43, 145, 175);">Database</span><span style="background: white; color: black;">&gt; GetDatabaseAsync()
    {
      </span><span style="background: white; color: blue;">return </span><span style="background: white; color: rgb(43, 145, 175);">Task</span><span style="background: white; color: black;">.Run(() =&gt;
      {
        DBLoaded.WaitOne();
        </span><span style="background: white; color: blue;">return </span><span style="background: white; color: black;">db;
      });
    }

    </span><span style="background: white; color: green;">// Code to execute when the application is launching (eg, from Start)
    // This code will not execute when the application is reactivated
    </span><span style="background: white; color: blue;">private void </span><span style="background: white; color: black;">Application_Launching(</span><span style="background: white; color: blue;">object </span><span style="background: white; color: black;">sender, </span><span style="background: white; color: rgb(43, 145, 175);">LaunchingEventArgs </span><span style="background: white; color: black;">e)
    {
      LoadDatabase();
    }

    </span><span style="background: white; color: blue;">private async </span><span style="background: white; color: rgb(43, 145, 175);">Task </span><span style="background: white; color: black;">LoadDatabase()
    {
      </span><span style="background: white; color: green;">// Get a reference to the SQLite database
      </span><span style="background: white; color: black;">db = </span><span style="background: white; color: blue;">new </span><span style="background: white; color: black;">SQLiteWinRTPhone.</span><span style="background: white; color: rgb(43, 145, 175);">Database</span><span style="background: white; color: black;">(<br />          </span><span style="background: white; color: rgb(43, 145, 175);">ApplicationData</span><span style="background: white; color: black;">.Current.LocalFolder, </span><span style="background: white; color: rgb(163, 21, 21);">&quot;sqlitedemo.db&quot;</span><span style="background: white; color: black;">);

      </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.OpenAsync();

      </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">sql = </span><span style="background: white; color: rgb(163, 21, 21);">@&quot;CREATE TABLE IF NOT EXISTS
                                Customer (Id      INTEGER PRIMARY KEY,
                                          Name    VARCHAR( 140 ),
                                          City    VARCHAR( 140 ),
                                          Contact VARCHAR( 140 ) 
                            );&quot;</span><span style="background: white; color: black;">;
      </span><span style="background: white; color: blue;">string </span><span style="background: white; color: black;">description = </span><span style="background: white; color: rgb(163, 21, 21);">&quot;Create Customer table&quot;</span><span style="background: white; color: black;">;
      </span><span style="background: white; color: blue;">await </span><span style="background: white; color: black;">db.ExecuteStatementAsync(sql);
        </span><span style="background: white; color: black;">
</span><span style="background: white; color: black;">
      DBLoaded.Set();
    }
</span><span style="background: white; color: black;">}</span></pre>

<p>The ManualResetEvent is declared unsignalled as a static field of the app class:</p>

<p>&#160;<font face="Consolas">static ManualResetEvent DBLoaded = new ManualResetEvent(false);</font></p>

<p>and is only set at the very end of the <strong>async Task LoadDatabase()</strong> method:</p>

<p><font face="Consolas">private async Task LoadDatabase() 
    <br />{ 

    <br />&#160; // Get a reference to the SQLite database 

    <br />&#160; db = new SQLiteWinRTPhone.Database(…); 

    <br />&#160;</font><font face="Consolas"> await db.OpenAsync(); 
    <br /></font><font face="Consolas">&#160; ...</font></p>

<p><font face="Consolas">&#160; DBLoaded.Set(); 
    <br />}</font></p>

<p>The final key ingredient is a ‘gatekeeper’ method which must be called by every other method in the app that wants to access the database:</p>

<p><font face="Consolas">public static Task&lt;SQLiteWinRTPhone.Database&gt; GetDatabaseAsync() 
    <br />{ 

    <br />&#160; return Task.Run(() =&gt; 

    <br />&#160; { 

    <br />&#160;&#160;&#160; DBLoaded.WaitOne(); 

    <br />&#160;&#160;&#160; return db; 

    <br />&#160; }); 

    <br />}</font></p>

<p>This method waits for the DBLoaded semaphore to be set and does so on a Threadpool thread (through Task.Run()) so does not block the UI thread.</p>

<h3>Calling async code from Application_Deactivated or Application_Closing</h3>

<p>The guidance here is “don’t'”. If you write your apps carefully, you can be saving changes to persistent data as you go along, so you shouldn’t have anything to do in the application lifecycle events.</p>

<p>If you must, you can try doing something like this: </p>

<p><font face="Consolas">SomeAsyncMethod().AsTask().Wait()</font>&#160;&#160;&#160; </p>

<p>If the operation completes within the timeout period AND it doesn’t deadlock due to needing to pump the UI thread, it will work… but don’t count on it. </p>



<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:d8bd688d-f34a-4f53-8f58-40d7f15095e2" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5187.AsyncSynchronizationProblem_1BABB018.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5187.AsyncSynchronizationProblem_5F00_1BABB018.zip" target="_blank">Sample code</a></p></div>]]></content:encoded>
    </item>
    <item>
      <title>SQLite-WinRT: Database programming on Windows Phone and Windows 8</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/sqlite-winrt-database-programming-on-windows-phone-and-windows-8</link>
      <pubDate>Thu, 06 Jun 2013 12:48:06 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/</guid>
      <description><![CDATA[Today at TechEd North America in New Orleans, I am presenting a session on programming the SQLite...]]></description>
      <content:encoded><![CDATA[<p>Today at TechEd North America in New Orleans, I am presenting a session on programming the SQLite database on Windows Phone 8. You can watch the video and download the slides from here: <a href="https://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/WPH-B306#fbid=JdY6A6IA9Ej" target="_blank">Support Your Demanding LOB Apps With SQLite and Windows Phone 8</a>. The sample application I walked through is here:</p>  <div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:a8c2f424-bd71-4de5-a18e-0800f057e7bb" class="wlWriterEditableSmartContent" style="margin: 0px; padding: 0px; float: none; display: inline;"><p> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/5444.SqlitePhoneSample_195D42FB.zip" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/5444.SqlitePhoneSample_5F00_195D42FB.zip" target="_blank">SqlitePhoneSample.zip</a></p></div>  <p>The session is a deep dive on the new SQLite-WinRT API that we released on Codeplex last week. This new API is a thin wrapper around the native database engine, sqlite3.dll and exposes the key methods of the database engine through a modern Windows Runtime API callable from C#, Visual Basic and C++ that is all async methods and which reports unexpected results by throwing exceptions. The code is all up at <a href="http://sqlwinrt.codeplex.com">http://sqlwinrt.codeplex.com</a>. There’s no download for this project – you just download the source code, which is a complete Visual Studio 2012 solution containing projects for Windows Phone 8 and Windows 8 Store App components.</p>  <h3>Why another database API on Windows Phone?</h3>  <p>That’s a valid question! After all, we already have the <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspx">Local Database</a> in the Windows Phone SDK which is a LINQ to SQL API where the underlying database is SQL Server Compact Edition 3.7-ish. And we also have the <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/03/12/using-the-sqlite-database-engine-with-windows-phone-8-apps.aspx">SQLite-NET API</a> for accessing SQLite which also exposes a LINQ API for working with a SQLite database. The Local Database LINQ to SQL API is not available for Windows 8 Store App development so not a great choice if you want to share code between your phone and tablet/PC apps, but SQLite-NET is available for both phone and Windows 8, as is SQLite-WinRT – so why do we need this new API?</p>  <p>SQLite-WinRT is for those developers who prefer to work with SQL statements rather than the object-oriented layer that LINQ gives you. It is also for those coming to Windows Phone 8 or Windows 8 from other platforms who have worked with SQLite before probably programming with C/C++ – the methods exposed by the SQLite-WinRT API are very thin wrappers around the SQLite C/C++ API. It’s all about giving choice to our developers – we have heard feedback that not all developers like to work with a local database using LINQ, so this API is for them.</p>  <p>To give you a comparison, this is how you might select a Customer from the Customer table using SQLite-NET:</p>  <pre class="csharpcode">var db =&#160; <span class="kwrd">new</span> SQLite.SQLiteAsyncConnection(App.DBPath); 
var _customer = await&#160; (from c <span class="kwrd">in</span> db.Table&lt;Customer&gt;() 
                        <span class="kwrd">where</span> c.Id == customerId&#160; <br />                        select c).FirstOrDefaultAsync(); 

<span class="kwrd">if</span> (customer != <span class="kwrd">null</span>) 
{&#160; <br />&#160;&#160;&#160; var Id = _customer.Id;
    var Name = _customer.Name;
}</pre>


<p>And this is how you would do the same thing in SQLite-WinRT:</p>

<pre class="csharpcode"><span class="kwrd">using</span> (var db = <span class="kwrd">new</span> SQLiteWinRTPhone.Database(
    ApplicationData.Current.LocalFolder, <span class="str">&quot;demo.db&quot;</span>)) 
{ 
    await db.OpenAsync(); 
    <span class="kwrd">using</span> (var stmt = await db.PrepareStatementAsync(<span class="str">&quot;SELECT name, age FROM people&quot;</span>)) 
    { 
        <span class="kwrd">while</span> (await stmt.StepAsync()) 
        { 
            var name = stmt.GetTextAt(0); 
            var age = stmt.GetIntAt(1); 
        } 
    } 
}</pre>

<p>The choice is yours!</p>

<h2>Getting Started with SQLite-WinRT</h2>

<p>Start by installing the SQLite Extension SDK. This is the native dll, sqlite3.dll, which contains the database engine. To install this, in Visual Studio, on the <strong>Tools</strong> menu, open <strong>Extensions and Updates</strong>. In the left hand pane, select Online – Visual Studio Gallery, then enter SQLite into the search box. Select <strong>SQLite for Windows Phone</strong> and click the Download button to download and install the vsix package. (The same procedure works for the SQLite for Windows Runtime extension for Windows 8 Store Apps.)</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/2110.image_3B85C418.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/2110.image_5F00_3B85C418.png"><img title="image" style="display: inline; background-image: none;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/4101.image_thumb_689AB0E6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/4101.image_5F00_thumb_5F00_689AB0E6.png" width="550" height="382" /></a></p>

<p>After you’ve installed that, the native sqlite3 dlls are installed into a folder under C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\ExtensionSDKs\SQLite.WP80\. That’s just for your information – you should never have to manually copy the sqlite3.dll from there in order to use the database</p>

<p><strong><u>Warning</u></strong>: You will be prompted whenever an update is available for the SQLite database engine. When you install it, you will inadvertently ‘break’ SQLite-WinRT, in the sense that Visual Studio will be unable to open the project. That is because the project references the C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\ExtensionSDKs\SQLite.WP80\3.7.17 path in a number of places, and when you upgrade SQLite, the version part of that path will change. 

  <br />I will be adding a powershell script into the download to make it easy to update the SQLite-WinRT project file with the correct path, but if this happens to you before I do it, just edit the SQLiteWinRTPhone.vcxproj file (carefully!) to correct references to the old version and update them to pojnt at whatever new version you have installed.</p>

<h2>Creating your Project</h2>

<p>Create your C# or Visual Basic project as normal. Then go to <a href="http://sqlwinrt.codeplex.com">http://sqlwinrt.codeplex.com</a> and download the source code from there – remember there is no ‘official download’ for this Codeplex project.</p>

<p>&#160;</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/1070.image_40F434BC.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/1070.image_5F00_40F434BC.png"><img title="image" style="display: inline; background-image: none;" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/56/30/metablogapi/7652.image_thumb_0E242E48.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-56-30-metablogapi/7652.image_5F00_thumb_5F00_0E242E48.png" width="555" height="346" /></a></p>

<p>The source code for this project is a solution containing two projects, the SQLite-WinRT component for Windows Phone, and the same thing but for Windows 8 Store Apps. Copy the Windows Phone project and use ‘Add Existing Project…’ to add it into your solution, then add a reference to the SQLite-WinRT project from your C#/VB project. That’s all you have to do!</p>

<p>Remember, if Visual Studio cannot load the SQLite-WinRT project, it’s probably because the SQLite extension has been updated. Read the Warning a few paragraphs before to resolve this.</p>

<h2>Creating a database</h2>

<p>To create a database, you can use code such as this:</p>

<pre class="csharpcode">    <span class="kwrd">private</span> async <span class="kwrd">void</span> LoadDatabase()
    {
      <span class="rem">// Get a reference to the SQLite database</span>
      db = <span class="kwrd">new</span> SQLiteWinRTPhone.Database(ApplicationData.Current.LocalFolder, <span class="str">&quot;sqlitedemo.db&quot;</span>);

      await db.OpenAsync();

      <span class="kwrd">string</span> sql = <span class="str">@&quot;CREATE TABLE IF NOT EXISTS
                                Customer (Id      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                          Name    VARCHAR( 140 ),
                                          City    VARCHAR( 140 ),
                                          Contact VARCHAR( 140 ) 
                            );&quot;</span>;
      <span class="kwrd">string</span> description = <span class="str">&quot;Create Customer table&quot;</span>;
      await ExecuteSQLStatement(db, sql, description);

      sql = <span class="str">@&quot;CREATE TABLE IF NOT EXISTS
                   Project (Id          INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                            CustomerId  INTEGER,
                            Name        VARCHAR( 140 ),
                            Description VARCHAR( 140 ),
                            DueDate     DATETIME,
                            FOREIGN KEY(CustomerId) REFERENCES Customer(Id) ON DELETE CASCADE 
                            )&quot;</span>;
      description = <span class="str">&quot;Create Project table&quot;</span>;
      await ExecuteSQLStatement(db, sql, description);

      <span class="rem">// Turn on Foreign Key constraints</span>
      sql = <span class="str">@&quot;PRAGMA foreign_keys = ON&quot;</span>;
      description = <span class="str">&quot;Enable foreign key constraints&quot;</span>;
      await ExecuteSQLStatement(db, sql, description);

      DBLoaded.Set();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> async Task ExecuteSQLStatement(<br />                                SQLiteWinRTPhone.Database db, <span class="kwrd">string</span> sql, <span class="kwrd">string</span> description)
    {
      <span class="kwrd">try</span>
      {
        await db.ExecuteStatementAsync(sql);
        Debug.WriteLine(description + <span class="str">&quot; executed OK&quot;</span>);
      }
      <span class="kwrd">catch</span> (Exception ex)
      {
        var result = SQLiteWinRTPhone.Database.GetSqliteErrorCode(ex.HResult);
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(description + <span class="str">&quot; Failed with error &quot;</span> + result);
      }
    }</pre>


<p>You can call this code from your Application_Loaded and Application_Activated event handlers. One particular thing I want to call out here: notice the last line of the LoadDatabase method:</p>

<pre class="csharpcode">DBLoaded.Set();</pre>

<p><strong>DBLoaded</strong> is a <strong>ManualResetEvent</strong> which is used to flag when the database opening logic has completed. It is declared at the top of my App.Xaml.cs class, along with a ‘Gatekeeper’ method called GetDatabaseAsync():</p>

<pre class="csharpcode">  <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> App : Application
  {
    <span class="kwrd">static</span> SQLiteWinRTPhone.Database db;
    <span class="kwrd">static</span> ManualResetEvent DBLoaded = <span class="kwrd">new</span> ManualResetEvent(<span class="kwrd">false</span>);

    <span class="kwrd">public</span> <span class="kwrd">static</span> Task&lt;SQLiteWinRTPhone.Database&gt; GetDatabaseAsync()
    {
      <span class="kwrd">return</span> Task.Run(() =&gt;
      {
        DBLoaded.WaitOne();
        <span class="kwrd">return</span> db;
      });
    }</pre>


<p>The ManualResetEvent is created unset, and doesn’t get set until the last line of LoadDatabase(). All other database access code in my viewmodel classes makes a call to GetDatabaseAsync as the first thing it does. The DBLoaded.WaitOne() call in there blocks until DBLoaded is set, so this prevents any other database accessing code from executing until the LoadDatabase() method has completed.</p>

<h2>Handling Errors</h2>

<p>The SQLWinRT API throws exceptions when something goes wrong. Unfortunately, exceptions thrown in a WinRT component are not the most developer-friendly things ever devised. They are COMException objects, have no useful error text in them and just return to you a HResult. But you can get a meaningful error message if you call the handy GetSqliteErrorCode method which is used like this:</p>

<pre class="csharpcode">      <span class="kwrd">try</span>
      {
        await db.ExecuteStatementAsync(sql);
      }
      <span class="kwrd">catch</span> (COMException ex)
      {
        var result = SQLiteWinRTPhone.Database.GetSqliteErrorCode(ex.HResult);
        <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(description + <span class="str">&quot; Failed with error &quot;</span> + result);
      }
</pre>


<p>GetSqliteErrorCode() returns the – yes, you guessed it – SQLite error code, which mostly are self explanatory (such as ‘SQLITE_CONSTRAINT’) are documented at <a title="http://www.sqlite.org/c3ref/c_abort.html" href="http://www.sqlite.org/c3ref/c_abort.html">http://www.sqlite.org/c3ref/c_abort.html</a>.</p>

<h2>CRUD operations</h2>

<h3>Create </h3>

<p>To create records in the database, use code similar to this:</p>

<pre class="csharpcode"><span class="kwrd">try</span> 
{
    <span class="rem">// Connection already opened in app.xaml.cs - get reference<br /></span>&#160;&#160;&#160; SQLiteWinRT.Database db = await App.GetDatabaseAsync();<br />&#160;&#160;&#160; <span class="kwrd">using</span> (var custstmt = await db.PrepareStatementAsync(
      <span class="str">&quot;INSERT INTO Customer (Name, City, Contact) VALUES (@name, @city, @contact)&quot;</span>))
    {&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span class="rem">// NOTE that named parameters have a leading &quot;@&quot;,&quot;:&quot; or &quot;$&quot;.&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span>
        custstmt.BindTextParameterWithName(<span class="str">&quot;@name&quot;</span>, customer.Name);
        custstmt.BindTextParameterWithName(<span class="str">&quot;@city&quot;</span>, customer.City);<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; custstmt.BindTextParameterWithName(<span class="str">&quot;@contact&quot;</span>, customer.Contact);
<br />        <span class="rem">// Use StepAsync to execute a prepared statement</span>&#160;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; await custstmt.StepAsync();<br />&#160;&#160;&#160;&#160; } 
} 
<span class="kwrd">catch</span> (System.Runtime.InteropServices.COMException) 
{ … }
</pre>

<p>This uses a SQL statement containing named parameters (@name, @city, @contact), which you prepare using <strong>PrepareStatementAsync()</strong> and which you ‘plug in’ the values using the <strong>Bind<em>type</em>ParameterWithName(string parametername, <em>type</em> value)</strong> method. An alternative is to use anonymous parameters (shown below when describing Update).</p>

<p>Notice that we use the StepAsync() method to execute a row-returning SQL statement. StepAsync may seem curious, but the SQLite C/C++ API method this wraps is called Step(), so that’s the name we adopt for our WinRT method.</p>

<p><strong>IMPORTANT</strong>: Remember to dispose of your Statement objects when you’re done with them – a good way of doing that is to use the C# <strong>using</strong> statement, as shown above.</p>

<h3>Read</h3>

<p>To read objects, use a SELECT statement:</p>

<pre class="csharpcode"><span class="kwrd">public</span> async Task&lt;CustomerViewModel&gt; GetCustomerAsync(<span class="kwrd">int</span> customerId)
{
    var db = await App.GetDatabaseAsync();<br />&#160;&#160;&#160; CustomerViewModel customer = <span class="kwrd">null</span>;<br />&#160;&#160;&#160; <span class="kwrd">using</span> (var readstmt = await db.PrepareStatementAsync(
              <span class="str">&quot;SELECT Id, Name, City, Contact FROM Customer WHERE Id = &quot;</span> + customerId)) <br />    {<br />&#160;&#160;&#160;&#160;&#160; <span class="kwrd">if</span> (await readstmt.StepAsync() == <span class="kwrd">true</span>)<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {<br />&#160;&#160;&#160;&#160;&#160;&#160; var customer = <span class="kwrd">new</span> CustomerViewModel()<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {<br />&#160;&#160;&#160;&#160;&#160; Id = readstmt.GetIntAt(0),<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Name = readstmt.GetTextAt(1),<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; City = readstmt.GetTextAt(2),<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Contact = readstmt.GetTextAt(3)<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }; 
        }<br />&#160;&#160;&#160; }<br />&#160;&#160;&#160; <span class="kwrd">return</span> customers;
}
</pre>


<p><strong>StepAsync()</strong> returns <strong>true</strong> if there is a row to return. The example above would reasonably be expected to return just a single row, but if you get multiple rows returned from the database, then you would loop around creating your in-memory objects (your viewmodel objects) and entering them into some collection until StepAsync() returns false.</p>

<p>An alternative form of SELECT allows you to extract data from the rowset returned from the database by using the column name, rather than the column position as the previous code sample did. You enable this behaviour by calling the Statement.EnableColumnsProperty() method. Then the results are returned as a Dictionary&lt;string, string&gt; which you key into using the column name:</p>

<pre class="csharpcode">&#160;&#160;&#160; <span class="kwrd">using</span> (var readstmt = await db.PrepareStatementAsync(
              <span class="str">&quot;SELECT Id, Name, City, Contact FROM Customer WHERE Id = &quot;</span> + customerId))<br />&#160;&#160;&#160; {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span class="rem">// Enable the columns property<br /></span>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; statement.EnableColumnsProperty();<br /><br />&#160;&#160;&#160;&#160;&#160;&#160; <span class="kwrd">if</span> (await readstmt.StepAsync() == <span class="kwrd">true</span>)<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; { 
            <span class="rem">// it isn't super useful as all columns are returned as text and must be parsed<br />        </span>&#160;&#160;&#160; var columns = statement.Columns;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var customer = <span class="kwrd">new</span> CustomerViewModel()<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {<br />&#160;&#160;&#160;&#160;&#160; Id = <span class="kwrd">int</span>.Parse(columns[<span class="str">&quot;Id&quot;</span>]),<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Name = columns[<span class="str">&quot;Name&quot;</span>],<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; City = columns[<span class="str">&quot;City&quot;</span>],<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Contact = columns[<span class="str">&quot;Contact&quot;</span>]<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }; 
        }<br />&#160;&#160;&#160; } </pre>


<p>This does impose a slight performance overhead, and every value returns as a string, so you have to parse the string to get the correct value type, as shown here for the Id column.</p>

<h3>Update</h3>

<p>Update is simple enough. This sample uses anonymous parameters in the SQL statement, rather then the named parameters we saw when discussing the Insert operation. Note that anonymous parameters are 1-based, not 0-based like just about every other collection in .NET!</p>

<pre class="csharpcode"><span class="rem">// See if the customer already exists</span>
var existingCustomer = await GetCustomerAsync(customer.Id); 
<span class="kwrd">if</span> (existingCustomer != <span class="kwrd">null</span>) 
{&#160;&#160;&#160; <span class="kwrd">using</span> (var custstmt = await db.PrepareStatementAsync(
        <span class="str">&quot;UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?&quot;</span>)) 
    { 
        <span class="rem">// NOTE when using anonymous parameters the first has an index of 1, not 0. </span>
        custstmt.BindTextParameterAt(1, customer.Name);<br />&#160;&#160; custstmt.BindTextParameterAt(2, customer.City);<br />&#160;&#160;&#160; custstmt.BindTextParameterAt(3, customer.Contact);<br />&#160;&#160;&#160; custstmt.BindIntParameterAt(4, customer.Id);<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; await custstmt.StepAsync();<br />&#160;&#160; }<br />}
</pre>

<p></p>

<h3>Delete</h3>

<p>Delete is simple enough:</p>

<pre class="csharpcode">  <span class="kwrd">string</span> sql = <span class="str">@&quot;DELETE FROM Customer WHERE Id={0}&quot;</span>; 
  sql = <span class="kwrd">string</span>.Format(sql, customerId);<br /><br />&#160; <span class="rem">// Can use ExecuteStatementAsync to run non row returning statements</span>
  await App.db.ExecuteStatementAsync(sql);
</pre>

<h2>Summary</h2>

<p>That’s an introduction to getting started with SQLite-WinRT. In the next posts, I will talk some more about Foreign Key constraints and about working with Read-only databases.</p>
]]></content:encoded>
    </item>
    <item>
      <title>PhoneGap devs–bring your app to Windows Phone and win!</title>
      <link>https://docs.microsoft.com/archive/blogs/andy_wigley/phonegap-devsbring-your-app-to-windows-phone-and-win</link>
      <pubDate>Tue, 21 May 2013 02:09:31 GMT</pubDate>
      <dc:creator><![CDATA[Andy Wigley]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/andy_wigley/2013/05/21/phonegap-devsbring-your-app-to-windows-phone-and-win/</guid>
      <description><![CDATA[From now until&nbsp; June 30th, 2013, we are running a competition aimed at developers who have...]]></description>
      <content:encoded><![CDATA[From now until&nbsp; June 30th, 2013, we are running a competition aimed at developers who have built PhoneGap apps and published in other stores &ndash; for example, Apple iTunes, Google Play, Blackberry World, Bada, Symbian, or Palm OS &ndash; to take any of their existing PhoneGap apps and port it to Windows Phone 8, like the Untappd app <a href="http://blog.untappd.com/post/49432420630/untappd-for-windows-phone-8">recently ported to Windows Phone 8</a>.

<a href="http://www.phonegapwpchallenge.com/"><img title="clip_image002" border="0" alt="clip_image002" src="http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image002_5F00_thumb_5F00_43F15E0B.png" width="223" height="240"></a>

Members of a panel selected from Microsoft, the Adobe PhoneGap team, and industry experts will choose 20 winners, based on apps that are:

<ul>   <li>Original </li>    <li>Innovative </li>    <li>Easy to use </li>    <li>Engaging and visually appealing to the user</li> </ul>

The panel will pick 3 grand prize winners who each will receive a Windows Phone 8 and a Surface Pro, and 17 first prize winners who each will receive a Windows Phone 8. All winning apps will be evaluated for featured slots in the Windows Phone Store.

<p>Full details on the <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/05/20/use-your-html5-skills-port-your-phonegap-app-to-windows-phone-and-win-prizes.aspx">Windows Phone Dev Blog here</a>, entry page for the <a href="http://www.phonegapwpchallenge.com/">Windows Phone Porting Challenge competition here</a>.</p>]]></content:encoded>
    </item>
  </channel>
</rss>