async Bing for Metro Style Apps

While getting ready to support customers
developing great Windows 8 Metro Style Apps I started creating an App myself.

I chose to write some code that queries Bing Search Service for Images and displays results as
tiles.

I stumbled across some things that I want to share with you.

For details how to code against Bing Search please refer to the docs I will focus only on the steps necessary to
incorporate it in Metro Apps.

1) Download the latest Bing Azure Service Proxy and add the code file to your Metro App Project

2) With only default references the code does not compile you need to add references to the following Lib:

    C:\Program Files (x86)\Microsoft WCF Data Services\5.0\bin\Metro\Microsoft.Data.Services.Client.Metro.dll

3) You can now declare a bing search Service Proxy and create an instance consuming the Service Url and your unique ID:

 BingSearchContainer bs = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));
_bsc.Credentials = new System.Net.NetworkCredential("YOUR_ID”,”YOUR_ID”);

4) Now, in order to run an actual query you need to create query object providing a query string and other options that

are unused in this example:

 var webQ = _bsc.Image(search.Text, null, null, null, null, null);

5) You could now use the query object’s BeginExecute EndExecute Methods to asynchronously receive results using the

well-known Asynch Programming Pattern (APM).

6) But you could also make use of the new new async / await keywords. In order to do this you need to bridge between the

old APM the newer Task Parallel Librariy (TPL) to return a Task object which is required by the async keyword. The TaskFactory

helps you with that:

 Task<int> bytesRead = Task<int>.Factory.FromAsync( stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);

7) I found it handy to use a generic extension method decorating the Bing Query with an await-compatible method that

returns the type you request for such as web results, images etc:

 

 public static class QueryExtensions   
{        
     public static Task<IEnumerable<TResult>> QueryAsync<TResult>(this DataServiceQuery<TResult> query)
     {
            return Task<IEnumerable<TResult>>.Factory.FromAsync(query.BeginExecute, query.EndExecute, null);
     }
} 

8) Even though the implementation might look a little awkward, it’s application doesn’t and smart and simple. I assume

you are familiar with data-binding to Objects in the DefaultViewModel using Xaml:

 DefaultViewModel["Items"] = await webQ.QueryAsync() ;

Hope it helps you easily integrating Bing Search Service into your Metro Apps – Happy coding!

PS: The Demo Project is attached to this post.

App1.zip