What About Windows Phone?

In the past couple of days since I announced the release of Icenium, I’ve had a number of people asking me if it supports Windows Phone in addition to Apple iOS and Google Android. I suppose that is because nearly all other Telerik products are dedicated to the Microsoft technology stack, so it would be almost expected that Icenium would get on the band-wagon.

Its All About the Data

Allow me to let data do the speaking: 

Image

In the past year Apple and Google have grown in market share by nearly 17% (Source: comScore, U.S. Mobile Subscriber Market Share). In that same period, Microsoft dropped nearly 2% – meaning Apple and Google are outpacing Microsoft by nearly 20%. In fact, Apple and Google are the only two mobile platform providers that have been consistently growing in market share during that period.

So I decided to focus our efforts on Apple and Google. Microsoft will have to wait.

What Will Windows Phone Do?

I used to be a Windows Phone user. I loved my Windows Phone (I missed a lot of the apps from my old iPhone, but I LOVED the operating system and the Live Tiles). In the last year I have regularly switched phones every month or two, trying out several Android devices in addition to the iPhone 4/4S and now iPhone 5. I’m a believer in Windows Phone – I think it is a great operating system. That is completely separate from the business decisions I make.

With Windows Phone 7 already on death row, and the success of Windows Phone 8 nothing more than speculation (like this and this), I didn’t feel like WIndows Phone warranted our time…yet. I am bullish on Windows Phone. Like I said, I love the OS and the new hardware is looking pretty good.

I have maintained a wait-and-see stance on adding Windows Phone support to Icenium.

We’re Not Waiting Idle

Of course, Telerik has a lot of knowledge in Windows Phone, which means we’ve already done some research. We’ve done a proof-of-concept to learn more about what it would take to support Windows Phone, and we know what we need in order to give Windows Phone the Icenium treatment. We’ve already engaged Microsoft to work out some of the details, in the event we decide to move forward.

Over the next few weeks we’ll be watching the early adoption of Windows Phone to see what the consumer reaction is, and use that to make some decisions about how we prioritize our backlog for the remainder of the year, and early 2013.

OK, What About Windows 8?

Having worked on Windows 8 tooling before I left Microsoft, I feel like I know the app-type Formerly Known as Metro (FKM) pretty well. I’m curious to see how consumers and enterprises react to both the app-type and the new hardware. Clearly Windows 8 will be successful in the PC market – although I’m not sure how well PC users will take to the FKM style apps.

ImageFor the mobile device market, the success of the Surface with Windows RT (Surface RT) and the OEM tablet form factors will have a huge impact on the success of FKM apps on devices. If the hardware isn’t sexy, the Windows 8 tablet will suffer the same fate as Windows Phone 7.

If the Surface RT and its cousins do well with consumers (and even in the enterprise), then the FKM app-type has a shot, and it would make sense for Icenium to support it. The advantage we have is that FKM apps can be built with HTML and JavaScript, which work through a projection layer into the Windows Runtime (WinRT) – basically the exact same way Apache Cordova works (in concept), making adding FMK app support to Icenium very achievable.

Like WIndows Phone 8, I am bullish on Windows 8, and the Surface RT – I’d say I am even more bullish on Windows 8 than Windows Phone 8. I’ve already pre-ordered my Surface RT and a Windows 8 Ultrabook with a touchscreen.

Keep Your Fingers Crossed (and Buy a Surface RT)

I hope that helps you understand some of the decision making process I used for deciding what platforms to support in the initial offering of Icenium. We have aspirations to support all relevant platforms – and right now that definition excludes Windows 8 and Windows Phone 8. Let’s hope that changes.

I’d love to see a three-horse race in the mobile market.

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