Data Snacking Metro Style: Part 1 Working with Web APIs

In a previous post I discussed the five different types of Metro style apps that are relevant for Windows 8. In this series I will walk you through building a basic data-snacking application.

Topics Covered

  • Windows 8 Metro apps
  • HTML & JavaScript Metro apps
  • Using data from Web APIs
  • Asynchronous calls
  • JavaScript Promises
  • ListView UI control
  • Data binding HTML controls

Get the sample app.

The Scenario

For review, a data snacking app is one that enables users to consume small chunks of information in a hurry, as time permits. These apps are used regularly and repetitively by users during “down-time” (e.g. waiting in a lobby, on the metro (pun intended), before a meeting, etc.). For the purpose of this walk-through I will build a weather app, similar to the Weather app included in the Windows 8 Developer Preview release. This weather app, named “Seven Days,” will show the current weather conditions, plus the forecasts for the next six days (seven days in all, hence the name). In this post I will build the app to get weather data based on a static (aka hard coded) location, and in follow-up posts I will add the ability to get the weather info based on either the current location of the device the app is running on, or through user input of one or more locations.

image

Language Choice

The first consideration is whether to build a XAML/C# app or an HTML/JavaScript app. Ultimately I know that this application is going to revolutionize the weather-data-snacking market, so I want it to reach as many platforms as possible, so I am going with HTML5 and JavaScript. Of course, I know that this choice doesn’t automatically make my app portable, but as a long-time ASP.NET developer, HTML and JavaScript are more familiar to me than XAML (although I do love C#), and using HTML/JavaScript means that I will have some ability to reuse assets (e.g. HTML layouts, CSS styles, base-level JavaScript functions) across device platforms, rewriting only platform-specific code.

Its settled, I will use HTML and JavaScript.

Using Visual Studio 11 Express for Windows Developer Preview, I create a new Fixed Layout project and get to work.

Setting up the UI

I tend to think in user experience first, and prefer to start with my UI layout before anything else. Looking at the screenshot above, there is a basic structure I need to build – three rows (one in the middle row—outlined in a green dashed line below—for the current weather detail, and one in the bottom row—outlined in a red dashed line below—for the forecast) with two grids (the current weather detail grid—outlined in a red solid line—and a forecast grid—outlined in white).

image

Using DIV Elements as Placeholders

The first two rows are pretty straight forward – I’ll use a set of DIV elements for the current temperature and location in the top row, and a TABLE with DIV elements for the current weather detail in the middle row.

<!DOCTYPE html>
<
html
>
<
head
>
<
meta charset
=”utf-8″ />
<
meta name=”viewport” content
=”width=1024, height=768″ />
<
title>Seven Days by Doug Seven</title
>
<!– WinJS references –>
<link rel=”stylesheet” href
=”/winjs/css/ui-dark.css” />
<
script src=”/winjs/js/base.js”></script
>
<
script src=”/winjs/js/ui.js”></script
>
<
script src=”/winjs/js/binding.js”></script
>
<
script src=”/winjs/js/controls.js”></script
>
<
script src=”/winjs/js/animations.js”></script
>
<
script src=”/winjs/js/uicollections.js”></script
>
<
script src=”/winjs/js/wwaapp.js”></script
>
<!– SevenDays references –>

    <
script src=”/js/default.js”></script>
<
link rel=”stylesheet” href
=”/css/default.css” />
</
head
>
<
body
>
<
div data-win-control
=”WinJS.UI.ViewBox”>
<
div class
=”fixed-layout”>
<
div id
=”topRow”>
<
div id
=”currentWeather”>
<
div id
=”currentTemp”>
</
div
>
<
div id
=”currentLocation”>
</
div
>
</
div
>
</
div
>
<
div id
=”middleRow”>
<
div id
=”statusMessage”>
</
div
>
<
div id
=”currentWeatherData”>
<
table
>
<
tr
>
<
td class
=”currentWeatherElement”>
<
div id
=”currentTempRange”
class
=”currentWeatherDataItem”>
</
div
>
High / Low
</td
>
<
td class
=”currentWeatherElement”>
<
div id
=”humidity”
class
=”currentWeatherDataItem”>
</
div
>
Humidity
</td
>
<
td class
=”currentWeatherElement”>
<
div id
=”currentCondition”
class
=”currentWeatherDataItem”>
</
div
>
Current condition
</td
>
</
tr
>
<
tr
>
<
td class
=”currentWeatherElement”>
<
div id
=”feelLike”
class
=”currentWeatherDataItem”>
</
div
>
Feels like
</td
>
<
td class
=”currentWeatherElement”>
<
div id
=”uvIndex”
class
=”currentWeatherDataItem”>
</
div
>
UV Index
</td
>
<
td class
=”currentWeatherElement”>
<
div id
=”wind”
class
=”currentWeatherDataItem”>
</
div
>
Wind
</td
>
</
tr
>
</
table
>
</
div
>
<
div id
=”currentDateTime”>
</
div
>
</
div
>
<
div id=”bottomRow”>

            </
div>
</
div
>
    </div
>
</
body
>
</
html
>

This is pretty straight forward, so I won’t go into any detail on it. I also spent some time on CSS definition, to make it look nice. Nothing surprising in the CSS, and it is available as part of the sample download.

Using a ListView

For the bottom row, I anticipate getting a feed of data from a weather service, and binding that data to a grid layout with a single row of six items. The ListVIew control (WinJS.UI.ListView) works in just that way. I can use the ListView to create a grid layout and use a template to define how the items in the grid will look. In this case, I want a grid where each item shows the date, a weather icon, the high and low expected temperatures and a brief forecast on the conditions of the day.

The ListView is a DIV element with a data-win-control attribute set to WinJS.UI.ListView.

<div id=”forecastGrid”
data-win-control
=”WinJS.UI.ListView”
data-win-options
=”{itemRenderer: template,
layout: {type: WinJS.UI.GridLayout, maxRows:1}}”>
</
div>

I’ve also set the data-win-options attribute to define how I want the ListView to render (use an item template named “template”, layout as a grid (as opposed to a list), and have no more than one row). The use of the template is key; this is what enables me to define the look of each item that is rendered in the grid.

A template is a DIV with the data-win-control attribute set to WinJS.Binding.Template. This enables it to be the template used when data bound to a source (don’t worry, I’ll get to that soon).

<div id=”template”
data-win-control
=”WinJS.Binding.Template”>
<
div class
=”dailyWeather”>
<
div class
=”dayTitle”>
<
span data-win-bind=”innerText: Day” class=”dayPart”></span
>
<
span data-win-bind=”innerText: Date” class=”datePart”></span
>
</
div
>
<
div class
=”weatherIcon”>
<
img data-win-bind=”src: IconUrl; alt: IconAlt”
/>
</
div
>
<
div data-win-bind
=”innerHTML: HighLow”
class
=”highLow”>
</
div
>
<
div data-win-bind
=”innerText: Condition”
class
=”condition”>
</
div
>
</
div
>
</
div>

Inside the template I have defined how I expect the data source to be bound to the UI elements. Using the data-win-bind attribute I define the element attribute to bind, and the data source item’s property to bind to.

<img data-win-bind=”src: IconUrl; alt: IconAlt” />

In the IMG element example, I have specified that the SRC attribute should be bound to the item.IconUrl value and the ALT attribute should be bound to the item.IconAlt value.

Getting Data from a Web API

The next step in building Seven Days is to get some real data. There are a lot of weather Web APIs to choose from, and I’m not here to tell you which one to use. For the purpose of this example I have chosen to use Weather Underground (Wunderground.com) because they provide their results in JSON format, have clear pricing structures (including a free Developer level) and will provide up to 10-days of weather forecasts (many other weather Web APIs only provide 2 or 3 days of forecasts).

The first thing I need to do is add some JavaScript to get the weather data for a predefined location (I won’t add fancy functionality like geolocation lookup, or pick-a-location until I get the basics working). To do this I can use WinJS.xhr, which is an asynchronous wrapper on the XMLHttpRequest object, to make the request, and return the response.

// Query Format: http://api.wunderground.com/api/KEY/FEATURE/%5BFEATURE…%5D/
// q/QUERY.FORMAT
function weatherLookup(loc) {
// Set the date and time info
var d = new Date();
id(“currentDateTime”).innerText = d.toLocaleDateString()
+
“, ”
+ d.toLocaleTimeString();

var apiUrl = http://api.wunderground.com/api/&#8221;
+ apiKey
+ “/geolookup/conditions/forecast10day/q/”
+ loc
+ “.json”;

// WinJS.xhr is an async wrapper for the XMLHttpRequest class.
WinJS.xhr({ url: apiUrl }).then(
processWeather,         // Called when the promise is complete
dataFetchingError       // Called when there is an error
);
}
wunderground.weatherLookup = weatherLookup;

The apiKey value is provided to you when you create an account on wunderground.com, and the loc value is whatever predefined location string you want to use (I am using “WA/SAMMAMISH”).

Working with Promises

The WinJS.xhr object is a “promise” object. There is a proposed JavaScript standard for promises, which enable invoking methods which promise to return a value at a point in the future. The WinJS.Promise object exposes a “then” method (which I have used in this example) which identifies what to do when the promise returns a value. The first argument of “then” is the callback function to invoke when the promise (in this case, sending the HTTP request and getting back the response) completes successfully. The second argument is the callback function to invoke when the promise returns an error. There is a third option for invoking a progress callback, if the promise reports on progress (so far very few promise operations implement the progress callback option).

Anytime you are invoking a method that could take longer than 50-milliseconds, the guidance is to use an asynchronous method, which enables the UI to continue working while the asynchronous method executes. That is exactly what the “promise” object and “then” method enable. When the promise object is invoked, the code flow surrounding the promise continues (e.g. the next line of code is executed) and the asynchronous (promise) method is invoked on another thread. This enables long running operations (like retrieving data from a Web API) to be called without blocking the UI functionality, resulting in a much more responsive (aka “fast and fluid”) application.

Consider the following example, where two asynchronous calls are made to get data from Bing.com using the Promise/Then model. When the application runs, the progress callback is called every time the XMLHttpRequest object being used changes its ready state. Since each of the requests is running asynchronously, the results are intermixed, and the UI is refreshed without blocking any responsiveness.

(function () {
‘use strict’
;
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);

WinJS.Application.onmainwindowactivated =function(e) {
if(e.detail.kind
===
Windows.ApplicationModel.Activation.ActivationKind.launch
) {
// Add an event listener for the button’s click event.
document.getElementById(“myButton”).addEventListener
(
‘click’, onMyButtonClicked,false
);
}
}

function onMyButtonClicked() {
getWebContent
();
}

function getWebContent() {
var bingUrl =http://www.bing.com/search?q=windows+8&#8221;
;
id(“contentDiv”).innerHTML =“Calling xhr (First).<br/>”
;
// WinJS.xhr is an async wrapper for the XMLHttpRequest class.
       
WinJS.xhr({ url: bingUrl }).then(
onComplete,   
// Called when the promise is complete
onError,      
// Called when there is an error
onProgress    
// Called when the promise reports progress
);
id(“contentDiv”).innerHTML +=“Called xhr (First).<br/>”
;

id(“contentDiv”).innerHTML +=“Calling xhr (Second).<br/>”;
WinJS.xhr({ url: bingUrl }).then(

               
onComplete,
               
onError,
               
onProgress2    // Call a different function to show progress.
);
id(“contentDiv”).innerHTML +=“Called xhr (Second).<br/>”
;
}

function onComplete(request) {
id(“contentDiv”).innerHTML +=“Request complete.<br/>”
;
}

function onError(request) {
id(“contentDiv”).innerHTML +=“<p>!!!ERROR!!! “+request.status+“</p>”
;
}

function onProgress(request) {
id(“contentDiv”).innerHTML +=“Progress on First.<br/>”
;
}

functiononProgress2(request) {
id(“contentDiv”).innerHTML +=“Progress on Second.<br/>”
;
}

functionid(elem) {
returndocument.getElementById(elem
);
}

WinJS.Application.start();
})();

image

Connecting the Data to the UI

Now that I have data coming from a Web API, the last thing I need to do to get Seven Days working, so I can see the fruit of my labor, is to populate the UI controls with the appropriate data. The data from the WinJS.xhr() call is returned when the “complete” callback is invoked (i.e. processWeather()).

// WinJS.xhr is an async wrapper for the XMLHttpRequest class.
WinJS.xhr({ url: apiUrl }).then(
processWeather,        // Called when the promise is complete
   
dataFetchingError    // Called when there is an error
);

The processWeather function uses the JSOPN.parse method to create objects from the data returned. To make setting UI attributes easier, I create four objects from the JSON results returned by the Web API.

var forecastList;
function processWeather(request) {
// Clear the forecast list
   
forecastList = [];
// Parse the JSON response into navigatable objects
   
var weatherData = JSON.parse(request.responseText);
var currentObservation = weatherData.current_observation;
var currentForecast = weatherData.forecast.simpleforecast.forecastday[0];
var forecasts = weatherData.forecast.simpleforecast.forecastday;

Each of these objects will be used to populate different parts of the UI.

  • weatherData represents the entire JSON result set.
  • currentObservation represents the current conditions for the specified location, including an array of weather stations nearby and temperature, as well as some, but not all of the details (like UV index, wind chill, condition, humidity, wind direction and wind speed).
  • currentForecast represents forecast data for the current day (the first item in the forecastday array), including expected high and low temperatures.
  • forecasts is an array of forecasts for the current day and the following 9-days (the Web API request specified a 10-day forecast) and will be used to display the lower table of forecasts.

To populate the UI I am using a combination of explicit value setting and data binding. As the app develops, and I add the ability to get weather for multiple cities, I may move to an entirely data binding model, but that is overkill for the app right now.

To do the element value setting (for the top two rows), I am going to steal borrow an id() function from the Windows 8 SDK samples to make setting values easier.

function id(elemName) { return document.getElementById(elemName); }

This enables me to set an element’s innerText or innerHTML value (or any other property) in the following way:

id("currentTemp").innerHTML = tempString + "&deg;";

Using this model, the next section of the processWeather function looks like this:

// Set the values of the current day weather
var tempString = currentObservation.temp_f.toString();
tempString = tempString.indexOf(‘.’) > 0 ?
tempString.substring(0, tempString.length 2) :
tempString;
id(“currentTemp”).innerHTML = tempString + “&deg;”;
id(“currentLocation”).innerText = currentObservation.display_location.full;
var todayHigh = currentForecast.high.fahrenheit;
var todayLow = currentForecast.low.fahrenheit;
id(“currentTempRange”).innerHTML = todayHigh + “&deg; / ” + todayLow + “&deg;”;
id(“feelLike”).innerHTML = currentObservation.windchill_f + “&deg;”;
id(“uvIndex”).innerText = currentObservation.UV;
id(“currentCondition”).innerText = currentObservation.weather;
id(“humidity”).innerText = currentObservation.relative_humidity;
var windSpeed = currentObservation.wind_mph;
var windDir = currentObservation.wind_dir;
id(“wind”).innerText = windSpeed + ” mph ” + windDir;
id(“lastUpdated”).innerText = currentObservation.observation_time + “. Data provided by wunderground.com”;

With the top two rows populated its now time to build the data source for the lower grid and bind the ListView control to the data source. To build the data source I loop through the forecasts object that I created from the JSON results (skipping the first item, which is today’s forecast), and create an array of forecast items with specific properties that will be displayed. Once the loop has iterated six times, I break out of the loop (remember, this app is Seven Days, not Ten Days). The last step is to set the data source of the ListView control to the array that was just created.

// Build the forecast list for the next six days
for (var i = 1, len = forecasts.length; i < len; i++) {
var item = forecasts[i];
var itemHigh = item.high.fahrenheit;
var itemLow = item.low.fahrenheit;
var itemHighLow = itemHigh + “&deg; / ” + itemLow + “&deg;”;
var forecastItem = {
Day: item.date.weekday_short,
Date: item.date.day,
HighLow: itemHighLow,
IconAlt: item.icon,
IconUrl: item.icon_url,
Condition: item.conditions
};
if (i == 1) {
forecastItem.Day = “Tomorrow”;
forecastItem.Date = “”;
}
forecastList.push(forecastItem);
// Once there are six days of weather, stop building the list
if (i >= 6)
break;
}
// Populate the forecastGrid control
forecastGrid.winControl.dataSource = forecastList;
}

To trigger the binding of the UI elements to the data source, I need to invoke WinJS.UI.processAll() which processes all declarative controls so that any that are data bound get processed and the data is rendered on screen. I have this call in the default.js file as the last line of the initialization function.

WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
// TODO: startup code here
       
wunderground.weatherLookup(“WA/SAMMAMISH”);
// process the declarative controls
        WinJS.UI.processAll();
}
}

With that, I now have a functioning weather app (there is some CSS styling I didn’t show in this post, but is in the sample code).

Summary

In this post I showed you how to create a basic Metro style app for Windows 8 that asynchronously calls a Web API to get and display some data, both explicitly and with data binding. In follow up posts I will show you how to

  • use the geolocation capabilities of Windows 8 to get actual position data to display weather for
  • how to use local storage to save a list of favorite cities to get weather for
  • how to use the AppBar to expose additional capabilities
  • how change the UI when the device orientation changes.
    In the final set of posts I will show you how to port this application to the iPad and Android tablets to extend the reach of your application.

What About Video

On a final note, the app wouldn’t have the right level of polish without a cool HD video background running in a loop, which can be done easily with the following HTML and CSS (the video is not included in the sample download):

HTML

<video id="vidbg" src="/video/background.mp4" autoplay="autoplay" loop="loop" />

CSS

#vidbg { position: absolute; top: 0px; left: 0px; width: 100%; z-index: -1; }

Language Choice in Windows 8 is Not About Portability

Every time I go to talk to folks about Windows 8, the same questions pop up. I blame this largely on Microsoft’s silence about Windows 8 following the release of a tidal wave of information followed by the Windows 8 Developer Preview at Build in September. C’est la vie. This too shall pass.

One of the topics of conversation that comes up repeatedly is how to choose between using HTML5 + JavaScript or XAML + C#/VB (aka .NET) to build Metro style applications. What are the factors that you should consider before making your choice? Is HTML5 better? Is there a future for XAML? How do you choose?

Inevitably someone in the conversation cites the portability of HTML5 and JavaScript as the answer. It goes something like this…

“You should use HTML5 and JavaScript for Metro style applications because its portable and XAML isn’t. If you build with HTML5 then you can use the same code for your website or other platforms because its standards-based….HTML and JavaScript.”

This couldn’t be further from the truth. The use of HTML5 + JavaScript in Windows 8 is about as proprietary as using XAML + .NET. Consider the “Hello World” of the modern era – an RSS feed reader.

If you are going to build a feed reader into your Metro style application using HTML5 and JavaScript, it would look something like this:

DEFAULT.HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>RssReader</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-light.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- RssReader references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
  <h1>RSS Reader</h1>
  <div id="downloadStatus"></div>
  <div id="template" data-win-control="WinJS.Binding.Template">
    <div class="postTitle" data-win-bind="innerText: title"></div>
    <div class="postDate" data-win-bind="innerText: date"></div>
  </div>
  <div id="posts" data-win-control="WinJS.UI.ListView"
    data-win-options="{itemRenderer: template,
                       layout: {type: WinJS.UI.ListLayout},
                       selectionMode: 'single',
                       onselectionchanged: selectionChanged}">
  </div>
  <div id="contentTemplate" data-win-control="WinJS.Binding.Template">
    <div class="postTitle" data-win-bind="innerText: title"></div>
    <div class="postDate" data-win-bind="innerText: date"></div>
    <div class="postContent" data-win-bind="innerHTML: content"></div>
  </div>
  <div id="content"></div>
</body>
</html>

DEFAULT.JS

(function () {
  'use strict';
  WinJS.Application.onmainwindowactivated = function (e) {
    if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch){
      downloadStatus.innerText = "Downloading posts...";

      var syn = new Windows.Web.Syndication.SyndicationClient();
      var url = new Windows.Foundation.Uri("https://dougseven.com/feed/");
      syn.retrieveFeedAsync(url).then(processPosts, downloadError);

      // Define an event listener for the onselectionchanged event.
      posts.addEventListener("selectionchanged", selectionChanged);
      // Process the declarative controls
      WinJS.UI.processAll();
    }
 
}

  function selectionChanged(e) {
    content.innerHTML = "";
    var selection = posts.winControl.selection;

    if (selection.length) {
      var post = postItems[selection[0].begin];
      var contentTemplate = WinJS.UI.getControl(
        document.getElementById("contentTemplate")
        );

      contentTemplate.render(post).then(function (element) {
        content.appendChild(element);
        });
    }
  }

  var postItems = [];
  function processPosts(feed) {
    // Clear the process indicator
    downloadStatus.innerText = "";
    // Iterate over the items
    for (var i = 0, len = feed.items.length; i < len; i++) {
      var item = feed.items[i];
      var post = {
        title: item.title.text,
        date: item.publishedDate,
        content: item.summary.text,
        };

      postItems.push(post);
    }

    // Populate the ListView control's data source
    posts.winControl.dataSource = postItems;
  }

  function downloadError() {
    downloadStatus.innerText = "Error loading posts.";
  }

  WinJS.Application.start();
})();

The Results

The resulting application creates a simple two column RSS feed reader, with post titles on the left, and post content on the right (in HTML):

image

Now imagine you wanted to use the same code to make your RSS feed reader website. Immediately you have to cut out all references to the WinJS JavaScript files, since WinJS is a JavaScript wrapper around key WinRT functions.

<!-- WinJS references –>
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>

For example, the Metro style RSS feed reader application uses WinJS to manage a lot of the UI look and feel, data binding and how you interact with the application, including controls, animations, etc. All of that functionality will have to be rewritten in non WinJS format.

You are forced to rewrite key functionality, such as the feed syndication capabilities written in JavaScript which leverage Windows.Web.Syndication.SyndicationClient – a WinRT class that manages the network interaction between the client and the feed provider, including the asynchronous calls to get the RSS data and parse and format it correctly.

var syn = new Windows.Web.Syndication.SyndicationClient();
var url = new Windows.Foundation.Uri("https://dougseven.com/feed/");
syn.retrieveFeedAsync(url).then(processPosts, downloadError);

You have to rewrite the data binding of the feed items to the HTML layout.

// Populate the ListView control's data source
posts.winControl.dataSource = postItems;

// Process the declarative controls
WinJS.UI.processAll();

<div id="template" data-win-control="WinJS.Binding.Template">
  <div class="postTitle" data-win-bind="innerText: title"></div>
  <div class="postDate" data-win-bind="innerText: date"></div>
</div>
<div id="posts"
  data-win-control="WinJS.UI.ListView"
  data-win-options="{itemRenderer: template,
                     layout: {type: WinJS.UI.ListLayout},
                     selectionMode: 'single',
                     onselectionchanged: selectionChanged}">
</div>
<div id="contentTemplate" data-win-control="WinJS.Binding.Template">
  <div class="postTitle" data-win-bind="innerText: title"></div>
  <div class="postDate" data-win-bind="innerText: date"></div>
  <div class="postContent" data-win-bind="innerHTML: content"></div>
</div>

That doesn’t feel very portable.

The conclusion is that your language choice when building a Windows 8 Metro style application has next-to-nothing to do with portability.

Before you get on your soap box, yes you can reuse some of the assets from the application. For example, the CSS is reusable between Windows 8 and the web. Some of the JavaScript is likely reusable, if it isn’t tightly coupled to WinJS or WinRT. But that’s it. Most of what makes the app work is dependent on WinRT, so its not portable – WinRT only runs on Windows 8.

Get Comfortable

So what should your language selection be based on? Comfort.

Microsoft architected an application development stack that does what Microsoft does best – provides flexibility and gives YOU choice. If you want to build an application for Microsoft’s upcoming platform, you can choose the language that you are most comfortable with. Microsoft isn’t making you learn an entirely new stack – just learn the new bits – and use the skills you already have.

Choose XAML

If you are a .NET developer currently working in WPF or Silverlight, then XAML+.NET will be right up your alley. Sure you will have to learn WinRT and some new syntax, but most of what you need to know you already do.

Choose HTML

If you are a web-standards developer, familiar with HTML and JavaScript, then use those skills. Use HTML5, JavaScript and learn WinJS and WinRT.

Either way Microsoft has made developing for Windows 8 very approachable. Make your language selection based on your skillset and what is comfortable for you. Don’t feel like you have to lean a new language. Use what you know.

D7

There is a need for only five Metro style apps in the world.

Windows 8 Start Screen

Over the past week I have spent some time playing with Windows 8 and the Samsung Windows 8 Developer Preview Device (SW8DPD). If you’ve spent any time lurking around the Start page or trying out the Metro apps you’ve likely come to the same conclusion I have. There are only five (5) Metro style application types. All of the Metro style app samples in the Windows 8 Developer Preview fit pretty nicely into one of these five categories, which leads me to assert that these are the five intended categories for Metro style apps – anything else is meant for Desktop mode.

Windows 8 Start Screen
Windows 8 Start Screen

In my earlier post (I know what you’re thinking, and you’re wrong.) I talk about Visual Studio as a Desktop mode application – some applications just aren’t metro sexual style. So if Visual Studio is—as an example—not meant to be Metro style, what is? What are the five application types.

First let me inventory the Metro style apps (I am excluding Windows resources and tools, including Control Panel, Alarms and Store).

  • Internet Explorer (obvious)
  • Build (a Build conference schedule and experience app)
  • Tweet@rama (a Twitter client)
  • Socialite (a Facebook client)
  • Stocks (a stock market data viewer)
  • Headlines (an RSS feed aggregator)
  • Weather (a weather data viewer)
  • 5 (a tic tac toe like 2-D game)
  • Piano (a piano simulator)
  • picstream (a picture feed viewer)
  • Zero Gravity (a 2-D game)
  • Measure It (a measuring tool that uses pictures and relative sizing)
  • PaintPlay (a free-painting tool)
  • Tile Puzzle (a 2-D puzzle game)
  • Near Me (a location-based data viewer to find activities near you)
  • Tree House Stampede (a 2-D spelling game)
  • Labyrinth (an accelerometer based maze game)
  • Mopod (a podcast viewer/player)
  • Tube Rider (a 2-D game)
  • Memories (a magazine/scrap book style photo and video viewer)
  • Sudoku (a 2-D puzzle game)
  • CheckM8 (a 2-D chess game)
  • Air Craft (a 2-D game/tool to design and create paper airplanes)
  • Word Hunt (a 2-D Scrabble-type game)
  • Copper (an immersive/3-D video game)
  • Flash Cards (a children’s educational game)
  • Ink Pad (a note taking app for the stylus)
  • Bit Box (a music creation app)

Whew! That’s a lot of Metro style.

Let me group these apps into the five types I believe there are. Consider this your guidebook to Metro style apps. If its not in this list, don’t Metrofy it.

Data Snacks

  • Stocks
  • Weather
  • Near Me

Data Snack apps enable users to consume small chunks of information in a hurry as time permits. These apps are used regularly and repetitively by users during “down-time” (e.g. waiting in a lobby, on the metro (pun intended), before a meeting, etc.).

Social Networking / Mash-Ups

  • Tweet@rama
  • Socialite

If you want to know where people spend their time on a computing device (PC, Phone, iPad), its here in the Social Networking / Communication / Collaboration category. More often than not consumers are using one of the many social networking client apps available (e.g. Twitterific) and in some cases those client apps bring-together (or mash-up) multiple social networking APIs (e.g. TweetDeck) or other unique options.

Content / Media Applications

  • Headlines
  • picstream
  • Memories
  • Mopod

Consumers, and especially device users, are expecting more out of content than simply text. More often than not content is being delivered in rich ways, more like well produced magazines (e.g. Flipboard) than just content feeds. The magazine-style applications are evolving to deliver more richness thorugh integrated media (e.g. Memories use of photos and videos).

Casual Games

  • 5
  • Piano
  • Zero Gravity
  • Measure It
  • PaintPlay
  • Tile Puzzle
  • Tree House Stampede
  • Labyrinth
  • Tube Rider
  • Sudoku
  • CheckM8
  • Air Craft
  • Word Hunt
  • Flash Cards
  • Ink Pad
  • Bit Box

Based on the proportion of apps in this category, it feels like this is where Microsoft would like to succeed (it also happens to be where iOS is killing it).

Games are the king, and probably will be. If you haven’t played Angry Birds, then you live on an island and are likely reading this off a print out that floated to you in a bottle because you don’t have WiFi, an iPad or power. It is ridiculous how much time we all spend playing games. But not XBox games…casual, easy to play games…like Angry Birds, or Mafia Wars, or CityVille (over 20-million users).

Graphical Games

  • Copper

This category is about highly graphical, fully immersive games. These are typically produced by game studios and include racing games, first person shooters, and other fully immersive, highly interactive games. These are games that would be most likely built for Windows 8 with DirectX and C/C++.

…and I’m Out

So there you have it, the five types of Metro apps – Data Snacks, Social Networking/Mash-ups, Content/Media, Casual Games and Graphical Games. Two things are missing – the Build app (maybe this is a content app, but mostly it’s a tax – how could Microsoft give out devices at Build without a Build app), and Line-of-Business (LOB) apps. Frankly, unless you are building a touch-centric app for agents using 3G devices in the field, Metro style is no style for LOB. Stick with Desktop mode and Silverlight/WPF for LOB apps.

D7

A bad picture is worth a thousand long discussions.

While here at Build I’ve been in lots of conversations with customers, other attendees, Microsoft MVP’s, Microsoft Regional Directors, and Microsoft engineering team members. One of the recurring topics that I’ve been talking about ad nausium is the “boxology” diagram of the Windows 8 Platform and Tools (shown here).

Now let me tell you, I have drawn a lot of these “marketecture” diagrams in my time and its not easy. These kind of diagrams are never technically accurate. There is simply no easily digestible way to make a technically accurate diagram for a complex system that renders well on a slide and is easy to present and explain. The end result is that you create a diagram that is missing a lot of boxes – missing a lot of the actual technology that is present in the system. Unfortunately that is exactly what has happened here – the Windows 8 boxology is missing some of the actual technology that is present.

One of the conversations that has come up is around the missing box in the “green side” (aka Metro style apps) for the .NET Framework and the CLR. Do VB and C# in Metro style apps compile and run directly against the WinRT? Is this the end of the .NET Framework?

Others who have done some digging into the bits are wondering if there are two CLRs. What the heck is going on in Windows 8?

I spent some time with key members of the .NET CLR team last night (no names, but trust me when I say, these guys know exactly how the system works), and here’s the skinny.

Basic Facts:

  • There is only one CLR. Each application or application pool (depending on the app type) spins up a process and the CLR is used within that process. Meaning, a Metro style app and a Desktop Mode app running at the same time are using the same CLR bits, but separate instances of the CLR.
  • The .NET Framework 4.5 is used in both Desktop Mode apps and in Metro style apps. There is a difference though. Metro style apps use what is best described as a different .NET Profile (e.g. Desktop apps use the .NET Client Profile and Metro style apps use the .NET Metro Profile). There is NOT actually a different profile, but the implementation of .NET in Metro style apps is LIKE a different profile. Don’t go looking for this profile – its basically rules built into the .NET Framework and CLR that define what parts of the framework are available.
  • Whether a Desktop Mode app or a Metro style app, if it is a .NET app, it is compiled to the same MSIL. There isn’t a special Windows 8 Metro IL – there is, like the CLR, only one MSIL.

A More Accurate Picture

A more correct (but still marketecture that is not wholly technically accurate) would look like this:

In this diagram you can see that the CLR and the .NET Framework 4.5 are used for C# and Visual Basic apps in either Desktop Mode apps (blue side) or Metro style apps (green side). Silverlight is still only available in Desktop Mode as a plug-in to Internet Explorer (yes, out of browser is still supported in Desktop Mode). Another addition in this diagram is DirectX, which was strangely absent from the original diagram. DirectX is the defacto technology for high-polygon count applications, such as immersive games. DirectX leverages the power of C++ and can access the GPU.

This biggest confusion, as I mentioned, has been around the use of the .NET Framework across the blue side and green side. The reason for the, as I call it, .NET Metro Profile is because the Metro style apps run in an app container that limits what the application can have access to in order to protect the end user from potentially malicious apps. As such, the Metro Profile is a subset of the .NET Client Profile and simply takes away some of the capabilities that aren’t allowed by the app container for Metro style apps. Developers used to .NET will find accessing the WinRT APIs very intuitive – it works similarly to having an assembly reference and accessing the members of said referenced assembly.

Additionally, some of the changes in the Metro Profile are to ensure Metro style apps are constructed in the preferred way for touch-first design and portable form factors. An example is File.Create(). Historically if you were using .NET to create a new file you would use File.Create(string fileLocation) to create the new file on the disk, then access a stream reader to create the contents of the file as a string. This is a synchronous operation – you make the call and the process stalls while you wait for the return. The idea of modern, Metro style apps is that ansychronous programming practices should be used to cut down on things like IO latency, such as that created by file system operations. What this means is that the .NET Metro Profile doesn’t provide access to FileCreate() as a synchronous operation. Instead, you can still call File.Create() (or File.CreateNew()…I can’t recall right now) as an asynchronous operation. Once the callback is made you can still open a stream reader and work with the file contents as a string, just like you would have.

Ultimately all of this means that you have some choice, but you don’t have to sacrifice much if anything along the way. You can still build .NET and Silverlight apps the way you are used to, and they will run on Windows for years to come. If you want to build a new Metro style app, you have four options to choose from:

  1. XAML and .NET (C# or VB)You don’t have to giving up too much in the .NET Framework (remember, you only give up what is forbidden by the Application Container), and you get access to WinRT APIs for sensor input and other system resources.
  2. XAML and C++You can use your skills in XAML and C++ in order to leverage (or even extend) WinRT. Of course you don’t get the benefit of the .NET Framework, but hey….some people like managing their own garbage collection.
  3. HTML and JavaScriptYou can leverage the skills you have in UI layout, and make calls from JavaScript to WinRT for access to system resources, and sensor input.
  4. DirectX and C++If you’re building an immersive game you can use DirectX and access the device sensors and system resources through C++ and WinRT.

Hopefully this adds some clarity to the otherwise only slightly murky picture that is the Windows 8 boxology.

Don’t forget to check out Telerik.com/build.

D7

I know what you’re thinking, and you’re wrong.

Its day 2 of the Microsoft Build conference, and if you’ve been keeping up with the hype you are probably thinking that you need to throw away that WPF or Silverlight app you’re building and start fresh with HTML5 or this new XAML that is the future. If that is what you are thinking, you are wrong. Everything you are doing today you should keep doing. The world didn’t end for you, and your job is not at risk (at least not because of this!). As a .NET junkie going back to the first pre-beta release of the ,NET Framework at PDC 2000 (it was called NGWS back then), and as the former Director of Product Management for Visual Studio, I can tell you that I am comfortable with how useful my skills, and my existing code will be going forward. I am also confident in the value of Telerik’s controls and tools in the future – clearly I knew enough of what was going on with Windows 8 and Visual Studio before I accepted the position of Executive Vice President at Telerik. If I am confident enough to bet my the livelihood of my family on it, you should also be confident in your skills and your existing code and projects.

I’ve also been talking to a lot of attendees at Build, and hearing from a lot of Telerik customers via Twitter and email. There is a lot of concern about the future of the technology we are all using today – specifically WPF and Silverlight. How do these technologies work in the Windows 8 world, and how different is XAML in Windows 8.

First things first, let me help clarify a bit of what Windows 8 is all about. The way to think about it is as though there are two completely different runtime environments….because there kind of are. On one side there is the new Metro style app models that run on the new Windows Runtime (WinRT) and on the other is what is being referred to as Desktop Mode running on the CLR, Win32 and/or IE. Here is the diagram that Microsoft presented.

win8-platform-and-tools

In this diagram there is a green side (Metro style) and a blue side (Desktop Mode). While it is not depicted here, there is a big fat solid wall in between the two sides. That which runs in the green side, cannot run in, nor access anything in the blue side, and vice versa. Apps you build for Windows 8 are either Metro styled apps or Desktop Mode apps. There shall be no comingling. This is a great design. Some apps should never be Metro styled apps, and some apps should ONLY be Metro styled apps.

Metro style apps run in an Application Container that enforces some security constraints and limits access to some system resources. This enables them to be interesting and engaging apps, with access to some identity services and other appropriate resources, but still have limitations that protect the end users. Desktop Mode applications don’t run in the Application Container, and have all the system-level access available to you today depending on how you are building your applications (e.g. .NET and trust levels, or Win32 and system level APIs).

The greatest example of the right use of Desktop Mode not talked about this week is Visual Studio 11 (yes, VS11 was talked about but no one pointed out why it is not a Metro style app). Your dev environment is not a touch-centric, sensor aware app that you’ll run on a small form factor. It is a powerful app that will need access to many system resources and is best experienced with a mouse and keyboard (and preferably more than one high-resolution monitors). Metro style apps are intended to be touch centric, sensor aware, single screen apps that will likely run on smaller form factors more often than a desktop or laptop PC (in fact we were thinking about calling these apps ‘NISA apps’ – Natural Interface, Sensor Aware apps….we canned that idea).

Just like Visual Studio is a ‘Desktop Mode’ app, so will be many of the apps you write. This isn’t to say there isn’t an opportunity for you to write a killer Metro style app, it just means you need to think about the user experience you want to enable and choose the app model that is best for your goals.

As you build applications between now and whenever Windows 8 ships, and beyond, chances are that unless you’re building an immersive, sensor aware app (like a device centric app or a game), or a rich content experience (like a magazine) you will still be targeting Desktop Mode. All of those business apps will still be Desktop Mode apps, and if that is the case, your use of WPF or Silverlight (including Telerik controls) is safe. All of that code you have today will run in Windows 8 Desktop Mode.

To be sure, I spent some time today with some of the folks that build the .NET CLR. They confirmed this to be true, and we spent some time talking about their Pri-0 commitment to not impact existing .NET Framework applications so that they will run in Desktop Mode.

Metro style apps are different. There is no support for Silverlight nor WPF for Metro style apps. And frankly you don’t need it. What you do need is controls and components that are compatible with the new XAML model for Metro style apps…and Telerik will deliver. We will begin working immediately on making our controls work in the new Metro style app model (in fact today @worksonmypc showed one of the Telerik demos running on the Windows 8 devices handed out at Build). In the future you will have a toolkit that includes Telerik Desktop Mode controls and Telerik Metro style controls. in some cases these will be the same or similar experiences, but we will also deliver to you Metro style controls that take advantage of all that the new app models offer, such as smaller screen resolutions, touch, accelerometer and other sensor inputs.

The one thing I haven’t addressed is the roadmap for Silverlight, and that is because Microsoft hasn’t shared anything beyond SL5, which is currently in RC. It is unclear whether or not there will be an SL6, but this I know – there will be an SL5, and it will have a 10-year support lifecycle. You can safely invest in Silverlight now, knowing that that investment will be supported for longer than the app will be useful, and Telerik will continue to make compelling UI controls for Silverlight as long as enough people want to use that platform.

Technology changes like what we are facing now take a long time to get to ubiquity. People are still using Windows XP (over 40% of all Windows usage is still Windows XP) and people will be using Windows 7 for a very long time. Even as people move to Windows 8 they will still live in Desktop Mode most of the time, except when they are using a tablet form factor. My advice…keep doing what you are doing, and invest 20% of your time in learning about Windows 8 and the Metro style app models. We’ve got a while before Windows ships, and a while after that before it becomes the most used version of Windows.

D7