Using the Windows Store App WebView Control with CSS

With Windows 8.1 a major update of the WebView control is available. The updates make the control usable with many different scenarios.

In one project I'm using the WebView control to dynamically get HTML content via a string from a Web service, and make use of a CSS style sheet file that is stored with the Windows Store app.

Loading HTML content from a string can now be done by calling the method NavigateToString:

string htmlContent = service.GetHtml();
webView1.NavigateToString(htmlContent);

Referencing the style sheet that is stored with the Windows Store app is done via the ms-appx-web prefix with the link to the style sheet. The WebView control doesn't support ms-appx, but ms-appx-web is possible:

<link href="ms-appx-web:///css/Styles.css" rel="stylesheet" />

Christian

http://www.cninnovation.com


Tiles, Toasts, and Notifications in Windows Store Apps

Samples for my sessions from TechEd North America and TechEd Europe! I hope you enjoyed the session!

This sample shows tiles, toasts, badges, secondary tiles:

Tiles and Toasts Sample

And here are the sample to show different versions for push notifications:

Push Notifications

Christian

Watch this space for more information on developing Windows Store apps with Windows 8 and Windows 8.1!


Associating Windows Store Apps with Websites

How to make a Windows App findable? If there’s already a Website that is known, it is easy to associate this site with the app. Users can find the app easily by opening the Website. A requirement for this is using IE in the new modern mode, and adding two meta elements to the Website.

This article shows what’s needed to associate a Windows Store app with a Website, and what’s the result.

The Website http://www.kantine.at already uses these meta elements. If you open this page with IE 10, you’ll have a direct link to the Kantine App.

Deutschsprachige Version dieses Artikels

For all my friends outside of Austria, the Kantine app currently is only available in the Austrian marketplace. You can use http://www.bing.com for showing these features as well.

KantineWebsite_thumb[1]

Internet Explorer offers buttons to Refresh and Pin the website, Page Tools, and Forward. The Forward button only becomes active if the Back button was clicked before, or with the Flip Ahead feature turned on. The Page Tools allow to switch the browser in the desktop mode, and find content within the page.

NotAssociated_thumb

If the Website is associated with a Windows Store app, the Page Tools button receives an additional plus sign:

Associated_thumb

Clicking this button if the app is not installed yet, a menu is opened with the new entry Get app for this site:

AssociatedOpen_thumb[1]

Clicking this menu entry directly opens the page of the app in the store:

Store_thumb[4]

If the app is already installed, the menu entry is replaced with Switch to Kantine app, and clicking this menu the app is started:

image

All this is possible just by adding two meta elements within the HTML head element: msApplication-ID and msApplication-PackageFamily:

<meta name="msApplication-ID" content="App" />
<meta name="msApplication-PackageFamilyName" content="CNelements.Kantine_x1ms6s50zdxze" />

You can get the values for these elements directly from the package manifest of the application. msApplication-ID is the ID of the application that is found using the XML editor. The Application element is child element of the Applications element. Get the value of the Id attribute. The value for msApplication-PackageFamilyName can be read using the manifest editor, Packaging Tab:

VStudio_thumb[1]

Summary

Just by using two meta elements it’s becoming easier to find your Windows Store app. Maybe it will take some time before users find this AppBar button in IE. As soon as the user finds this information, it works the same with all the associated Web sites. In any case, it just takes two meta elements for this feature.

Christian

CN innovation

More information about this feature in the IE Blog: http://blogs.msdn.com/b/ie/archive/2011/10/20/connect-your-web-site-to-your-windows-8-app.aspx

More info's to Windows Store apps in my workshops and in the book Professional C# and .NET 4.5.


Buying Apps in the Windows Store with Family Safety

You can find many free kids games in the Windows Store. However, more interesting games need payment. You either need to buy apps immediately, buy them after some testing, or use in-app payment to get more interesting offers.

Using family safety there are some issues with buying from the store – buying just doesn’t work with the kids account. I had some issues with this that I could all resolve, and this is explained with this article.

Deutschsprachige Version des Artikels

image

Some questions I had:

  • How to buy apps from the store with family safety?
  • I don’t want to add my credit card to the kids accounts
  • Do I have to buy the same app for every kid account?

All these questions are resolved with this article. Using the Windows Store with family safety does not work automatic. Doing this as I’ve finally found out, buying kids games with family safety can be done fine.

In case you try to buy apps from kids accounts with family safety turned on, timeouts can be the result. I never succeeded buying an app this way. At least there’s the issue that the URLs for the Windows store are not opened with family safety. I didn’t check to allow the correct URLs, maybe there would be some other issues as well I’ve found a better way.

Parent Account

First, a specific parent account should e created. For this account I didn’t use my major Microsoft account but added another one. These are the reasons for adding another Microsoft account:

  • One Microsoft account can only install apps from the store using 5 PCs. With my PC’s and the PC’s of my children, this limit is exceeded.
  • With my major account I don’t want to see all the games as my apps. The Windows store hast the great feature that just with a few clicks all my apps can be installed on a fresh new system. The children’s apps shouldn’t be part of this.
  • One great feature of the Windows store is that with just a few clicks to install all my apps with just a few clicks.

Buying Apps with the Parent Account

Using the parent account it’s fine for me to add the credit card to the store. Now I can install games on the kid’s PC’s using this parent account. In-app payment is also done using this account. Games I’m buying for the children I need to test anyway, so it’s not an issue to start in-app payment from the parent account.

Installing Apps with Kids-Accounts

The next step is to install the app again using the kids account. One paid app can be installed on up to 5 PC’s – and this can be done from other accounts as well. First I’m logging into the kids-account. However, in the store I’m changing the account to the parents account. This is done from the charms bar, Settings, Your Account. Changing to the parent account in the store, it’s easy to find the paid apps again with Your Apps in the app bar. This also makes it easy to install the apps for every kid.

Summary

The easiest way to install paid apps for children is to use a dedicated parent account. First install the apps using this parent account. Logging in to the system with the kids account, changing the store to to the parents account, the apps can be installed again for the children.

It”s possible to install a paid app on up to 5 PCs. So this is fine for up to 5 children. I’m not planning to exceed this Windows limit Winking smile

Have fun!

Christian

CN innovation


A Happy New Year 2013!

2013 – the first year with 4 different digits since…. since 1987!

My previous blog article was about 2012. What can we expect from 2013?

German Version

image

Windows 8 was the start in a new era. Applications are becoming easier, specialized for a feature. Touch is an important aspect of the new applications. Focusing them to specific features makes them easier to use. However, with such smaller apps, communication between apps is becoming more and more important.

The new Microsoft design not only influences Windows Store apps, but also desktop apps (btw, desktop apps can be found by the Windows Store, and Windows Store apps can be installed without the Windows Store by using sideloading).

Windows 8 is becoming a cool operating system only with its apps. For 2013 I’m expecting many new apps; not only consumer apps but also LOB apps. Some of the LOB apps were already shown at the last Build conference, e.g. apps from SAP, Citrix, Hyland, Greenway Medical, and others. With the start of developing LOB apps for Windows 8, I’m expecting to see many new usability ideas. This is for accounting apps as well.

It will take some time before the desktop can be fully replaced by Windows RT. The year 2013 will bring some progress to this, but of course the desktop will stay important in 2013. Talking more time, the new UI will win. In reality, many users nowadays don’t need more than Windows RT. With more apps, Windows RT is becoming the future.

Many new Windows Store apps in 2013

Windows Blue was already discussed. What’s really behind Windows Blue we’ll see in 2013. No matter what this code really means, I believe in faster update cycles. Windows Azure is a front-runner with this to bring new features every quarter. Visual Studio is running with a faster update pace as well since the release of Visual Studio 2012. Windows should deliver faster updates, as well.

Last year, Microsoft introduced Windows Phone 8. With this phone update, the operating system for the phone is similar to the one for the desktop. In reality it’s not the same, but became more similar. With Windows Phone apps some features from Windows Store apps are still missing. I’m missing JavaScript project templates in Visual Studio, and some small parts like the HttpClient class (namespace System.Net.Http). I’m expecting some updates for Windows Phone in 2013 as well.

Faster updates for Windows, Windows Phone, Visual Studio

Continuing with development, at Microsoft Windows Store apps have a major focus – of course. I’m expecting updates for libraries, many new features, and features in regard to LOB apps.

JavaScript is becoming more and more important. JavaScript is not only used for client-side development, but on the server as well. Using table and blob storage with Windows Azure Mobile Services can be done using JavaScript – with the help of Node.js. Issues of JavaScript are solved with TypeScript.

image

C++ is becoming more important again. For 2013 I’ve already requests for C++11 workshops Smile

image

C++11 and TypeScript

Let’s make a move to hardware. Microsoft Surface Pro is available soon.

image

I’m already using a Microsoft Surface RT, running several Windows Store apps on this device. For development with Visual Studio I need a larger touch device. Hardware manufactures were not delivering powerful devices in 2012. Now some cool devices are nearby.

One powerful device is the Lenovo Thinkpad X1 Carbon Touch

image

another option the HP Spectre XT TouchSmart

image

Microsoft Surface Pro or a powerful device such as Lenovo Thinkpad X1 Carbon Touch or HP Spectre XT TouchSmart?

In 2012 I completed the book Professional C# 2012 and .NET 4.5. For 2013 I’m hoping it sells well – and I’m already working on another book. However, the time is not right to talk about this Winking smile

image

Professional C# 2012 and .NET 4.5

A Happy New Year 2013!

Live long and prosper!

 

Christian

CN innovation


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