« November 2012 | Main | January 2013 »

December 2012

A Happy New Year 2013!

2013 was a year of several Microsoft product releases: Windows 8, Windows Server 8, Office 2013, Windows Phone 8, Visual Studio 2012, SQL Server 2012, Microsoft Surface… What can we expect from the year 2013? Let’s start with a look back to 2012.

A personal look back to 2012

With my workshops, I had a huge demand for WPF workshops (that’s similar to 2011). This year also ASP.NET MVC and HTML5 was in demand – I also had some workshops to develop Windows Store Apps. Parallel Programming was a hot topic in 2012 as well.

With my own Websites, I moved to Windows Azure in 2012. http://www.kantine.at and http://www.cninnovation.com is hosted by Windows Azure Websites. Besides Azure Websites, I’m also using SQL Azure and Blob Storage for these sites.

image

image

My first Windows Store apps are in the store:

Picture Search is used for searching images via Bing Search – and sharing images, as well es doing slide shows:

image

Kantine (only available in Austria) shows menus of the week. The restaurant opens again on 7-January, so the next menus will be shown that day.

image

What can be expected from 2013? Let’s wait for the first blog entry of 2013. 

I wish you all the best in the New Year!

Christian

CN innovation

Picture Search available in the Windows Store

You still need a Christmas present? Picture Search is available in the Windows Store – ready for Christmas Smile

After submitting the app it didn’t take 24 hours until the app was available!

Picture Search is a Windows Store app that uses Bing Search to search for pictures – you just need to enter a Bing id, and you’re ready to go.

Picture Search in the store

image

You can use any term to search for pictures – of course using the Search charms.

With the settings you need to enter the Bing id before searching can start:

 

picturesearch4

Then you can step into search results to see thumbnails of the search:

image

Within a group you can also browse the pictures in large size:

picturesearch6

And open the Web page of the image from the app bar:

picturesearch7

Here you also can see information about the image:

picturesearch8

Of course images can be shared using the charms bar.

Try it out and have fun!

Christian

CN innovation

Windows Store App Picture Search Part 2: Creating a Windows Runtime Component

Picture Search is a Windows Store sample app that is used to search pictures with Bing Search. The first part of this article series showed the implementation of a ASP.NET Web API service that itself called the Bing service. The second part of this series is about creating a Windows Runtime component that makes a request to the Web API service. The article is not only about the invocation of the service, but also the implementation of a Windows Runtime Component.

Deutschsprachige Version des Artikels

Picture Search in the App Store

 

Libraries for Windows Store Apps

For creating libraries for Windows Store apps using C# and XAML different options are available:

  • Class Library (Windows Store Apps)
  • Windows Runtime Component
  • Portable Class Library

The Class Library (Windows Store Apps) is a .NET library as we know it from creating .NET applications. However, here the library is reduced to a .NET subset with classes and methods that are available for Windows Store apps.

With the Add New Project template, The Portable Class Library cannot be found in the category of Windows Store templates. Instead, this template is available in the Windows category. This library is not restricted to use from Windows Store apps, you can use it with Windows desktop apps or Silverlight apps instead. The library can be configured for the available set of technologies (including Xbox 360) to create applications. Accordingly to the configuration only a subset of .NET is available.

The third option is the Windows Runtime Component. Creating such a library, the library can not only be used with .NET applications, but also with other Windows Store app technologies such as JavaScript and C++. However, creating this library with C# and using it from C++ or JavaScript also means that the .NET runtime needs to be loaded

Creating a Windows Runtime Component

Windows Runtime Components can be created with a Visual Studio project template.

image

Only Sealed Types

An important restriction for this type of library is that all public types must be sealed – with the exception of UI components.

PictureInformation represents the data which is received from the service: Title, Url, ThumbnailUrl, and Source. This class is similar to other .NET classes – with the exception that it needs to be sealed. Properties can be offered by Windows Runtime components directly.

public sealed class PictureInformation
{
   public string Title { get; set; }
   public string Url { get; set; }
   public string ThumbnailUrl { get; set; }
   public string Source { get; set; }
}
 

Converting a JSON Array to an Object List

SearchManager is the second class in this assembly. This class is sealed as well.

The GetImagesAsyncInternal method makes a call to the Web service. Similar to the first part of this article series, the HttpClient class is used to make the request. GetStringAsync returns a JSON result from the service.

A JSON string can be parsed by using classes from the namespace Windows.Data.Json. The Windows Runtime offers JSON and XML classes in the namespaces Windows.Data.Json, Windows.Data.Xml.Dom, and Windows.Data.Xml.Xsl.

private async Task<IEnumerable<PictureInformation>> GetImagesAsyncInternal(string searchTerm)
{
   string urlRequest = url + searchTerm;
   var client = new HttpClient();
   string jsonResult = await client.GetStringAsync(urlRequest);

  var results = await Task.Run<IEnumerable<PictureInformation>>(() =>
   {
     var searchItems = new List<PictureInformation>();

    JsonArray result;
     if (JsonArray.TryParse(jsonResult, out result))
     {
         foreach (var jsonItem in result)
         {
             JsonObject jsonObj = jsonItem.GetObject();

            var searchItem = new PictureInformation
             {
                 Title = jsonObj["Title"].GetString(),
                 Url = jsonObj["Url"].GetString(),
                 Source = jsonObj["Source"].GetString(),
                 ThumbnailUrl = jsonObj["ThumbnailUrl"].GetString()
             };
             searchItems.Add(searchItem);
         }
     }
     return searchItems;
   });

  return results;
}

The GetImagesAsyncInternal method uses the C# 5 async and await keywords for calling asynchronous methods. As usual with .NET async code, the method returns a task. The caller of an async mehtod does not block the caller thread. Continuation tasks are used behind the scenes with the await keyword.

If this method would be declared public, a compile run results in the error that the task of the type is not a valid Windows runtime type. Public methods within Windows runtime components can only use Windows runtime compatible types in the signature.

A Task can be converted to a Windows runtime type by using the extension method AsAsyncOperation. AsAsyncOperation is an extension method for the Task type and returns IAsyncOperation. IAsyncOperation is the interface of the Windows runtime (namespace Windows.Foundation) for asynchronous calls, and can be used with C# 5 async and await.

public IAsyncOperation<IEnumerable<PictureInformation>> GetImagesAsync(string searchTerm)
{
   Task<IEnumerable<PictureInformation>> t = GetImagesAsyncInternal(searchTerm);
   return t.AsAsyncOperation();
}

 

Summary

Windows Runtime components are libraries for Windows Store apps and can be used with .NET, JavaScript, and C++. Contrary to other .NET libraries, this library is restricted on using Windows runtime types in the signature. With the help of small utilities, such as extension methods, this is an easy task.

Christian

CN innovation

More about Windows Store apps in my book Professional C# 2012 and .NET 4.5, and my Windows Store App workshops.

This article series:

Part 1 – Web API – Search with Bing

Part 2 – Windows Runtime Components

Part 3 – Layout

Part 4 – Settings

Part 5 – Search

Part 6 – Share

Picture Search Part 1: Searching with Bing

Picture Search is a Windows Store sample app that is used to search pictures with Bing or other services such as Flickr. With this blog you will find an article series that goes through all the different aspects of the application such as defining the user interface to show a grid of pictures, starting the search with the help of the search contract, sharing pictures, and organizing the pictures in the UI with the grid view control using grouping and a collection view source.

The first part of this article series shows the implementation of the server part using the ASP.NET Web API hosted within a Windows Azure Web site. The service offered here will be used from the Windows Store app later on.

Attendees of my Windows 8 Camp at Microsoft or from the Windows 8 Deep Dive at Basta! Austria already know this Windows Store sample app – Picture Search. Please find the source code here!

Creating the service using the ASP.NET Web API

Let’s start with an ASP.NET MVC 4 Web Application.

image

The ASP.NET MVC 4 Web Application offers the Web API Project template.

image

This project type defines a ValuesController type in the Controllers folder. However, this one is not used for the sample app. A new controller named BingSearchController is created for the Picture Search app.

image

The BingSearchController defines the Get method for doing a HTTP GET request passing a search term, and retrieving a list of PictureInformation objects. This controller method makes use of the SearchManager that instantiates the request to the Bing service.

        public async Task<IEnumerable<PictureInformation>> Get(string id)
        {
          SearchManager manager = new SearchManager();
          IEnumerable<PictureInformation> result = await manager.SearchImagesAsync(id);
          return result;
        }

By defining the Get method in the BingSearchController class, the URL to retrieve the returned items is http://<server>/api/bingsearch/<searchTerm>.

For the implementation of the controller, the SearchManager and PictureInformation types are needed. These types are defined next.

The Data Transfer Object

The PictureInformation class is a simple data holder that contains the title, Url, and ThumbnailUrl of the image.

  public class PictureInformation
  {
    public string Title { get; set; }
    public string Url { get; set; }
    public string ThumbnailUrl { get; set; }
    public string Source { get; set; }
  }

Contract for Image Requests

The picture search service can use different picture search providers, e.g. Bing and Flickr. In the book Professional C# 2012 and .NET 4.5 you can find implementations calling both of these services. The sample here just makes use of Bing search.

For creating different implementations, the interface IImageRequest is defined. With this interface, the search provider returns a Url property dependent on the provider that contains the search term. Both of these providers return XML content with the search request. This content is parsed by calling the Parse method of the IImageRequest interface. This returns a collection of PictureInformation objects.

  public interface IImageRequest
  {
    string SearchTerm { get; set; }
    string Url { get; }

    IEnumerable<PictureInformation> Parse(string xml);

    ICredentials Credentials { get; }
  }

Bing Search Request

The class BingRequest is the implementation of the IImageRequest interface to do the search via Bing. For using this class you need to add the application identifier. You can get this identifier by registering with the Bing Search API available at the Windows Azure Marketplace: https://datamarket.azure.com/dataset/bing/search. Up to 5000 transactions per month are free.

The major parts of this class are the Url property that returns the URL link to access the service including the search term, and the Parse method that makes use of LINQ to XML to convert the XML content to an object collection.

  public class BingRequest : IImageRequest
  {
    private const string AppId = "enter your BING app-id here!";

    public BingRequest()
    {
      Count = 50;
      Offset = 0;
    }

    private string searchTerm;
    public string SearchTerm
    {
      get { return searchTerm; }
      set { searchTerm = value; }
    }

    public string Url
    {
      get
      {
        return string.Format("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query=%27{0}%27&$top={1}&$skip={2}&$format=Atom", SearchTerm, Count, Offset);
      }
    }

    public int Count { get; set; }
    public int Offset { get; set; }

    public IEnumerable<PictureInformation> Parse(string xml)
    {
      XElement respXml = XElement.Parse(xml);
      XNamespace d = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");
      XNamespace m = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

      return (from item in respXml.Descendants(m + "properties")
              select new PictureInformation
              {
                Title = new String(item.Element(d + "Title").Value.Cast<char>().Take(50).ToArray()),
                Url = item.Element(d + "MediaUrl").Value,
                ThumbnailUrl = item.Element(d + "Thumbnail").Element(d + "MediaUrl").Value,
                Source = "Bing"
              }).ToList();
    }

    public ICredentials Credentials
    {
      get
      {
        return new NetworkCredential(AppId, AppId);
      }
    }
  }

Making the Call to Bing Search

The SearchManager class that is called from the Web API controller makes an asynchronous GET request to the Bing service. The request is done by the HttpClient class. This class is new with .NET 4.5 and fully based on asynchronous features.

  public class SearchManager
  {
    public async Task<IEnumerable<PictureInformation>> SearchImagesAsync(string searchTerm)
    {
      var request = new BingRequest();
      request.SearchTerm = searchTerm;
      
      var client = new HttpClient(new HttpClientHandler
        {
          Credentials = request.Credentials
        });
      HttpResponseMessage response = await client.GetAsync(request.Url);
      string resp = await response.Content.ReadAsStringAsync();
      IEnumerable<PictureInformation> images = null;
      await Task.Run(() =>
      {
        images = request.Parse(resp);
      });
      return images;
    }
  }

Instead of invoking GetAsync and then ReadAsStringAsync with the returned HttpResponseMessage, the implementation could be simplified by invoking GetStringAsync. I’ve decided for the former version to show more functionality of this class.

Calling the Search Service

With all this in place, the service can be invoked to make picture search requests. This can be a simple test from a Web browser, e.g. calling http://<server>/api/bingsearch/Ferrari. Calling this from IE returns JSON data, e.g. this collection as defined by the PictureInformation class:

[{"Title":"Voici une belle photo de Ferrari de qualité",
   "Url":"http://images-et-photos.com/files/ferrari1.jpg",
   "ThumbnailUrl":"http://ts1.mm.bing.net/th?id=H.4902048858114356&pid=15.1",
   "Source":"Bing"},
  {"Title":"Name: ferrari pictures.jpgViews: 110204Size:337.4",
   "Url":"http://www.whitegadget.com/attachments/pc-wallpapers/75212d1315377041-ferrari-ferrari-pictures.jpg",
   "ThumbnailUrl":"http://ts2.mm.bing.net/th?id=I.4894034425284685&pid=15.1&W=160&H=120",
   "Source":"Bing"},
  {"Title":"Ferrari Enzo Ferrari Photos:",
   "Url":"http://world-viewer.com/data_images/ferrari-enzo-ferrari/ferrari-enzo-ferrari-04.jpg",
   "ThumbnailUrl":"http://ts3.mm.bing.net/th?id=I.4935837306587618&pid=15.1&W=160&H=120",
   "Source":"Bing"},

 

In the next article of this series I’m creating a Windows runtime component to call this Web API service.

More information on the Web API and Windows Store apps can be found in my workshops and in my book Professional C# 2012 and .NET 4.5.

Christian

CN innovation