<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Andy Wigley&#039;s Blog</title>
	<atom:link href="http://andywigley.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://andywigley.com</link>
	<description>Building phone and tablet apps using Microsoft technologies...</description>
	<lastBuildDate>Thu, 06 Jun 2013 21:20:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='andywigley.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/0c01244de28b816c5363d1210d2e4bea?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Andy Wigley&#039;s Blog</title>
		<link>http://andywigley.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://andywigley.com/osd.xml" title="Andy Wigley&#039;s Blog" />
	<atom:link rel='hub' href='http://andywigley.com/?pushpress=hub'/>
		<item>
		<title>SQLite-WinRT: Database programming on Windows Phone and Windows 8</title>
		<link>http://andywigley.com/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/</link>
		<comments>http://andywigley.com/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/#comments</comments>
		<pubDate>Thu, 06 Jun 2013 19:49:35 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=53</guid>
		<description><![CDATA[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: Support Your Demanding LOB Apps With SQLite and Windows Phone 8. The sample application I walked through is here: SqlitePhoneSample.zip The session [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=53&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></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="http://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="float:none;margin:0;display:inline;padding:0;">
<p> <a href="http://andywigley.files.wordpress.com/2013/06/sqlitephonesample5.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 = <span class="kwrd">new</span> SQLite.SQLiteAsyncConnection(App.DBPath); 
var _customer = await (from c <span class="kwrd">in</span> db.Table&lt;Customer&gt;() 
                        <span class="kwrd">where</span> c.Id == customerId 
                        select c).FirstOrDefaultAsync(); 
<span class="kwrd">if</span> (customer != <span class="kwrd">null</span>) 
{ 
    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">"demo.db"</span>)) 
{ 
    await db.OpenAsync(); 
    <span class="kwrd">using</span> (var stmt = await db.PrepareStatementAsync(
                        <span class="str">"SELECT name, age FROM people"</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="http://andywigley.files.wordpress.com/2013/06/image_thumb31.png"><img title="image_thumb3" style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" border="0" alt="image_thumb3" src="http://andywigley.files.wordpress.com/2013/06/image_thumb3_thumb1.png?w=535&#038;h=373" width="535" height="373"></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>&nbsp;</p>
<p><a href="http://andywigley.files.wordpress.com/2013/06/image_thumb71.png"><img title="image_thumb7" style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" border="0" alt="image_thumb7" src="http://andywigley.files.wordpress.com/2013/06/image_thumb7_thumb1.png?w=548&#038;h=344" width="548" height="344"></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="code"><span style="background:white;color:black;">    </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:#2b91af;">LaunchingEventArgs </span><span style="background:white;color:black;">e)
    {
      LoadDatabase();
    }

    </span><span style="background:white;color:blue;">private 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;">SQLiteWinRTPhone.</span><span style="background:white;color:#2b91af;">Database</span><span style="background:white;color:black;">(
          </span><span style="background:white;color:#2b91af;">ApplicationData</span><span style="background:white;color:black;">.Current.LocalFolder, </span><span style="background:white;color:#a31515;">"sqlitedemo.db"</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:#a31515;">@"CREATE TABLE IF NOT EXISTS
                    Customer (Id      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                                Name    VARCHAR( 140 ),
                                City    VARCHAR( 140 ),
                                Contact VARCHAR( 140 ) 
                );"</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:#a31515;">"Create Customer table"</span><span style="background:white;color:black;">;
      </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">ExecuteSQLStatement(db, sql, description);

      sql = </span><span style="background:white;color:#a31515;">@"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 
                )"</span><span style="background:white;color:black;">;
      description = </span><span style="background:white;color:#a31515;">"Create Project table"</span><span style="background:white;color:black;">;
      </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">ExecuteSQLStatement(db, sql, description);

      </span><span style="background:white;color:green;">// Turn on Foreign Key constraints
      </span><span style="background:white;color:black;">sql = </span><span style="background:white;color:#a31515;">@"PRAGMA foreign_keys = ON"</span><span style="background:white;color:black;">;
      description = </span><span style="background:white;color:#a31515;">"Enable foreign key constraints"</span><span style="background:white;color:black;">;
      </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">ExecuteSQLStatement(db, sql, description);

      DBLoaded.Set();
    }

    </span><span style="background:white;color:blue;">private static async </span><span style="background:white;color:#2b91af;">Task </span><span style="background:white;color:black;">ExecuteSQLStatement(
        SQLiteWinRTPhone.</span><span style="background:white;color:#2b91af;">Database </span><span style="background:white;color:black;">db, 
        </span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">sql, 
        </span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">description)
    {
      </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:black;">db.ExecuteStatementAsync(sql);
        </span><span style="background:white;color:#2b91af;">Debug</span><span style="background:white;color:black;">.WriteLine(description + </span><span style="background:white;color:#a31515;">" executed OK"</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:#2b91af;">Exception </span><span style="background:white;color:black;">ex)
      {
        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">result = 
            SQLiteWinRTPhone.</span><span style="background:white;color:#2b91af;">Database</span><span style="background:white;color:black;">.GetSqliteErrorCode(ex.HResult);
        </span><span style="background:white;color:blue;">throw new </span><span style="background:white;color:#2b91af;">ApplicationException</span><span style="background:white;color:black;">(description + 
            </span><span style="background:white;color:#a31515;">" Failed with error " </span><span style="background:white;color:black;">+ result);
      }
    }</span></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>
<p>&nbsp;&nbsp;&nbsp; <font face="Consolas">DBLoaded.Set();</font></p>
<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="code"><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:#2b91af;">Database </span><span style="background:white;color:black;">db;
    </span><span style="background:white;color:blue;">static </span><span style="background:white;color:#2b91af;">ManualResetEvent </span><span style="background:white;color:black;">DBLoaded = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">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:#2b91af;">Task</span><span style="background:white;color:black;">&lt;SQLiteWinRTPhone.</span><span style="background:white;color:#2b91af;">Database</span><span style="background:white;color:black;">&gt; GetDatabaseAsync()
    {
      </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#2b91af;">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></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="code"><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:black;">db.ExecuteStatementAsync(sql);
}
</span><span style="background:white;color:blue;">catch </span><span style="background:white;color:black;">(</span><span style="background:white;color:#2b91af;">Exception </span><span style="background:white;color:black;">ex)
{
</span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">result = 
    SQLiteWinRTPhone.</span><span style="background:white;color:#2b91af;">Database</span><span style="background:white;color:black;">.GetSqliteErrorCode(ex.HResult);
</span><span style="background:white;color:blue;">throw new </span><span style="background:white;color:#2b91af;">ApplicationException</span><span style="background:white;color:black;">(</span><span style="background:white;color:#a31515;">"Failed with error " </span><span style="background:white;color:black;">+ result);
}</span></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="code"><span style="background:white;color:blue;">try 
</span><span style="background:white;color:black;">{
    </span><span style="background:white;color:green;">// Connection already opened in app.xaml.cs - get reference&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="background:white;color:black;">SQLiteWinRT.Database db = </span><span style="background:white;color:#2b91af;">App</span><span style="background:white;color:black;">.db;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </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;">custstmt = await db.PrepareStatementAsync(
    </span><span style="background:white;color:#a31515;">"INSERT INTO Customer (Name, City, Contact) VALUES (@name, @city, @contact)"
      </span><span style="background:white;color:black;">))
    {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="background:white;color:green;">// NOTE that named parameters have a leading "@",":" or "$".&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="background:white;color:black;">custstmt.BindTextParameterWithName(</span><span style="background:white;color:#a31515;">"@name"</span><span style="background:white;color:black;">, customer.Name);
        custstmt.BindTextParameterWithName(</span><span style="background:white;color:#a31515;">"@city"</span><span style="background:white;color:black;">, customer.City);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; custstmt.BindTextParameterWithName(</span><span style="background:white;color:#a31515;">"@contact"</span><span style="background:white;color:black;">, customer.Contact);
        </span><span style="background:white;color:green;">// Use StepAsync to execute a prepared statement&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="background:white;color:black;">await custstmt.StepAsync();&nbsp;&nbsp;&nbsp;&nbsp; } 
} 
</span><span style="background:white;color:blue;">catch </span><span style="background:white;color:black;">(System.Runtime.InteropServices.</span><span style="background:white;color:#2b91af;">COMException</span><span style="background:white;color:black;">) 
{ … }</span></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="code"><span style="background:white;color:blue;">public async </span><span style="background:white;color:#2b91af;">Task</span><span style="background:white;color:black;">&lt;</span><span style="background:white;color:#2b91af;">CustomerViewModel</span><span style="background:white;color:black;">&gt; GetCustomerAsync(</span><span style="background:white;color:blue;">int </span><span style="background:white;color:black;">customerId)
{
    </span><span style="background:white;color:#2b91af;">CustomerViewModel </span><span style="background:white;color:black;">customer = </span><span style="background:white;color:blue;">null</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;">readstmt = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:#2b91af;">App</span><span style="background:white;color:black;">.db.PrepareStatementAsync(
                </span><span style="background:white;color:#a31515;">"SELECT Id, Name, City, Contact FROM Customer WHERE Id = " 
                </span><span style="background:white;color:black;">+ customerId))
    {
        </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(</span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">readstmt.StepAsync() == </span><span style="background:white;color:blue;">true</span><span style="background:white;color:black;">)
        {
            </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">customer = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">CustomerViewModel</span><span style="background:white;color:black;">()
            {
                Id = readstmt.GetIntAt(0),
                Name = readstmt.GetTextAt(1),
                City = readstmt.GetTextAt(2),
                Contact = readstmt.GetTextAt(3)
            };
        }
    }
    </span><span style="background:white;color:blue;">return </span><span style="background:white;color:black;">customers;
}</span></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="code"><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;">readstmt = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:#2b91af;">App</span><span style="background:white;color:black;">.db.PrepareStatementAsync(
    </span><span style="background:white;color:#a31515;">"SELECT Id, Name, City, Contact FROM Customer WHERE Id = " 
    </span><span style="background:white;color:black;">+ customerId))
{
    </span><span style="background:white;color:green;">// Enable the columns property
    </span><span style="background:white;color:black;">statement.EnableColumnsProperty();

    </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(</span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">readstmt.StepAsync() == </span><span style="background:white;color:blue;">true</span><span style="background:white;color:black;">)
    {
        </span><span style="background:white;color:green;">// it isn't super useful as all columns are returned as text and must be parsed 
        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">columns = statement.Columns;
        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">customer = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">CustomerViewModel</span><span style="background:white;color:black;">()
        {
            Id = </span><span style="background:white;color:blue;">int</span><span style="background:white;color:black;">.Parse(columns[</span><span style="background:white;color:#a31515;">"Id"</span><span style="background:white;color:black;">]),
            Name = columns[</span><span style="background:white;color:#a31515;">"Name"</span><span style="background:white;color:black;">],
            City = columns[</span><span style="background:white;color:#a31515;">"City"</span><span style="background:white;color:black;">],
            Contact = columns[</span><span style="background:white;color:#a31515;">"Contact"</span><span style="background:white;color:black;">]
        };
    }
}&nbsp; </span></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="code"><span style="background:white;color:green;">// See if the customer already exists
</span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">existingCustomer = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">GetCustomerAsync(customer.Id);
</span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(existingCustomer != </span><span style="background:white;color:blue;">null</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;">custstmt = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:#2b91af;">App</span><span style="background:white;color:black;">.db.PrepareStatementAsync(
        </span><span style="background:white;color:#a31515;">"UPDATE Customer SET Name = ?, City = ?, Contact = ? WHERE Id=?"</span><span style="background:white;color:black;">))
    {
        </span><span style="background:white;color:green;">// NOTE when using anonymous parameters the first has an index of 1, not 0. 
        </span><span style="background:white;color:black;">custstmt.BindTextParameterAt(1, customer.Name);
        custstmt.BindTextParameterAt(2, customer.City);
        custstmt.BindTextParameterAt(3, customer.Contact);
        custstmt.BindIntParameterAt(4, customer.Id);

        </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">custstmt.StepAsync();
    }
}</span></pre>
<h2>Delete</h2>
<p>Delete is simple enough:</p>
<pre class="code"><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">sql = </span><span style="background:white;color:#a31515;">@"DELETE FROM Customer WHERE Id={0}"</span><span style="background:white;color:black;">;
sql = </span><span style="background:white;color:blue;">string</span><span style="background:white;color:black;">.Format(sql, customerId);

</span><span style="background:white;color:green;">// Can use ExecuteStatementAsync to run non row returning statements
</span><span style="background:white;color:blue;">await </span><span style="background:white;color:#2b91af;">App</span><span style="background:white;color:black;">.db.ExecuteStatementAsync(sql);</span></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/53/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=53&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="http://andywigley.files.wordpress.com/2013/06/image_thumb3_thumb1.png" medium="image">
			<media:title type="html">image_thumb3</media:title>
		</media:content>

		<media:content url="http://andywigley.files.wordpress.com/2013/06/image_thumb7_thumb1.png" medium="image">
			<media:title type="html">image_thumb7</media:title>
		</media:content>
	</item>
		<item>
		<title>PhoneGap devs&#8211;bring your app to Windows Phone and win!</title>
		<link>http://andywigley.com/2013/05/21/phonegap-devsbring-your-app-to-windows-phone-and-win/</link>
		<comments>http://andywigley.com/2013/05/21/phonegap-devsbring-your-app-to-windows-phone-and-win/#comments</comments>
		<pubDate>Tue, 21 May 2013 09:07:38 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Competitions]]></category>
		<category><![CDATA[PhoneGap]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=46</guid>
		<description><![CDATA[From now until&#160; June 30th, 2013, we are running a competition aimed at developers who have built PhoneGap apps and published in other stores – for example, Apple iTunes, Google Play, Blackberry World, Bada, Symbian, or Palm OS – to take any of their existing PhoneGap apps and port it to Windows Phone 8, like [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=46&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>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 – for example, Apple iTunes, Google Play, Blackberry World, Bada, Symbian, or Palm OS – 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>.</p>
<p><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></p>
<p>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>Innovative
<li>Easy to use
<li>Engaging and visually appealing to the user</li>
</ul>
<p>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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/46/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=46&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/05/21/phonegap-devsbring-your-app-to-windows-phone-and-win/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="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" medium="image">
			<media:title type="html">clip_image002</media:title>
		</media:content>
	</item>
		<item>
		<title>Live Apps: Creating Custom Tile and Lock Screen Images</title>
		<link>http://andywigley.com/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images/</link>
		<comments>http://andywigley.com/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images/#comments</comments>
		<pubDate>Wed, 10 Apr 2013 15:00:33 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Lock Screen]]></category>
		<category><![CDATA[sample]]></category>
		<category><![CDATA[Tiles]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=45</guid>
		<description><![CDATA[One of the really great ways that apps in Windows Phone can connect with the user is by supporting Live Tiles – tiles that are more than just a quick launcher, but instead get updated with timely, specific information to connect the user with the data that’s important to them. As a developer, you can [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=45&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>One of the really great ways that apps in Windows Phone can connect with the user is by supporting Live Tiles – tiles that are more than just a quick launcher, but instead get updated with timely, specific information to connect the user with the data that’s important to them. </p>
<p>As a developer, you can update Tiles in lots of different ways:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206971(v=vs.105).aspx">From the app</a> while the user is running it
<li>Using <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.105).aspx">Push notifications</a> to send updates through from backend services
<li>Using a <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769548(v=vs.105).aspx">TileSchedule</a>
<li>From a <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx">Background Agent</a> </li>
</ul>
<p>For most purposes, the Tile templates are plenty rich enough for the developer to be able to communicate new information to the user. For example, the Flip Tile template allows you to set all the properties shown here:</p>
<p><img title="Windows Phone Flip Tile template properties" alt="Windows Phone Flip Tile template properties" src="http://i.msdn.microsoft.com/dynimg/IC600902.png"></p>
<p>However, as you can see the areas for text are fairly limited, and sometimes the developer will want to communicate more than is possible using the available properties. The only way to do this is to create a custom image and draw the text (or additional graphics) onto the custom image, then use that to update the tile.</p>
<p>In Windows Phone 8, your app can also be the Lock Screen image provider. Here, all you can supply is the image, so if you wanted to communicate some up to date information, the only way you can do that is to write onto the image. But what a size of image! Plenty of room for writing additional text, icons or custom graphs for example!</p>
<h2>Creating custom images using a User Control</h2>
<p>The easiest way to layout a custom tile or lock screen image is to create a User Control of the required size, just as you would lay out a page. Of course, what you put onto the control is entirely up to you, but as an example, here’s the Xaml for a user control for a standard Wide Tile for the FlipTile template:</p>
<pre class="code"><span style="background:white;color:blue;">&lt;</span><span style="background:white;color:rgb(163,21,21);">UserControl </span><span style="background:white;color:red;">x</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">Class</span><span style="background:white;color:blue;">="RenderImageLibrary.WideTileControl"
    </span><span style="background:white;color:red;">xmlns</span><span style="background:white;color:blue;">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    </span><span style="background:white;color:red;">xmlns</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">x</span><span style="background:white;color:blue;">="http://schemas.microsoft.com/winfx/2006/xaml"
    </span><span style="background:white;color:red;">xmlns</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">d</span><span style="background:white;color:blue;">="http://schemas.microsoft.com/expression/blend/2008"
    </span><span style="background:white;color:red;">xmlns</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">mc</span><span style="background:white;color:blue;">="http://schemas.openxmlformats.org/markup-compatibility/2006"
    </span><span style="background:white;color:red;">mc</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">Ignorable</span><span style="background:white;color:blue;">="d"
    </span><span style="background:white;color:red;">FontFamily</span><span style="background:white;color:blue;">="{</span><span style="background:white;color:rgb(163,21,21);">StaticResource </span><span style="background:white;color:red;">PhoneFontFamilyNormal</span><span style="background:white;color:blue;">}"
    </span><span style="background:white;color:red;">FontSize</span><span style="background:white;color:blue;">="{</span><span style="background:white;color:rgb(163,21,21);">StaticResource </span><span style="background:white;color:red;">PhoneFontSizeNormal</span><span style="background:white;color:blue;">}"
    </span><span style="background:white;color:red;">Foreground</span><span style="background:white;color:blue;">="{</span><span style="background:white;color:rgb(163,21,21);">StaticResource </span><span style="background:white;color:red;">PhoneForegroundBrush</span><span style="background:white;color:blue;">}"
    </span><span style="background:white;color:red;">d</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">DesignHeight</span><span style="background:white;color:blue;">="336" </span><span style="background:white;color:red;">d</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">DesignWidth</span><span style="background:white;color:blue;">="691"&gt;
    
    &lt;</span><span style="background:white;color:rgb(163,21,21);">Grid </span><span style="background:white;color:red;">x</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">Name</span><span style="background:white;color:blue;">="LayoutRoot"&gt;
        &lt;</span><span style="background:white;color:rgb(163,21,21);">Image </span><span style="background:white;color:red;">x</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">Name</span><span style="background:white;color:blue;">="BackgroundImage" </span><span style="background:white;color:red;">Stretch</span><span style="background:white;color:blue;">="UniformToFill" /&gt;
        &lt;</span><span style="background:white;color:rgb(163,21,21);">Rectangle </span><span style="background:white;color:red;">Stroke</span><span style="background:white;color:blue;">="Black"&gt;
            &lt;</span><span style="background:white;color:rgb(163,21,21);">Rectangle.Fill</span><span style="background:white;color:blue;">&gt;
                &lt;</span><span style="background:white;color:rgb(163,21,21);">LinearGradientBrush </span><span style="background:white;color:red;">EndPoint</span><span style="background:white;color:blue;">="0.5,1" </span><span style="background:white;color:red;">StartPoint</span><span style="background:white;color:blue;">="0.5,0"&gt;
                    &lt;</span><span style="background:white;color:rgb(163,21,21);">GradientStop </span><span style="background:white;color:red;">Color</span><span style="background:white;color:blue;">="#99000000" </span><span style="background:white;color:red;">Offset</span><span style="background:white;color:blue;">="0.007"/&gt;
                    &lt;</span><span style="background:white;color:rgb(163,21,21);">GradientStop </span><span style="background:white;color:red;">Color</span><span style="background:white;color:blue;">="#19000000" </span><span style="background:white;color:red;">Offset</span><span style="background:white;color:blue;">="1"/&gt;
                &lt;/</span><span style="background:white;color:rgb(163,21,21);">LinearGradientBrush</span><span style="background:white;color:blue;">&gt;
            &lt;/</span><span style="background:white;color:rgb(163,21,21);">Rectangle.Fill</span><span style="background:white;color:blue;">&gt;
        &lt;/</span><span style="background:white;color:rgb(163,21,21);">Rectangle</span><span style="background:white;color:blue;">&gt;
        &lt;</span><span style="background:white;color:rgb(163,21,21);">TextBlock </span><span style="background:white;color:red;">x</span><span style="background:white;color:blue;">:</span><span style="background:white;color:red;">Name</span><span style="background:white;color:blue;">="TextOverlayTextBox" </span><span style="background:white;color:red;">VerticalAlignment</span><span style="background:white;color:blue;">="Center" <br />                   </span><span style="background:white;color:red;">HorizontalAlignment</span><span style="background:white;color:blue;">="Center" 
                   </span><span style="background:white;color:red;">Text</span><span style="background:white;color:blue;">="Text" </span><span style="background:white;color:red;">Margin</span><span style="background:white;color:blue;">="31,29,31,77" </span><span style="background:white;color:red;">TextWrapping</span><span style="background:white;color:blue;">="Wrap"
                   </span><span style="background:white;color:red;">Style</span><span style="background:white;color:blue;">="{</span><span style="background:white;color:rgb(163,21,21);">StaticResource </span><span style="background:white;color:red;">PhoneTextLargeStyle</span><span style="background:white;color:blue;">}" </span><span style="background:white;color:red;">Foreground</span><span style="background:white;color:blue;">="White"
                   </span><span style="background:white;color:red;">Width</span><span style="background:white;color:blue;">="629" </span><span style="background:white;color:red;">Height</span><span style="background:white;color:blue;">="230" /&gt;
    &lt;/</span><span style="background:white;color:rgb(163,21,21);">Grid</span><span style="background:white;color:blue;">&gt;
&lt;/</span><span style="background:white;color:rgb(163,21,21);">UserControl</span><span style="background:white;color:blue;">&gt;</span></pre>
<p>As you can see, this is layed out in a Grid with an Image element first, and overlaying that is a black filled Rectangle which is semi transparent and overlays the image using a gradient fill. This is there so that the text which forms the top layer – in the TextBlock – and which is drawn in white, is clearly legible, even over a light coloured background image.</p>
<p><a href="http://andywigley.files.wordpress.com/2013/04/image.png"><img title="image" style="background-image:none;display:inline;" border="0" alt="image" src="http://andywigley.files.wordpress.com/2013/04/image_thumb.png?w=654&#038;h=410" width="654" height="410"></a></p>
<p>&nbsp;</p>
<p>In the code for this control, there is a property to set the text overlay. The background image used is included as content in this sample so is not changeable at runtime, but this could easily be changed so that any new image could be plugged into it.</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.Linq;
</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">System.Windows;
</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">System.Windows.Controls;
</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">System.IO.IsolatedStorage;
</span><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">System.Windows.Media.Imaging;

</span><span style="background:white;color:blue;">namespace </span><span style="background:white;color:black;">RenderImageLibrary
{
    </span><span style="background:white;color:blue;">public partial class </span><span style="background:white;color:rgb(43,145,175);">WideTileControl </span><span style="background:white;color:black;">: </span><span style="background:white;color:rgb(43,145,175);">UserControl
    </span><span style="background:white;color:black;">{
        </span><span style="background:white;color:blue;">public </span><span style="background:white;color:black;">WideTileControl(</span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">tileText)
        {
            InitializeComponent();

            Text = tileText;
        }

        </span><span style="background:white;color:blue;">public string </span><span style="background:white;color:black;">Text { </span><span style="background:white;color:blue;">get</span><span style="background:white;color:black;">; </span><span style="background:white;color:blue;">set</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;">&lt;</span><span style="background:white;color:rgb(43,145,175);">SaveJpegCompleteEventArgs</span><span style="background:white;color:black;">&gt; SaveJpegComplete;

        </span><span style="background:white;color:blue;">public void </span><span style="background:white;color:black;">BeginSaveJpeg()
        {
            </span><span style="background:white;color:green;">// Load the background image directly - important thing is to delay 
            // rendering the image to the WriteableBitmap until the image has
            // finished loading
            </span><span style="background:white;color:rgb(43,145,175);">BitmapImage </span><span style="background:white;color:black;">backgroundImage = <br />                </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">BitmapImage</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);">Uri</span><span style="background:white;color:black;">(</span><span style="background:white;color:rgb(163,21,21);">"DefaultWideTile.jpg"</span><span style="background:white;color:black;">, </span><span style="background:white;color:rgb(43,145,175);">UriKind</span><span style="background:white;color:black;">.Relative));
            backgroundImage.CreateOptions = </span><span style="background:white;color:rgb(43,145,175);">BitmapCreateOptions</span><span style="background:white;color:black;">.None;

            backgroundImage.ImageOpened += (s, args) =&gt;
                {
                    </span><span style="background:white;color:blue;">try
                    </span><span style="background:white;color:black;">{
                        </span><span style="background:white;color:green;">// Set the loaded image
                        </span><span style="background:white;color:black;">BackgroundImage.Source = backgroundImage;

                        </span><span style="background:white;color:green;">// Set the text
                        </span><span style="background:white;color:black;">TextOverlayTextBox.Text = </span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">.Text;

                        </span><span style="background:white;color:green;">// Explicitly size the control - for use in a background agent
                        </span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">.UpdateLayout();
                        </span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">.Measure(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">Size</span><span style="background:white;color:black;">(691, 336));
                        </span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">.UpdateLayout();
                        </span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">.Arrange(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">Rect</span><span style="background:white;color:black;">(0, 0, 691, 336));

                        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">wb = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">WriteableBitmap</span><span style="background:white;color:black;">(691, 336);
                        wb.Render(LayoutRoot, </span><span style="background:white;color:blue;">null</span><span style="background:white;color:black;">);
                        wb.Invalidate();

                        </span><span style="background:white;color:green;">// Create a filename for JPEG file in isolated storage
                        // Tile images *must* be in shared/shellcontent.
                        </span><span style="background:white;color:rgb(43,145,175);">String </span><span style="background:white;color:black;">fileName = </span><span style="background:white;color:rgb(163,21,21);">"Tile_" </span><span style="background:white;color:black;">+ </span><span style="background:white;color:rgb(43,145,175);">Guid</span><span style="background:white;color:black;">.NewGuid().ToString() + </span><span style="background:white;color:rgb(163,21,21);">".jpg"</span><span style="background:white;color:black;">;

                        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">myStore = </span><span style="background:white;color:rgb(43,145,175);">IsolatedStorageFile</span><span style="background:white;color:black;">.GetUserStoreForApplication();
                        </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(!myStore.DirectoryExists(</span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent"</span><span style="background:white;color:black;">))
                        {
                            myStore.CreateDirectory(</span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent"</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:rgb(43,145,175);">IsolatedStorageFileStream </span><span style="background:white;color:black;">myFileStream = <br />                            myStore.CreateFile(</span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent/" </span><span style="background:white;color:black;">+ fileName))
                        {
                            </span><span style="background:white;color:green;">// Encode WriteableBitmap object to a JPEG stream.
                            </span><span style="background:white;color:black;">wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 75);
                            myFileStream.Close();
                        }

                        </span><span style="background:white;color:green;">// Delete images from earlier execution
                        </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">filesTodelete = <br />                             </span><span style="background:white;color:blue;">from </span><span style="background:white;color:black;">f </span><span style="background:white;color:blue;">in </span><span style="background:white;color:black;">myStore.GetFileNames(</span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent/Tile_*"</span><span style="background:white;color:black;">)<br />                                .AsQueryable()
                             </span><span style="background:white;color:blue;">where </span><span style="background:white;color:black;">!f.EndsWith(fileName)
                             </span><span style="background:white;color:blue;">select </span><span style="background:white;color:black;">f;
                        </span><span style="background:white;color:blue;">foreach </span><span style="background:white;color:black;">(</span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">file </span><span style="background:white;color:blue;">in </span><span style="background:white;color:black;">filesTodelete)
                        {
                            myStore.DeleteFile(</span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent/" </span><span style="background:white;color:black;">+ file);
                        }

                        </span><span style="background:white;color:green;">// Fire completion event
                        </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(SaveJpegComplete != </span><span style="background:white;color:blue;">null</span><span style="background:white;color:black;">)
                        {
                            SaveJpegComplete(</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);">SaveJpegCompleteEventArgs</span><span style="background:white;color:black;">(</span><span style="background:white;color:blue;">true</span><span style="background:white;color:black;">, <br />                                                           </span><span style="background:white;color:rgb(163,21,21);">"shared/shellcontent/" </span><span style="background:white;color:black;">+ fileName));
                        }
                    }
                    </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);">Exception </span><span style="background:white;color:black;">ex)
                    {
                        </span><span style="background:white;color:green;">// Log it
                        </span><span style="background:white;color:black;">System.Diagnostics.</span><span style="background:white;color:rgb(43,145,175);">Debug</span><span style="background:white;color:black;">.WriteLine(<br />                                </span><span style="background:white;color:rgb(163,21,21);">"Exception in SaveJpeg: " </span><span style="background:white;color:black;">+ ex.ToString());

                        </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(SaveJpegComplete != </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;">args1 = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">SaveJpegCompleteEventArgs</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:rgb(163,21,21);">""</span><span style="background:white;color:black;">);
                            args1.Exception = ex;
                            SaveJpegComplete(</span><span style="background:white;color:blue;">this</span><span style="background:white;color:black;">, args1);
                        }
                    }
                };

            </span><span style="background:white;color:blue;">return</span><span style="background:white;color:black;">;
        }
    }
}
</span>&nbsp;</pre>
<p><span style="background:white;color:black;"><font color="#333333"></font></span>&nbsp;</p>
<p><span style="background:white;color:black;">The most important part of this code is the <strong>BeginSaveJpeg</strong> method which ensures the control is sized and layed out correctly, renders the control onto a <strong>WriteableBitmap</strong> which is used to write out the image to a jpg, and then fires the <strong>SaveJpegComplete</strong> event to inform callers that the work is done. Note that as this is a tile image, the method writes it to the <strong>/shared/ShellContent</strong> folder which is required for images used for tile updates.</span></p>
<p><span style="background:white;color:black;">We can now make use of this in – for example – a background agent. Here’s the code from the attached sample that creates a custom image in a background agent:</span></p>
<pre class="code"><span style="background:white;color:blue;">namespace </span><span style="background:white;color:black;">BackgroundUpdate
{
    </span><span style="background:white;color:blue;">public class </span><span style="background:white;color:rgb(43,145,175);">ScheduledAgent </span><span style="background:white;color:black;">: </span><span style="background:white;color:rgb(43,145,175);">ScheduledTaskAgent
    </span><span style="background:white;color:black;">{
        </span><span style="background:white;color:gray;">...</span></pre>
<pre class="code"><span style="background:white;color:gray;"></span><span style="background:white;color:black;">
        </span><span style="background:white;color:gray;">/// &lt;summary&gt;
        /// </span><span style="background:white;color:green;">Agent that runs a scheduled task
        </span><span style="background:white;color:gray;">/// &lt;/summary&gt;
        /// &lt;param name="task"&gt;
        /// </span><span style="background:white;color:green;">The invoked task
        </span><span style="background:white;color:gray;">/// &lt;/param&gt;
        /// &lt;remarks&gt;
        /// </span><span style="background:white;color:green;">This method is called when a periodic or resource intensive task is invoked
        </span><span style="background:white;color:gray;">/// &lt;/remarks&gt;
        </span><span style="background:white;color:blue;">protected override void </span><span style="background:white;color:black;">OnInvoke(</span><span style="background:white;color:rgb(43,145,175);">ScheduledTask </span><span style="background:white;color:black;">task)
        {
            </span><span style="background:white;color:green;">// Render a new image for the lock screen
            </span><span style="background:white;color:black;">System.Threading.</span><span style="background:white;color:rgb(43,145,175);">ManualResetEvent </span><span style="background:white;color:black;">mre = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:black;">System.Threading.</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:rgb(43,145,175);">Deployment</span><span style="background:white;color:black;">.Current.Dispatcher.BeginInvoke(() =&gt;
            {
                </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(</span><span style="background:white;color:rgb(43,145,175);">LockScreenManager</span><span style="background:white;color:black;">.IsProvidedByCurrentApplication)
                {
                    </span><span style="background:white;color:rgb(43,145,175);">LockScreenImageControl </span><span style="background:white;color:black;">cont = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">LockScreenImageControl</span><span style="background:white;color:black;">();
                    cont.SaveJpegComplete += (s, args) =&gt;
                        {
                            </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(args.Success)
                            {
                                </span><span style="background:white;color:green;">// Set the lock screen image URI - App URI syntax is required!  <br />                                </span><span style="background:white;color:rgb(43,145,175);">Uri </span><span style="background:white;color:black;">lockScreenImageUri = </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);">"ms-appdata:///Local/" <br />                                                        </span><span style="background:white;color:black;">+ args.ImageFileName, </span><span style="background:white;color:rgb(43,145,175);">UriKind</span><span style="background:white;color:black;">.Absolute);
                                </span><span style="background:white;color:rgb(43,145,175);">Debug</span><span style="background:white;color:black;">.WriteLine(lockScreenImageUri.ToString());
<br />                                </span><span style="background:white;color:rgb(43,145,175);">LockScreen</span><span style="background:white;color:black;">.SetImageUri(lockScreenImageUri);
                            }
                            mre.Set(); 
                        };
                    cont.BeginSaveJpeg();
                }
            });

            </span><span style="background:white;color:green;">// Wait for Lock Screen image to complete
            </span><span style="background:white;color:black;">mre.WaitOne();
            </span><span style="background:white;color:green;">// Then reset for the Tile Image operation
            </span><span style="background:white;color:black;">mre.Reset();

            </span><span style="background:white;color:rgb(43,145,175);">Deployment</span><span style="background:white;color:black;">.Current.Dispatcher.BeginInvoke(() =&gt;
            {
                </span><span style="background:white;color:green;">// Render the new tile image
                </span><span style="background:white;color:black;">RenderImageLibrary.</span><span style="background:white;color:rgb(43,145,175);">WideTileControl </span><span style="background:white;color:black;">wtc = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:black;">RenderImageLibrary.</span><span style="background:white;color:rgb(43,145,175);">WideTileControl</span><span style="background:white;color:black;">(
                    </span><span style="background:white;color:rgb(163,21,21);">"This text is written onto the image - allows you to specify more text than " 
      </span><span style="background:white;color:black;">+ </span><span style="background:white;color:rgb(163,21,21);">"you can fit onto a standard tile using the available properties in the tile templates"</span><span style="background:white;color:black;">);

                wtc.SaveJpegComplete += </span><span style="background:white;color:blue;">async </span><span style="background:white;color:black;">(s, args) =&gt;
                {
                    </span><span style="background:white;color:blue;">try
                    </span><span style="background:white;color:black;">{
                        </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(args.Success)
                        {
                            </span><span style="background:white;color:green;">// Set the tile image URI - "isostore:/" is important! <br />                            // Note that the control already
                            // puts the image into /Shared/ShellContent which is where tile <br />                            // images in the local folder must be
                            </span><span style="background:white;color:rgb(43,145,175);">Uri </span><span style="background:white;color:black;">tileImageUri = </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);">"isostore:/" <br />                                              </span><span style="background:white;color:black;">+ args.ImageFileName, </span><span style="background:white;color:rgb(43,145,175);">UriKind</span><span style="background:white;color:black;">.RelativeOrAbsolute);
                            </span><span style="background:white;color:rgb(43,145,175);">Debug</span><span style="background:white;color:black;">.WriteLine(tileImageUri.ToString());
                            
</span><span style="background:white;color:black;"><br />
                            </span><span style="background:white;color:green;">// Set the tile image
                            </span><span style="background:white;color:rgb(43,145,175);">FlipTileData </span><span style="background:white;color:black;">ftd = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">FlipTileData</span><span style="background:white;color:black;">();
                            ftd.WideBackgroundImage = tileImageUri;
                            ftd.Title = </span><span style="background:white;color:rgb(163,21,21);">"Set by BG agent"</span><span style="background:white;color:black;">;

                            </span><span style="background:white;color:rgb(43,145,175);">ShellTile</span><span style="background:white;color:black;">.ActiveTiles.First().Update(ftd);
                        }
                        </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);">Debug</span><span style="background:white;color:black;">.WriteLine(args.Exception.ToString());
                        }
                    }
                    </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);">Exception </span><span style="background:white;color:black;">ex)
                    {
                        </span><span style="background:white;color:rgb(43,145,175);">Debug</span><span style="background:white;color:black;">.WriteLine(ex.ToString());
                    }
                    </span><span style="background:white;color:blue;">finally
                    </span><span style="background:white;color:black;">{
                        mre.Set();
                    }
                };

                wtc.BeginSaveJpeg();
            }
    );
            </span><span style="background:white;color:green;">// Wait for tile operation to complete
            </span><span style="background:white;color:black;">mre.WaitOne();

            NotifyComplete();

        }
    }
}</span></pre>
<p>The result is a pretty custom tile image which you can see after you tap and hold on the sample app where it is listed in the Programs list, and then tap ‘Pin to Start’:</p>
<p><a href="http://andywigley.files.wordpress.com/2013/04/wp_ss_20130328_0001.png"><img title="wp_ss_20130328_0001" style="background-image:none;display:inline;" border="0" alt="wp_ss_20130328_0001" src="http://andywigley.files.wordpress.com/2013/04/wp_ss_20130328_0001_thumb.png?w=223&#038;h=369" width="223" height="369"></a></p>
<p>&nbsp;</p>
<p>The sample code gives examples for both a custom tile and a custom Lock Screen Image. If you study the code, you can see that the Windows Phone APIs show a shocking disregard (!) for consistency over how the URI of the image must be supplied. For the LockScreen API, the image can be anywhere in local storage, but you must use an ‘Application URI’ format, for example:</p>
<p><font face="Consolas"><span style="background:white;color:rgb(43,145,175);">Uri </span><span style="background:white;color:black;">lockScreenImageUri = </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);">&#8220;ms-appdata:///Local/myNewLockScreenImage.jpg&#8221; </span><span style="background:white;color:black;"></span><span style="background:white;color:rgb(43,145,175);">UriKind</span><span style="background:white;color:black;">.Absolute); <br /></span></font><font face="Consolas"><span style="background:white;color:rgb(43,145,175);">LockScreen</span></font><span style="background:white;color:black;"><font face="Consolas">.SetImageUri(lockScreenImageUri);</font> </span></p>
<p>The ShellTile API is different. Its images must be in /Shared/ShellContent or a subfolder of it, and the URI must be specified as an absolute URI, using the isostore: protocol:</p>
<p><span style="background:white;color:green;"></span><font face="Consolas"><span style="background:white;color:rgb(43,145,175);">Uri </span><span style="background:white;color:black;">tileImageUri = </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);">&#8220;isostore:/Shared/ShellContent/myNewTileImage.jpg&#8221; </span><span style="background:white;color:black;">, </span><span style="background:white;color:rgb(43,145,175);">UriKind</span></font><span style="background:white;color:black;"><font face="Consolas">.RelativeOrAbsolute);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br /></font></span><font face="Consolas"><span style="background:white;color:green;">// Set the tile image <br /></span><span style="background:white;color:rgb(43,145,175);">FlipTileData </span><span style="background:white;color:black;">ftd = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:rgb(43,145,175);">FlipTileData</span></font><span style="background:white;color:black;"><font face="Consolas">(); <br />ftd.WideBackgroundImage = tileImageUri; <br /><span style="background:white;color:rgb(43,145,175);">ShellTile</span><span style="background:white;color:black;">.ActiveTiles.First().Update(ftd);</span></font></span> </p>
<p>That minor grumble apart, the results are great!</p>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:e4e6069b-cb0a-4425-9e09-ed4e15849b79" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<p>Download the <a href="http://andywigley.files.wordpress.com/2013/04/lockscreenandtileimagedynamiccreation.zip" target="_blank">sample solution here</a></p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=45&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="http://i.msdn.microsoft.com/dynimg/IC600902.png" medium="image">
			<media:title type="html">Windows Phone Flip Tile template properties</media:title>
		</media:content>

		<media:content url="http://andywigley.files.wordpress.com/2013/04/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://andywigley.files.wordpress.com/2013/04/wp_ss_20130328_0001_thumb.png" medium="image">
			<media:title type="html">wp_ss_20130328_0001</media:title>
		</media:content>
	</item>
		<item>
		<title>Async and Await for HTTP Networking, Part 2&#8211;HttpClient</title>
		<link>http://andywigley.com/2013/03/12/async-and-await-for-http-networking-part-2httpclient/</link>
		<comments>http://andywigley.com/2013/03/12/async-and-await-for-http-networking-part-2httpclient/#comments</comments>
		<pubDate>Tue, 12 Mar 2013 10:13:12 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=39</guid>
		<description><![CDATA[In my previous post on this topic, Async and Await for Http Networking on Windows Phone, I described how you can use extension methods to create awaitable methods on the WebClient and HttpWebRequest APIs. Courtesy of Microsoft’s .NET Framework team, there have been more developments in this area – the creation of a portable implementation [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=39&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In my previous post on this topic, <a title="Async and Await for Http Networking on Windows Phone" href="http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx">Async and Await for Http Networking on Windows Phone</a>, I described how you can use extension methods to create awaitable methods on the WebClient and HttpWebRequest APIs. Courtesy of Microsoft’s .NET Framework team, there have been more developments in this area – the creation of a portable implementation of the <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(VS.110).aspx">HttpClient API</a>, until now available only for Windows 8 Store and .NET Framework 4.5 apps. This API will allow developers to consume HttpClient on Windows Phone 7.5 and higher, Windows Store apps, and .NET Framework 4.0 and higher.</p>
<h1>Portable HttpClient for .NET Framework and Windows Phone</h1>
<p>As they describe on their blog post here, the .NET Framework team have released a Beta release of the <a href="https://nuget.org/packages/Microsoft.Net.Http">portable version of HttpClient</a>, the modern networking API. The HttpClient library is a set of APIs for .NET which provide a flexible and extensible way to access all things exposed through HTTP. HttpClient exposes the new Task based asynchronous methods, which makes writing responsive and performant UI applications across all platforms a lot simpler.</p>
<p>This is particularly significant for anyone developing apps for both Windows Phone and Windows 8 as it allows you to standardise your networking code around HttpClient.&nbsp; In addition it also enables other portable library developers who require networking support to use HttpClient while targeting all or a subset of the supported platforms.
<p>To use it, first make sure you have got NuGet v2.1 or later installed (Go to Tools – Extensions and Updates). Then to use the HttpClient package, right click on your solution, go to the Manage Nuget Packages dialog, search for Id Microsoft.Net.Http, and make sure “Include Prerelease” is turned on.</p>
<p><a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/8015.HttpClient_5F00_1.png"><img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/8015.HttpClient_5F00_1.png"></a>
<p>Now you can go ahead and program against the HttpClient API. For example, here’s the code to access the OData feed for the Northwind sample feed at Odata.org:</p>
<pre class="code"><span style="background:white;color:#2b91af;">HttpClient </span><span style="background:white;color:black;">httpClient = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">HttpClient</span><span style="background:white;color:black;">();    
</span><span style="background:white;color:black;">httpClient.DefaultRequestHeaders.Add(</span><span style="background:white;color:#a31515;">"Accept"</span><span style="background:white;color:black;">, </span><span style="background:white;color:#a31515;">"application/json;odata=verbose"</span><span style="background:white;color:black;">);
</span><span style="background:white;color:#2b91af;">HttpResponseMessage </span><span style="background:white;color:black;">response = </span><span style="background:white;color:blue;">null</span><span style="background:white;color:black;">;
</span><span style="background:white;color:blue;">try
</span><span style="background:white;color:black;">{            
    response = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">httpClient.GetAsync(
        </span><span style="background:white;color:#a31515;">"http://services.odata.org/Northwind/Northwind.svc/Suppliers"</span><span style="background:white;color:black;">);

    response.EnsureSuccessStatusCode(); </span><span style="background:white;color:green;">// Throws exception if bad HTTP status code
    </span><span style="background:white;color:#2b91af;">Debug</span><span style="background:white;color:black;">.WriteLine(response.StatusCode + </span><span style="background:white;color:#a31515;">" " </span><span style="background:white;color:black;">+ response.ReasonPhrase);

    </span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">responseBodyAsText = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">response.Content.ReadAsStringAsync();
    </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">feed = Newtonsoft.Json.</span><span style="background:white;color:#2b91af;">JsonConvert</span><span style="background:white;color:black;">.DeserializeObject&lt;</span><span style="background:white;color:#2b91af;">SupplierODataFeed</span><span style="background:white;color:black;">&gt;(responseBodyAsText);

    </span><span style="background:white;color:#2b91af;">MessageBox</span><span style="background:white;color:black;">.Show(</span><span style="background:white;color:#a31515;">"Received payload of " </span><span style="background:white;color:black;">+ responseBodyAsText.Length + </span><span style="background:white;color:#a31515;">" characters"</span><span style="background:white;color:black;">);

    SuppliersList.ItemsSource = feed.d.results;
}
</span><span style="background:white;color:blue;">catch </span><span style="background:white;color:black;">(</span><span style="background:white;color:#2b91af;">HttpRequestException </span><span style="background:white;color:black;">hre)
{
    </span><span style="background:white;color:#2b91af;">MessageBox</span><span style="background:white;color:black;">.Show(</span><span style="background:white;color:#a31515;">"RespCallback Exception raised! Message:{0}" </span><span style="background:white;color:black;">+ hre.Message);
}</span></pre>
<h1>Using Compression with the Portable HttpClient </h1>
<p>Anyone who knows me or has seen the Networking JumpStart video, will know that I am running a bit of&nbsp; a crusade against the non-application of compression. Too many devs forget the simple fact that mobile apps on cellular networks (that’s not just Phone people – same for Windows 8 machines that have integrated cellular networking!) often find themselves trying to communicate over poor quality networks. Stack the cards in your favour, increase the chance of success and USE COMPRESSION!</p>
<p>Fortunately, many other people share my views on this. The excellent people at AdvancedREI have created the <strong>HttpClient.Compression</strong> NuGet package, based on <a href="https://gist.github.com/dotMorten/4981198">original work</a> by the super-excellent Morten Nielsen.</p>
<p>This is also a pre-release NuGet package. After you install that package, all you do is new up an instance of the CompressedHttpClientHandler and pass that into the constructor of HttpClient:</p>
<pre class="code"><span style="background:white;color:green;">// Requires HttpClient.Compression NuGet package
</span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">handler = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:black;">AdvancedREI.Net.Http.Compression.</span><span style="background:white;color:#2b91af;">CompressedHttpClientHandler</span><span style="background:white;color:black;">(); 

</span><span style="background:white;color:#2b91af;">HttpClient </span><span style="background:white;color:black;">httpClient = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">HttpClient</span><span style="background:white;color:black;">(handler); </span></pre>
<p>As long as your server is configured to serve up compressed content, you will receive data compressed over the wire and the handler will take care of decompression on receipt.</p>
<p><div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:4730fdc6-49a0-4452-a65d-7fe1ace69d01" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<p>Download the <a href="http://andywigley.files.wordpress.com/2013/03/demo-httpclient.zip" target="_blank">sample code here</a></p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=39&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/03/12/async-and-await-for-http-networking-part-2httpclient/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/8015.HttpClient_5F00_1.png" medium="image" />
	</item>
		<item>
		<title>UK App Builders: Reward Program *One Day Special* and Bonus Rewards</title>
		<link>http://andywigley.com/2013/03/05/uk-app-builders-reward-program-one-day-special-and-bonus-rewards/</link>
		<comments>http://andywigley.com/2013/03/05/uk-app-builders-reward-program-one-day-special-and-bonus-rewards/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 15:39:34 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Competitions]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=37</guid>
		<description><![CDATA[Show us that you’re a game changer and collect points every step of the way to redeem rewards like a brand new Windows 8 RT Slate. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone App. Get recognised and rewarded for building your original apps. Further, get bonus [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=37&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Show us that you’re a game changer and collect points every step of the way to redeem rewards like a brand new Windows 8 RT Slate. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone App.
<p>Get recognised and rewarded for building your original apps. Further, get bonus rewards for migrating your Windows Phone app to Windows Store and vice versa or incorporating one or more Windows Azure Services.
<p>Follow these 4 Simple Steps to Start Earning Points for your Awesome Apps:
<p>1. Register yourself on the <u><a href="http://www.appbuilder-rewards.co.uk/">UK App Builder Reward Programme website</a>.</u>
<p>2. Build &amp; publish your original &amp; unique app.
<p>3. Claim points by telling us about the app you’ve published and we’ll award points to you accordingly.
<p>4. Redeem your points for a range of fantastic prizes and gadgets.
<p><b>Introducing Our First Ever One Day Special</b><b> </b>
<p>On <b>Tuesday 19 March 2013</b>, we will be announcing a special one day deal for the Rewards Programme. To make sure you can take advantage of this special one day deal, publish your apps and ensure you claim your points before <b>Thursday 14 March 2013</b> (less than 2 weeks away) so you will have your all of your eligible points in your account to use. <b>You do not want to miss this one day special!</b> Look out for the announcement for the One Day Special on Tuesday 19 March.
<p><b><i></i></b>
<p><b>Don’t forget about our Bonus Rewards</b><b> </b>
<p>The <a href="http://www.appbuilder-rewards.co.uk/rewards">bonus rewards</a> are limited deals where you must fulfil the stated criteria. Once you have fulfilled the criteria, you will be notified by our team and delivery of your bonus reward will be arranged. The bonus reward is exactly that and it will not affect the balance of your points therefore, you will still be able to use your points to claim for your reward(s) of your choice. Nokia have generously sponsored the first set of bonus rewards. You have to be quick to take advantage of this special bonus reward.
<p>Bonus Reward 1: Receive a <b>Nokia Lumia 620 Windows Phone 8 Handset </b>if you are one of the first 20 App Builders who accumulate <b>100 points</b> from Windows Phone Apps published.
<p>Bonus Reward 2: Receive a <b>Nokia Lumia 920 Windows Phone 8 Developer Handset</b> if you are one of the first 10 App Builders who accumulate <b>200 points</b> for publishing Windows Phone apps. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=37&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/03/05/uk-app-builders-reward-program-one-day-special-and-bonus-rewards/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>
	</item>
		<item>
		<title>UK Windows App Builder Reward Programme</title>
		<link>http://andywigley.com/2013/02/19/uk-windows-app-builder-reward-programme/</link>
		<comments>http://andywigley.com/2013/02/19/uk-windows-app-builder-reward-programme/#comments</comments>
		<pubDate>Tue, 19 Feb 2013 09:29:15 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Competitions]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[windows phone]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=36</guid>
		<description><![CDATA[www.appbuilder-rewards.co.uk Show us that you’re a game changer and collect points every step of the way of your app building journey to redeem rewards like a brand new Lenovo Tablet 2. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone app – and get recognised and rewarded for [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=36&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.appbuilder-rewards.co.uk">www.appbuilder-rewards.co.uk</a>
<p>Show us that you’re a game changer and collect points every step of the way of your app building journey to redeem rewards like a brand new Lenovo Tablet 2. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone app – and get recognised and rewarded for your hard work. Further, get bonus rewards for migrating your Windows Phone app to Windows Store and vice versa or incorporating one or more Windows Azure Services.
<p><b>4 Simple Steps to Start Earning Points for your Awesome Apps </b>
<p>1. Register yourself on the <a href="http://www.appbuilder-rewards.co.uk/">UK App Builder Reward Programme website</a>.
<p>2. Build &amp; publish your original &amp; unique app.
<p>3. Claim points by telling us about the app you’ve published and we’ll award points to you accordingly.
<p>4. Redeem your points for a range of fantastic prizes and gadgets.
<p><b></b>
<p>Build &amp; publish an app between Monday 4<sup>th</sup> Feb 2013 and Tuesday 30<sup>th</sup> Apr 2013 to be eligible for points you can redeem for rewards. Here are the different ways you can earn points:</p>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="770">
<p><strong>Points for Apps</strong> </p>
</td>
</tr>
<tr>
<td valign="top" width="517">
<p>Publish a New Windows Store App</p>
</td>
<td valign="top" width="253">
<p>50 Points</p>
</td>
</tr>
<tr>
<td valign="top" width="517">
<p>Publish a New Windows Phone App</p>
</td>
<td valign="top" width="253">
<p>25 Points</p>
</td>
</tr>
</tbody>
</table>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="770">
<p><strong>Bonus Points</strong> </p>
</td>
</tr>
<tr>
<td width="517">
<p>Your Windows Store or Phone App incorporates one or more Windows Azure Services </p>
</td>
<td width="253">
<p>+ 25 Points</p>
</td>
</tr>
<tr>
<td width="517">
<p>Your app Windows Store app is migrated from Windows Phone or Windows Phone app is migrated from Windows Store</p>
</td>
<td width="253">
<p>+25 Points</p>
</td>
</tr>
</tbody>
</table>
<p>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="770">
<p><strong>Example</strong></p>
</td>
</tr>
<tr>
<td valign="top" width="770">
<p>For example, if you have built and publish a Windows Store app which was ported from an existing Windows Phone app and is hosted on Windows Azure, you will be eligible for up to 100 points for that app.
<p>Windows Store App = 50 Points
<p>+ Hosted on Windows Azure = 25 Bonus Points
<p>+ Ported from Windows Phone = 25 Bonus Points
<p>Total = 100 Points</p>
</td>
</tr>
</tbody>
</table>
<p>To recognise your hard work, the more apps you publish, the more points you receive. The more points you get, the more exciting rewards you can claim. Here’s a brief selection:<br />
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="193">
<p>Publish 1 Windows Phone App</p>
</td>
<td valign="top" width="193">
<p>Publish 1 Windows Store App</p>
</td>
<td valign="top" width="193">
<p>Publish 5 Windows Store apps + Windows Azure Services + Migrated from WP </p>
</td>
<td valign="top" width="193">
<p>Publish 10 Windows Store apps + Windows Azure Services + Migrated from WP</p>
</td>
</tr>
<tr>
<td valign="top" width="193">
<p><strong>Get a XBOX360 Wireless Headset </strong></p>
</td>
<td valign="top" width="193">
<p><strong>Get a XBOX360 12 Months Gold Subscription</strong></p>
</td>
<td valign="top" width="193">
<p><strong>Get a Lenovo Tablet 2</strong></p>
</td>
<td valign="top" width="193">
<p><strong>Get a Two Night Deluxe Paris Cuisine Break for 2</strong></p>
</td>
</tr>
</tbody>
</table>
<p>In addition to the fantastic selection of rewards and experiences you can redeem using your points, we’re also offering some bonus rewards to give your journey to publishing great apps that extra boost.<br />
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="385">
<p><strong>For Windows Store Apps Builders </strong></p>
</td>
<td valign="top" width="385">
<p><strong>For Windows Phone Apps Builders</strong></p>
</td>
</tr>
<tr>
<td valign="top" width="385">
<p>Receive <b>one of the latest XBOX360 titles</b> if you are one of the first 50 app builders who accumulate <b>150 points</b> from publishing Windows Store Apps. </p>
</td>
<td valign="top" width="385">
<p>Receive a <b>Nokia Lumia 620 Windows Phone 8 Handset </b>if you are one of the first 20 App Builders who accumulate <b>100 points</b> from Windows Phone Apps published (~windows phone apps)</p>
</td>
</tr>
<tr>
<td valign="top" width="385">
<p>Receive <b>a copy Visual Studio 2012 Professional (with MSDN Subscription)</b> if you are one of the first 5 app builders who accumulate <b>400 points</b> from publishing Windows Store Apps.</p>
</td>
<td valign="top" width="385">
<p>Receive a <b>Nokia Lumia 920 Windows Phone 8 Developer Handset</b> if you are one of the first 10 App Builders who accumulate <b>200 points</b> for publishing Windows Phone apps (~8 Windows Phone apps) </p>
</td>
</tr>
</tbody>
</table>
<p>The UK App Builder Rewards Programme finishes on the 30<sup>th</sup> April so get your thinking caps on and we look forward to rewarding your awesome apps very soon.
<p>UK App Builder Rewards Programme <a href="http://www.appbuilder-rewards.co.uk">www.appbuilder-rewards.co.uk</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=36&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/02/19/uk-windows-app-builder-reward-programme/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>
	</item>
		<item>
		<title>Async and Await for Http Networking on Windows Phone</title>
		<link>http://andywigley.com/2013/02/07/async-and-await-for-http-networking-on-windows-phone/</link>
		<comments>http://andywigley.com/2013/02/07/async-and-await-for-http-networking-on-windows-phone/#comments</comments>
		<pubDate>Thu, 07 Feb 2013 15:14:58 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[await]]></category>
		<category><![CDATA[HttpWebRequest]]></category>
		<category><![CDATA[WebClient]]></category>
		<category><![CDATA[Windows Phone 8]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=35</guid>
		<description><![CDATA[Using async and await for executing long-running operations such as networking calls has many benefits: your code is much cleaner and easier to maintain, the result is automatically marshalled back to the originating thread so you don’t need to use Dispatcher.BeginInvoke to get back to the UI thread, and exception handling is simpler to implement. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=35&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Using <strong>async</strong> and <strong>await</strong> for executing long-running operations such as networking calls has many benefits: your code is much cleaner and easier to maintain, the result is automatically marshalled back to the originating thread so you don’t need to use <font face="Consolas">Dispatcher.BeginInvoke</font> to get back to the UI thread, and exception handling is simpler to implement. Many of the APIs in the Windows Runtime on both Windows 8 and and Windows Phone 8 use this pattern. It’s the future way of programming asynchronous operations.</p>
<p>Unfortunately, the networking APIs in Windows Phone 8 have not been upgraded to support async and await. On Windows 8 Store Apps by contrast, HTTP networking APIs have been completely re-implemented to offer only async and await methods: the <font face="Consolas">WebClient</font> API has been removed and replaced with a more performant API, <font face="Consolas">HttpClient</font>, and <font face="Consolas">HttpWebRequest</font> has been revamped and now only offers Async methods. However, by use of some extension methods, we can enjoy the goodness of async and await with the <font face="Consolas">WebClient</font> and <font face="Consolas">HttpWebRequest</font> APIs on Windows Phone 8. It will work with Windows Phone 7.5/7.8 projects as well, as long as you add a reference to the NuGet Microsoft.bcl.Async package which adds in async and Task support for Windows Phone OS 7.1.</p>
<p>First, let’s look at <strong>HttpWebRequest</strong>. The GetResponseAsync extension method for this allow you to write code that is exactly the same as for Windows 8 – great if you are porting code between the two. Kudos to Mathias Shapiro, colleague at Microsoft, who developed this!</p>
<pre class="code"><span style="background:white;color:blue;">using </span><span style="background:white;color:black;">System.Net;
</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;">WinPhoneExtensions
{
    </span><span style="background:white;color:blue;">public static class </span><span style="background:white;color:#2b91af;">HttpExtensions
    </span><span style="background:white;color:black;">{
        </span><span style="background:white;color:blue;">public static </span><span style="background:white;color:#2b91af;">Task</span><span style="background:white;color:black;">&lt;</span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">&gt; GetResponseAsync(</span><span style="background:white;color:blue;">this </span><span style="background:white;color:#2b91af;">HttpWebRequest </span><span style="background:white;color:black;">request)
        {
            </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">taskComplete = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">TaskCompletionSource</span><span style="background:white;color:black;">&lt;</span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">&gt;();
            request.BeginGetResponse(asyncResponse =&gt;
            {
                </span><span style="background:white;color:blue;">try
                </span><span style="background:white;color:black;">{
                    </span><span style="background:white;color:#2b91af;">HttpWebRequest </span><span style="background:white;color:black;">responseRequest = (</span><span style="background:white;color:#2b91af;">HttpWebRequest</span><span style="background:white;color:black;">)asyncResponse.AsyncState;
                    </span><span style="background:white;color:#2b91af;">HttpWebResponse </span><span style="background:white;color:black;">someResponse = (</span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">)responseRequest.EndGetResponse(asyncResponse);
                    taskComplete.TrySetResult(someResponse);
                }
                </span><span style="background:white;color:blue;">catch </span><span style="background:white;color:black;">(</span><span style="background:white;color:#2b91af;">WebException </span><span style="background:white;color:black;">webExc)
                {
                    </span><span style="background:white;color:#2b91af;">HttpWebResponse </span><span style="background:white;color:black;">failedResponse = (</span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">)webExc.Response;
                    taskComplete.TrySetResult(failedResponse);
                }
            }, request);
            </span><span style="background:white;color:blue;">return </span><span style="background:white;color:black;">taskComplete.Task;
        }
    }

    </span><span style="background:white;color:blue;">public static class </span><span style="background:white;color:#2b91af;">HttpMethod
    </span><span style="background:white;color:black;">{
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Head { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"HEAD"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Post { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"POST"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Put { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"PUT"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Get { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"GET"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Delete { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"DELETE"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Trace { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"TRACE"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Options { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"OPTIONS"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Connect { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"CONNECT"</span><span style="background:white;color:black;">; } }
        </span><span style="background:white;color:blue;">public static string </span><span style="background:white;color:black;">Patch { </span><span style="background:white;color:blue;">get </span><span style="background:white;color:black;">{ </span><span style="background:white;color:blue;">return </span><span style="background:white;color:#a31515;">"PATCH"</span><span style="background:white;color:black;">; } }
    }
}</span></pre>
<p>Using this, your HttpWebRequest calls now look something like this (don’t forget to add a using WinPhoneExtensions; import to the top of your class!):</p>
<pre class="code"><span style="background:white;color:black;">        </span><span style="background:white;color:blue;">private async </span><span style="background:white;color:black;">System.Threading.Tasks.</span><span style="background:white;color:#2b91af;">Task </span><span style="background:white;color:black;">GetSuppliers()
        {
            </span><span style="background:white;color:#2b91af;">HttpWebRequest </span><span style="background:white;color:black;">request = (</span><span style="background:white;color:#2b91af;">HttpWebRequest</span><span style="background:white;color:black;">)</span><span style="background:white;color:#2b91af;">WebRequest</span><span style="background:white;color:black;">.Create(</span><span style="background:white;color:#a31515;">"http://services.odata.org/Northwind/Northwind.svc/Suppliers"</span><span style="background:white;color:black;">);
            request.Method = </span><span style="background:white;color:#2b91af;">HttpMethod</span><span style="background:white;color:black;">.Get;
            request.Accept = </span><span style="background:white;color:#a31515;">"application/json;odata=verbose"</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:#2b91af;">HttpWebResponse </span><span style="background:white;color:black;">response = (</span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">)</span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">request.GetResponseAsync();

                </span><span style="background:white;color:#2b91af;">Debug</span><span style="background:white;color:black;">.WriteLine(response.ContentType);
                </span><span style="background:white;color:green;">// Read the response into a Stream object.
                </span><span style="background:white;color:black;">System.IO.</span><span style="background:white;color:#2b91af;">Stream </span><span style="background:white;color:black;">responseStream = response.GetResponseStream();
                </span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">data;
                </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;">reader = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:black;">System.IO.</span><span style="background:white;color:#2b91af;">StreamReader</span><span style="background:white;color:black;">(responseStream))
                {
                    data = reader.ReadToEnd();
                }
                responseStream.Close();

                </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">feed = Newtonsoft.Json.</span><span style="background:white;color:#2b91af;">JsonConvert</span><span style="background:white;color:black;">.DeserializeObject&lt;</span><span style="background:white;color:#2b91af;">SupplierODataFeed</span><span style="background:white;color:black;">&gt;(data);
                SuppliersList.ItemsSource = feed.d.results;
            }
            </span><span style="background:white;color:blue;">catch </span><span style="background:white;color:black;">(</span><span style="background:white;color:#2b91af;">Exception </span><span style="background:white;color:black;">ex)
            {
                </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">we = ex.InnerException </span><span style="background:white;color:blue;">as </span><span style="background:white;color:#2b91af;">WebException</span><span style="background:white;color:black;">;
                </span><span style="background:white;color:blue;">if </span><span style="background:white;color:black;">(we != </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;">resp = we.Response </span><span style="background:white;color:blue;">as </span><span style="background:white;color:#2b91af;">HttpWebResponse</span><span style="background:white;color:black;">;
                    </span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">code = resp.StatusCode;
                    </span><span style="background:white;color:#2b91af;">MessageBox</span><span style="background:white;color:black;">.Show(</span><span style="background:white;color:#a31515;">"RespCallback Exception raised! Message:{0}" </span><span style="background:white;color:black;">+ we.Message);
                    </span><span style="background:white;color:#2b91af;">Debug</span><span style="background:white;color:black;">.WriteLine(</span><span style="background:white;color:#a31515;">"Status:{0}"</span><span style="background:white;color:black;">, we.Status);
                }
                </span><span style="background:white;color:blue;">else
                    throw</span><span style="background:white;color:black;">;
            }
        }</span></pre>
<p>…which is exactly the same as you would use in a Windows 8 store app.</p>
<p>We can do a similar thing for WebClient, though here the benefits are simply that the code you end up writing becomes so much cleaner. You don’t get the benefit of compatibility with Windows 8 since WebClient is not available on that platform.</p>
<p>I won’t list the code of the extension methods here, as it’s a bit lengthier than for HttpWebClient. Please download the samples attached to this post to get the extension methods code. When using the extension methods, you end up with lovely clean code like this:</p>
<pre class="code"><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">url = </span><span style="background:white;color:#a31515;">"https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&amp;include_rts=true&amp;screen_name="
    </span><span style="background:white;color:black;">+ nameTextBox.Text + </span><span style="background:white;color:#a31515;">"&amp;count=10"</span><span style="background:white;color:black;">;

</span><span style="background:white;color:blue;">var </span><span style="background:white;color:black;">client = </span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">WebClient</span><span style="background:white;color:black;">();
</span><span style="background:white;color:blue;">string </span><span style="background:white;color:black;">response = </span><span style="background:white;color:blue;">await </span><span style="background:white;color:black;">client.DownloadStringTaskAsync(</span><span style="background:white;color:blue;">new </span><span style="background:white;color:#2b91af;">Uri</span><span style="background:white;color:black;">(url));</span></pre>
<p>If you would like to watch me explaining this (and much, much more!) on video, check out the Networking video in the JumpStart series at <a href="http://aka.ms/i5qr0z">http<a href="http://aka.ms/i5qr0z">://</a><a href="http://aka.ms/i5qr0z">aka.ms/i5qr0z</a></a>.</p>
<p>Download the accompanying samples for the code!</p>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:e58e1990-2c8e-4a5a-856f-d7e30a5758f9" class="wlWriterEditableSmartContent" style="float:none;margin:0;display:inline;padding:0;">
<p> <a href="http://andywigley.files.wordpress.com/2013/02/async-await-http-on-phone-demos.zip" target="_blank">Async Await on Phone Samples</a></p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=35&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/02/07/async-and-await-for-http-networking-on-windows-phone/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows Phone&#8217;s Next App Star Contest</title>
		<link>http://andywigley.com/2013/01/30/windows-phone-s-next-app-star-contest/</link>
		<comments>http://andywigley.com/2013/01/30/windows-phone-s-next-app-star-contest/#comments</comments>
		<pubDate>Wed, 30 Jan 2013 10:13:29 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Competitions]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=33</guid>
		<description><![CDATA[Microsoft has launched a new contest with a very special top prize – featured placement of the winner’s app in a Windows Phone Primetime TV ad which will be broadcast in the U.S. There are many other prizes such as Nokia Lumia 920 phones and Dev Center subscriptions. Participation is easy and the contest is [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=33&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<blockquote><p>Microsoft has launched a new contest with a very special top prize – featured placement of the winner’s app in a Windows Phone Primetime TV ad which will be broadcast in the U.S. There are many other prizes such as Nokia Lumia 920 phones and Dev Center subscriptions.</p>
<p><a href="http://andywigley.files.wordpress.com/2013/01/image.png"><img title="image" style="background-image:none;margin:0;display:inline;" border="0" alt="image" src="http://andywigley.files.wordpress.com/2013/01/image_thumb.png?w=680&#038;h=204" width="680" height="204"></a></p>
<p>Participation is easy and the contest is open to developers worldwide. Just visit the Windows Phone Dev Centre to opt-in to the contest and then publish a new app by March 5th. All apps submitted will then be judged based on an equal rating of user ratings and app quality, including the implementation of new Windows Phone 8 features, such as the new Tile templates.</p>
<p>This judging will narrow the field to 64 finalists and these will participate in a head-to-head competition, in which public voting will narrow the field to 32, then 16, 8, 4, 2 and finally the Grand Prize Winner. The 64 finalists will win prizes such as Nokia Lumia 920 phones and Dev Center subscriptions.</p>
<p>The last app standing will be announced the ‘Windows Phone Next App Star’ and will be featured in the Primetime TV ad!</p>
<p>So what are you waiting for? <font color="#ff0000"><strong>Visit the Windows Phone Dev Center now and opt-in to the contest, then get your app published by March 5th to submit your entry.</strong></font> <font color="#333333"><strong>Good Luck!</strong></font></p>
<p>For more details, read the <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/01/14/next-app-star-see-your-app-featured-in-a-windows-phone-tv-ad.aspx">original announcement on the Windows Phone Developer Blog</a>.</p>
</blockquote>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/33/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=33&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/01/30/windows-phone-s-next-app-star-contest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="http://andywigley.files.wordpress.com/2013/01/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Recently submitted a great Windows Phone App? Want to go to Mobile World Congress 2013 in Barcelona&#8230;.?</title>
		<link>http://andywigley.com/2013/01/03/recently-submitted-a-great-windows-phone-app-want-to-go-to-mobile-world-congress-2013-in-barcelona/</link>
		<comments>http://andywigley.com/2013/01/03/recently-submitted-a-great-windows-phone-app-want-to-go-to-mobile-world-congress-2013-in-barcelona/#comments</comments>
		<pubDate>Thu, 03 Jan 2013 14:36:02 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Competitions]]></category>
		<category><![CDATA[Lumia]]></category>
		<category><![CDATA[MWC2013]]></category>
		<category><![CDATA[Nokia]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=30</guid>
		<description><![CDATA[And another great Windows Phone competition to get started with 2013! Though I have to admit, I’m a bit late with publicising this one… sorry! Nokia and Windows Phone Geek have teamed up to offer the LUMIA GEEK 8-WEEK CHALLENGE. There’s only ….ahem… less than one week left. But if you have submitted a new [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=30&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>And another great Windows Phone competition to get started with 2013! Though I have to admit, I’m a bit late with publicising this one… sorry!</p>
<p>Nokia and Windows Phone Geek have teamed up to offer the LUMIA GEEK 8-WEEK CHALLENGE. There’s only ….ahem… less than one week left. But if you have submitted a <strong>new</strong> or significantly <strong>updated</strong> app to the Windows Phone Store between 13<sup>th</sup> November 2012 and 8<sup>th</sup> January 2013, then you can enter this great competition.</p>
<p>There are <strong>three</strong> awesome prize categories all with <strong>amazing</strong> <strong>prizes</strong> to be won. They are looking for the best Windows Phone developers to make amazing apps for the new WP8 Nokia Lumia devices. The Top prize wins you goodies such as:</p>
<ul>
<li>Trip for 2 to MWC in Barcelona. Includes: Airfare, Hotel Accommodations, &amp; Event Passes
<li>App Demo @ WIPJam @ MWC
<li>Customized Nokia Lumia Device &amp; Nokia Gear
<li>$300 ad credit on Nokia’s Ad Exchange (NAX)
<li>1 Year Free Subscription to Nokia’s Premium Developer Program (NPDP)</li>
</ul>
<p>Head over to <a title="http://windowsphonegeek.com/lumia-geek-8-week-challenge" href="http://windowsphonegeek.com/lumia-geek-8-week-challenge">http://windowsphonegeek.com/lumia-geek-8-week-challenge</a> for full details.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=30&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/01/03/recently-submitted-a-great-windows-phone-app-want-to-go-to-mobile-world-congress-2013-in-barcelona/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows Phone &#8220;App to the Future&#8221; Design Challenge</title>
		<link>http://andywigley.com/2013/01/03/windows-phone-app-to-the-future-design-challenge/</link>
		<comments>http://andywigley.com/2013/01/03/windows-phone-app-to-the-future-design-challenge/#comments</comments>
		<pubDate>Thu, 03 Jan 2013 12:34:48 +0000</pubDate>
		<dc:creator>andywigley</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">https://andywigley.wordpress.com/?p=29</guid>
		<description><![CDATA[Happy New Year to everyone! We start 2013 with a Windows Phone competition that is being run by Core77, Inc. and Microsoft. Now You Can Change the FutureChallenge ends February 3, 2013 Design an app for Windows Phone that showcases how to create, connect or impress the pants off your future self. Apps are a [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=29&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Happy New Year to everyone! </p>
<p>We start 2013 with a Windows Phone competition that is being run by Core77, Inc. and Microsoft.</p>
<p><a href="http://apptothefuture.core77.com/"><img src="http://apptothefuture.core77.com/wp-content/themes/BASE/images/logo_apptothefuture.png" width="348" height="112"></a><br />
<h4>Now You Can Change the Future<br />Challenge ends February 3, 2013</h4>
<p>Design an app for Windows Phone that showcases how to create, connect or impress the pants off your future self. Apps are a way to take control of your day-to-day life. Today they help you wake up, dress, commute, stay on top of news and reach the important people in your life throughout the day, and at their best they help you do things the way YOU want to do them. But what more could your apps do for you tomorrow?
<p>Why wait to find out? <a href="http://apptothefuture.core77.com/register/">REGISTER NOW</a> to design your own App to the Future! Full details: <a title="http://apptothefuture.core77.com/" href="http://apptothefuture.core77.com/">http://apptothefuture.core77.com/</a>
<p>5 WINNERS WILL RECEIVE:
<p>A Microsoft Surface Tablet<img alt="Surface" src="http://apptothefuture.core77.com/wp-content/themes/BASE/images/prize-surface.png" width="92" height="54">a Windows Phone 8 device&nbsp; <em><img alt="Windows Phone device" src="http://apptothefuture.core77.com/wp-content/themes/BASE/images/prize-windows-phone.png" width="28" height="54">&nbsp;</em>and a one year subscription to the Windows Phone DEV CENTER.
<p><em>App to the Future</em> is an app design competition open to the international design community, challenging entrants to design and mockup conceptual apps for the Windows Phone platform to help with their day-to-day challenges, better connect with their family or friends, or showcase an innovative, new app idea. The goals of Core77 and Microsoft are to showcase and triumph innovative designs through the Core77 Design Network of websites and the Microsoft Windows Phone Store and related websites such as Channel 9. Top winning entrants will be further encouraged to develop and sell their app in the Windows Phone Store utilizing prizes, resources and assistance provided by Core77 and Microsoft.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andywigley.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andywigley.wordpress.com/29/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=andywigley.com&#038;blog=42562858&#038;post=29&#038;subd=andywigley&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://andywigley.com/2013/01/03/windows-phone-app-to-the-future-design-challenge/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/72de8fb96918cdeb16906940316bd81d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andywigley</media:title>
		</media:content>

		<media:content url="http://apptothefuture.core77.com/wp-content/themes/BASE/images/logo_apptothefuture.png" medium="image" />

		<media:content url="http://apptothefuture.core77.com/wp-content/themes/BASE/images/prize-surface.png" medium="image">
			<media:title type="html">Surface</media:title>
		</media:content>

		<media:content url="http://apptothefuture.core77.com/wp-content/themes/BASE/images/prize-windows-phone.png" medium="image">
			<media:title type="html">Windows Phone device</media:title>
		</media:content>
	</item>
	</channel>
</rss>
