Friday, 13 January 2012

The Majority Of Web Developers Are Moving To HTML5

A survey has found that 75 percent of developers are using, or plan to use HTML5 for app developement

A new survey from Evans Data has confirmed that developers continue to flock to HTML5.
Indeed, Evans Data’s latest Global Development Survey indicates that although the HTML5 standard is still a work in progress, software developers are already committed to it.

De Facto Standard

The survey of more than 1,200 developers conducted worldwide in November and December 2011 showed current use of HTML at 43 percent in North America; 39 percent in the Europe, Middle East and Africa (EMEA) region; and an even greater 58 percent in the Asia Pacific (APAC) region. Adding in those planning to use HTML5 brought the totals to over three-quarters across the regions.
“There isn’t any question about the adoption of HTML5 – it’s already the de facto standard” said Janel Garvin, CEO of Evans Data, in a statement. “There is special strength in HTML5 for mobile and cross-platform mobile apps, which is the direction the industry is moving for client devices, and that has made it extremely attractive to developers everywhere in the world. We see the most strength in Asia, a region that is generally quick to adopt new technologies.”
The survey also showed that developers are more likely to use a standalone HTML5 editor in APAC and EMEA, while North Americans prefer to use the editor in their integrated development environment (IDE). When asked about importance in the development cycle, HTML5 came in 20 percent higher on average across regions than either Flash or Silverlight.
HTML5 has caught on quickly with developers, and vendors are providing support for it in their core products. Microsoft has embraced HTML5 for its Internet Explorer browser and Windows 8 operating system.

Flash Dies

In November, Adobe announced plans to halt development of Flash for mobile browsers. In its explanation for the change in direction, Adobe cited the popularity of HTML5.

In a 9 November blog post, Danny Winokur, vice president and general manager of interactive development at Adobe, said, “However, HTML5 is now universally supported on major mobile devices, in some cases exclusively. This makes HTML5 the best solution for creating and deploying content in the browser across mobile platforms. We are excited about this, and will continue our work with key players in the HTML community, including Google, Apple, Microsoft and RIM, to drive HTML5 innovation they can use to advance their mobile browsers.”

The Evans Data Global Development Survey series is conducted worldwide twice a year. The current survey includes sections on Platform Use and Migration, Agile Development, Embedded Systems, Cloud Development, Mobile Development, Distribution Channels, Security, and Technology Adoption.

Tuesday, 3 January 2012

How to create HTML5 applications on Windows Phone thanks to PhoneGap

We will first see in this article what the added values of PhoneGap for HTML5 applications are. We’ll then discover how to create our very first project where we will retrieve the accelerometer’s values from our JavaScript code. At last, we will review a complete HTML5 gaming sample almost ported as-is to PhoneGap to use the accelerometer available on the Windows Phones.  
  1. Introduction
  2. PhoneGap: a framework filling the gap
  3. Let’s create our first PhoneGap project
  4. Getting the accelerometer’s values from JavaScript
  5. Review of a complete sample with the HTML5 Platformer game
    1. Forcing the landscape orientation
    2. Handling various resolutions
    3. Loading the levels with calls to the file system instead of using XHR
    4. Modification of the gameplay to use the accelerometer
    5. Screenshots of the result and FPS on some phones
    6. Complete Visual Studio Solution to download
  6. Conclusion

Introduction

image
The Mango update for Windows Phone came with the support of HTML5 thanks to the embedded IE9 browser. As the desktop version, the mobile version of IE9 delivers hardware acceleration through the GPU of your Windows Phone. Thus, combined with JavaScript, IE9 can now serve as a base of interesting user’s experiences usually reserved to “native code”.
The Pros of using HTML5 as a development platform is a relative promise to easily re-use parts of the code on others compatibles platforms like Android or iOS. HTML5 has then driven a lot of interests from the mobiles developers’ ecosystem during the last months.
However, even if the HTML5/CSS3/SVG & JavaScript specifications have greatly evolved during the last months, they still lack some major features to build mobile applications. Indeed, a phone or a tablet exposes specific capabilities like: GPS, accelerometer, camera, sending SMS, accessing contacts, etc.
To have access to these capabilities from the JavaScript code, the W3C has been working now for a while on what we call “Device APIs” or DAP. Unfortunately, we can consider that no implementation currently exists of those specifications as this document seems to confirm: Standards for Web Applications on Mobile: November 2011 current state and roadmap . Mozilla has started an interesting work by more or less forking those specifications via what they call Web APIs to support their Boot To Gecko project. This is then a good news as a form of implementation seems to start with an on-going discussions with the W3C. However, even if things start to move slowly, we will probably have to wait for several years before having a stable official W3C specification implemented widely on all platforms.
So the question is: what should we do in the meantime? Can HTML5 really address those scenarios?

PhoneGap: a framework filling the gap


While waiting on real standardized specifications, we don’t have the choice: we need to create some bridges between JavaScript and the native code of the targeted platform to have access to its capabilities. The idea is then the following one: taking the native languages of each platform (C#, Objective-C and Java) and creating a framework with these languages that will expose interfaces to the JavaScript developer.
This is exactly what PhoneGap is doing. Let’s take the Windows Phone case which is the main topic of this article. A Windows Phone’s PhoneGap project is simply a Silverlight application hosting the WebBrowser control (and thus IE9) as well as a Silverlight Assembly written in C# which does the job to access to the accelerometer, GPS, contacts, camera and so on. In this way, as a JavaScript developer, you will use a DLL named WP7GapClassLib.dll (the PhoneGap core runtime) without even knowing it via the usage of the code embedded in the phonegap-1.3.0.js file. This DLL contains some C# code which does calls to the Silverlight runtime available on the phone. As the runtime has access to all the capabilities of the phone, the JavaScript will do also. The JavaScript library will then act as a gateway between both worlds. Moreover, the good point of using this library is that your code will most of the time works as-is on the PhoneGap versions of Android or iOS. PhoneGap offers then an interesting form of portability.
Please note by the way that the PhoneGap support for Windows Phone is now totally complete since the recent 1.3.0 version:

At last, PhoneGap offers also another interesting service. It embeds your .js, .css, .html, .png resources inside its projects to package it as a classical application. In summary, you can use PhoneGap to package your HTML5 application for the various applications' stores. This is for instance the case of the SujiQ Windows Phone application built using this approach.

Let’s create our first PhoneGap project

Prerequisites

Here are the very first steps you need to follow:
  1. Download the Windows Phone SDK: Windows Phone SDK
  2. Download the last version of Phone (1.3.0 today) on their site: http://phonegap.com/
  3. Unzip the downloaded file 
  4. Copy the PhoneGapStarter.zip and PhoneGapCustom.zip files into \Documents\Visual Studio 2010\Templates\ProjectTemplates

File->New project

Once the previous steps are done, you will be able to create your first PhoneGap project. Start Visual Studio 2010, select the “Visual C#” templates and filter them via the “Gap” keyword. You should then see a new type of project named PhoneGapStarter:
image
Name your project “MyFirstPhoneGapProject”. Once done, you will find the files I was talking about before in the Solution Explorer:
image
You just now have to insert your HTML5 application into the “www” directory.
Here are several tips I’d like to share with you about this default project template:
- never ever touch the phonegap-1.3.0.js file if you’d like to keep a portable code on other versions of PhoneGap
- all files you will add inside the “www” directory must be set as “Content” in the properties window 
- instead of the WP7GapClassLib.dll binary file, you can add a reference to the WP7GapClassLib.csproj C# project available in the “Windows Phone\framework” directory of the downloaded PhoneGap archive. It will help you debugging or discovering the native code of the PhoneGap library if needed.
Ok, let’s now start by doing something normally impossible by default with IE9 Mango: accessing to the accelerometer’s values from JavaScript.

Getting the accelerometer’s values from JavaScript

We’re going to see here how to get the values sent back by the accelerometer (of the emulator or the real device) in a very simple way.
Open the “index.html” page and change its default body by this one:
<body>
    <h1>Accelerometer sample</h1>
    <div id="valueX"></div>
    <div id="valueY"></div>
    <div id="valueZ"></div>
</body>
We will simply use 3 <div> tags to display the current X, Y & Z values of the accelerometer.
Next step is to change the last default <script> block by this one:
<script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);

    // variable to output the current x, y & z values of the accelerometer
    var valueX;
    var valueY;
    var valueZ;

    // when PhoneGap tells us everything is ready, start watching the accelerometer
    function onDeviceReady() {
        valueX = document.getElementById("valueX");
        valueY = document.getElementById("valueY");
        valueZ = document.getElementById("valueZ");
        startWatch();
    }

    // start monitoring the state of the accelerometer
    function startWatch() {
        var options = { frequency: 500 };
        navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
    }

    // if the z-axis has moved outside of our sensitivity threshold, move the aarvark's head in the appropriate direction
    function onSuccess(acceleration) {
        valueX.innerHTML = "X: " + acceleration.x;
        valueY.innerHTML = "Y: " + acceleration.y;
        valueZ.innerHTML = "Z: " + acceleration.z;
    }

    function onError() {
        alert('onError!');
    }
</script>
Well the code is relatively self-explicit I think. The very first thing to note is that you need to wait for the “deviceready” event raised by PhoneGap to be sure to be in a stable state. You then need to subscribe to this event. In our case, we will be call-backed into the OnDeviceReady() function. This function is getting the references to the 3 <div> tags and then asks to be notified by any changes done inside the accelerometer every 500ms with the startWatch() function. The notifications will be sent to the onSuccess() function that will have access to the acceleration object containing the x, y & z values. You’ll find the complete documentation on the PhoneGap site: PhoneGap Documentation - API Reference - Accelerometer
This is all you need to do on the JavaScript side. However, to make it works, you need to specify in the project’s properties that you want to request access to the device’s sensor. The capabilities needed for the proper execution of our application are listed inside the WMAppManifest.xml file available in the “Properties” directory. By default, since 1.3.0, PhoneGap is listing the strict minimum capabilities:
<Capabilities>
  <Capability Name="ID_CAP_IDENTITY_DEVICE" />
  <Capability Name="ID_CAP_IDENTITY_USER" />
  <Capability Name="ID_CAP_LOCATION" />
  <Capability Name="ID_CAP_NETWORKING" />
  <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
</Capabilities>
It’s then up to you to add the capabilities you need for your PhoneGap application. In our case, we need to add this line:
<Capability Name="ID_CAP_SENSORS" />
To be allowed to access to the accelerometer. You’ll find the complete list of all available capabilities here:  Application Manifest File for Windows Phone
Ok, we’re logically ready to test that inside the emulator as a first phase. Press on the magical “F5” key and let’s have a look to the result:
image
By moving the virtual phone in the emulator on the right, you should see the values of the accelerometer updated. Congratulations!
You can download the complete source code of this first solution here: http://david.blob.core.windows.net/html5/MyFirstPhoneGapProject.zip

Issues with phones using French locale

If you’re testing the very same code on your phone configured to use a French local (as mine for instance! Clignement d'œil), you will have the feeling that the application doesn’t work at all…which is indeed the case. I’ve then spent some time debugging the code and I’ve discovered that the following exception was raised inside phonegap-1.3.0.js:
"Error in success callback: Accelerometer = Syntax error"
After dumping the values, I’ve seen that the error was due to a tentative of de-serialization of the following bad formatted JSON string:
"{\"x\":0,00472,\"y\":-0,19879,\"z\":-0,98115}" whereas the proper EN-US is the following one: "{\"x\":0.00472,\"y\":-0.19879,\"z\":-0.98115}"
Yes, we’re using a coma in France as a numeric separator. Clignement d'œil
2 solutions to solve this problem:
1 – The lazy one: switch your phone into EN-US (I know, this is not a solution!)
2 – Fix the problem that comes from the C# code. For that, replace the following code from the Accelometer.cs file of the WP7GalClassLib library:
/// <summary>
/// Formats current coordinates into JSON format
/// </summary>
/// <returns>Coordinates in JSON format</returns>
private string GetCurrentAccelerationFormatted()
{
    string resultCoordinates = String.Format("\"x\":{0},\"y\":{1},\"z\":{2}",
                    accelerometer.CurrentValue.Acceleration.X.ToString("0.00000"),
                    accelerometer.CurrentValue.Acceleration.Y.ToString("0.00000"),
                    accelerometer.CurrentValue.Acceleration.Z.ToString("0.00000"));
    resultCoordinates = "{" + resultCoordinates + "}";
    return resultCoordinates;
}
By this one:
private string GetCurrentAccelerationFormatted()
{
    string resultCoordinates = String.Format("\"x\":{0},\"y\":{1},\"z\":{2}",
             accelerometer.CurrentValue.Acceleration.X.ToString("0.00000", CultureInfo.InvariantCulture),
             accelerometer.CurrentValue.Acceleration.Y.ToString("0.00000", CultureInfo.InvariantCulture),
             accelerometer.CurrentValue.Acceleration.Z.ToString("0.00000", CultureInfo.InvariantCulture));
    resultCoordinates = "{" + resultCoordinates + "}";
    return resultCoordinates;
}
And the sample will now work with all locales. I’ve filled a bug on this topic here: https://issues.apache.org/jira/browse/CB-141 suggesting the same solution that will normally be shipped with the next version (2.0.0).
By the way, you’re maybe wondering how I’ve managed to debug the JavaScript part of my PhoneGap project? Well, you can simply use the wonderful jsConsole project. If you want to know more about that, please read one of my colleague’s article: jsConsole Remote Debugging in IE9 on Windows Phone Mango

Review of a complete sample with the HTML5 Platformer game

Let’s now review a more complex sample. My idea was to start from the game I’ve written before. It’s exposed in this article: HTML5 Platformer: the complete port of the XNA game to <canvas> with EaselJS . I wanted to see what I should do to make it works on the phone.
First step is to simply copy/paste the different .js, .png, .css files into the “www” directory and to mark them as “Content”. Here are the others steps to follow.

Forcing the landscape orientation

The game has to be played in landscape mode. I’ve then forced this orientation. I’ve also remove the information bar on the side (the System Tray). For that, you need to open the MainPage.xaml file and change these properties:
SupportedOrientations="Landscape" Orientation="Landscape" shell:SystemTray.IsVisible="False"

Handling various resolutions

As my main goal was to build a game that could run on the highest number of devices, I need to handle a lot of different resolutions.
For that, I’ve slightly modified the initial code of the Platformer you can download in the other article. The game is now capable on running at any resolution by applying a rescale ratio on the images and sprites to draw. Everything is being redrawn based on a specific ratio that came from the Windows Phone (800x480) which is the 100% ratio. You can test this version in your desktop browser here: HTML5 Platformer ReScale and try to dynamically resize the browser window. Moreover, if your screen resolution has a 16/9 aspect ratio, press the F11 key to play in fullscreen! The experience in this mode is really cool as you can see in this screenshot:
image
We’re letting the browser taking care of the anti-aliasing during this scaling operation. Based on the browser you’ll use, you will notice also that the performance could vary a lot related to the size of the window you’ll have. On my machine, IE9/IE10 seems relatively indifferent to the fullscreen mode or small resolutions by maintaining a stable 60 fps framerate.

Loading the levels with calls to the file system instead of using XHR

In the initial code, the .TXT files linked to the each level were stored on the web server and downloaded via XmlHttpRequest calls. As we’re now running everything client-side in offline mode, XHR local calls are not very appropriated. I’ve then replaced the initial code of the PlatformerGame.prototype.LoadNextLevel function by this one:
PlatformerGame.prototype.LoadNextLevel = function () {
    this.levelIndex = (this.levelIndex + 1) % numberOfLevels;

    // Searching where we are currently hosted
    var nextFileName = "app/www/assets/levels/" + this.levelIndex + ".txt";
    try {
        var instance = this;
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

        function gotFS(fileSystem) {
            fileSystem.root.getFile(nextFileName, null, gotFileEntry, fail);
        }

        function gotFileEntry(fileEntry) {
            fileEntry.file(gotFile, fail);
        }

        function gotFile(file) {
            readAsText(file);
        }

        function readAsText(file) {
            var reader = new FileReader();
            reader.onloadend = function (evt) {
                instance.LoadThisTextLevel(evt.target.result.replace(/[\n\r\t]/g, ''));
            };
            reader.readAsText(file);
        }

        function fail(evt) {
            console.log(evt.target.error.code);
        }
    }
    catch (e) {
        console.log("Error loading level: " + e.message);
        // Probably an access denied if you try to run from the file:// context
        // Loading the hard coded error level to have at least something to play with
        this.LoadThisTextLevel(hardcodedErrorTextLevel);
    }
};
I’ve just re-used the code available in the PhoneGap documentation: FileReader . As you can see, you have a full access to the Windows Phone file system from JavaScript with PhoneGap.
Cool tip: to help you debugging what’s really stored in the Isolated Storage of the phone or not, you should have a look to this awesome tool: IsoStoreSpy written by Samuel Blanchard.

Modification of the gameplay to use the accelerometer

Well, last part is just to mix all parts of this article to obtain the final result. For that, I’ve added the following code into the constructor of the Player object in the Player.js file:
var options = { frequency: 500 };
var that = this;

navigator.accelerometer.watchAcceleration(
    function (accelerometer) { that.moveDirectionAccel(accelerometer); },
    function () { console.log("Error with accelerometer"); }, 
    options);
Here is the function that will be call-backed during the accelerometer variations:
Player.prototype.moveDirectionAccel = function(acceleration) {
    var accelValue = -acceleration.y;

    // Move the player with accelerometer
    if (Math.abs(accelValue) > 0.15) {
        // set our movement speed
        this.direction = Math.clamp(accelValue * this.AccelerometerScale, -1, 1);
    }
    else {
        this.direction = 0;
    }
};
I’ve also added an handler on the “onmousedown” event on the canvas to jump when the user tap on the screen.

Screenshots of the result and FPS on some phones

First, let’s review the result within the Windows Phone emulator:
image
We have a framerate varying from 54 to 60 fps on my machine. On a real device, the framerate differs logically between models. Let’s take the first game level. On the LG E900, the framerate is around 22 fps. On the HTC Radar, it’s around 31 fps. On the Nokia Lumia 800, it’s around 42 fps.
DSCF4677
The gameplay could then be not very convincing in most cases. Indeed, I’m using a fullscreen canvas to draw the whole game. This is not a very good idea for the mobile limited power CPU, even if the Nokia seems powerful enough to handle this approach. A better methodology could be to cut the screen stage into various little canvas that will then be moved by modifying the CSS properties on them. This is what has been done for the HTML5 version of Angry Birds for instance. Some JS gaming frameworks start to think about handling this complexity for you. The idea would then be to code the game once with high level APIs and the framework could switch between a full frame canvas or various little canvas moved via CSS based on the performance.
Well, you’ll get it: the HTML5 gaming experience on mobile is currently just at its beginning. But its future looks very promising!

Complete Visual Studio Solution to download

You’ll find the complete source code of the HTML5 Platformer for PhoneGap here: HTML5GapPlatformer.zip

Other useful resources

Conclusion

PhoneGap offers interesting perspectives to help you writing applications on the phone. It lets you using your existing skills in JavaScript, HTML and CSS. PhoneGap won’t necessary cover all the scenarios currently available with the native development stack (Silverlight or XNA). But this could be something to have a look to if you’d like to capitalize on the HTML skills of one of your team. You will have to pay attention to properly identify the kind of project to work on.
You can also think about mixing both environments to create hybrid experiences: the main branch would be written using “HTML5” and some specific parts into native code. Using this idea, some plug-ins have been created to push a bit further the integration into the Metro UI: PhoneGap Plug-ins for Windows Phone . You’ll find for instance one of them allowing a JavaScript code to update the Tiles.
At last, PhoneGap and HTML5 could allow a relative portability to other platforms… with some limitations. But this is a vast subject with passionate debates that would need a complete dedicated article.

Thursday, 22 December 2011

The Definitive Guide To HTML5: 14 Predictions For 2012

HTML5in2012
 
 Guest contributor Ben Savage is the founder of Spaceport.io, a native Javascript and HTML5 platform for mobile game developers.
From tech titans like Zynga, Facebook, Microsoft, Google and Apple, to startups just launching, the battle lines of 2012 will be drawn across the landscape of HTML5. Below are 14 bold predictions for how HTML5 will evolve in 2012.

Welcome to a more interconnected web:
In 2012, HTML5 will be adding support for some really useful and cool APIs that allow one
website to connect to another.


For example, Zynga games on Facebook run inside of iframes. Using the new postMessage API these games will be able to communicate within the containing Facebook frame directly. Before HTML5, inter-window communication had to rely on a remote server – or use unreliable hacks.
Another exciting addition is CORS (Cross Origin Resource Sharing). This will make it much easier for different websites to share information with one another. For example, CORS will enable startups to create photo-editing services that download your photos from Facebook, let you modify them, and then re-upload them – again without having to resort to ugly hacks.

With all of the new semantic information (see Semantics and Microdata) available with HTML5, it will become much easier to create web tools that extract information from web pages. As a result, you can expect to see a plethora of new mashup services, as well as better browser modes (like readers and translators).

Web browsers will look more like iPhones
Everyone loves Apple’s iOS. Now it’s coming to the HTML5 web. In 2012 your browsers will start
sporting
push notifications, geolocation, and offline capable applications. Some browsers will likely adopt a more iOS-like user interface that will make the comparison all the more apt.

More and more applications will just be built in HTML5 instead of downloadable apps
If you’re like me, you already use web apps for email, calendars, and photo-sharing, but in 2012 more classes of applications will be HTML5 enabled. Next up, you can expect to see content creation apps like Inkscape and Illustrator emerge for HTML5 and start to catch on.

Internet Explorer & Microsoft will dramatically improve in coolness.
Internet explorer’s reputation will stop being “the browser where nothing works right” and start being “the fast browser”. Microsoft has made major investments into improving HTML5 performance that will give IE 10 a huge performance lead over competing browsers. Its hardware accelerated “canvas” will blow away all the other browsers in any speed test. Microsoft is also adding interesting ways for the HTML5 web and the desktop to work together that will really spice up its operating system. Having good support from IE will be the impetus that will really turn the tide in favor of authoring HTML5 applications.

Browser manufacturers will get into the App Store business
Taking a cue from Apple, browser manufacturers will start to realize that they are missing out by not being in the app store business. Google Chrome already has an integrated app-store as its splash page. Expect many other browsers to follow. This is actually a good thing for HTML5 application developers – it means more distribution opportunities for apps, although platform specific payment systems and platform revenue-shares will follow later on.
At least one major console game released or re-released using WebGL
In 2012, at least one AAA console game company is going to make the leap and decide to launch a 3D title on the web using WebGL instead of (or in addition to) creating a downloadable client. It might be a re-release of a well-known title (Like “Team Fortress 2″ or “Assassins Creed”), or another way to play a popular MMO (like “Eve Online” or “World of Warcraft”), or it may be an entirely new title launching for the first time.

Many more applications will use offline cache and will work offline
The offline application cache will dramatically improve the usability and speed of HTML5 apps. Querying a local database will allow applications to avoid a round-trip to the server, eliminating that laggy web-app feel that makes us all prefer native apps today.

In 2012, expect to see a few issues arise from this extended usage. You’ll lose your work by clearing your cache at least once or twice. Also expect security vulnerabilities to keep showing up that allow malicious applications to access private files stored on your computer by another
website.


HTML5 ads will become prevalent and overtake Flash ads
Website owners keen to monetize the increasingly large amount of traffic coming from iOS devices will demand HTML5 ads (rather than Flash ads). Startups will emerge to serve this market. These startups will solve the sand boxing, security, and authoring tools issues that this new market will face. Now that HTML5 is capable of doing everything that flash ads commonly do, it’s just a matter of time before they take over.

JavaScript will get a lot faster with better memory management and typed arrays
JavaScript has gotten really, really fast – it’s already among the world’s fastest scripting languages – but there is room for improvement. Google Chrome has started pushing the envelope on better memory management and garbage collection algorithms. This, combined with typed arrays, will bring JavaScript performance closer to more mature languages like Java.

Canvas will get hardware acceleration in more browsers (but no major mobile browsers)
Other browser makers will follow Internet Explorer’s lead and add hardware acceleration to their canvas implementations. Those that don’t will suffer a severe loss in mind-share. Firefox is most at-risk in this regard. If Mozilla fails to accelerate their canvas it risks being portrayed as the new IE — slow and bloated and burdened down with legacy code.

However, in 2012, no major mobile browsers will successfully roll out a hardware-accelerated canvas. We will have to wait until 2013 to start seeing that catch on.

People will play popular HTML5 games on their mobile devices from Zynga and others, but they will be very simple games
You can expect to see your friends playing games like Zynga Poker, Words with Friends, and Mafia Wars on their mobile phones, running purely in HTML5. These games will be played on both destination websites and within native applications (like the Facebook app).

However, successful HTML5 games on mobile devices will be limited to menu-based games, card games, board games, turn-based multiplayer games, and avatar customizer games. More complex and visually intensive Zynga “Ville” style games with isometric worlds or hundreds of animating sprites will not yet strike gold in 2012.

Facebook will release improved HTML5-based APIs that allow for more seamless integration with external websites
In its continued quest to be the de facto social-graph of the web, Facebook Connect will grow and expand to take advantage of new HTML5 features. This will allow even deeper and richer integration of Facebook connect with external websites and services.

Facebook will get a lot more seamlessly integrated with your desktop
Think drag-and-drop, file system access, photo synching, and widgets on your desktop. All of these features (and more) will start to blur the line between desktop and browser, bringing your social graph more closely into contact with your traditional desktop experience.

Apple will NOT fix HTML5 sound in mobile Safari
HTML5 sound used to work well in mobile Safari, back in the days iOS3. However, Apple disabled most of the API in iOS 4 and 5. It just introduces competition for iTunes — both the music store, and the App Store. In its continued fight to maintain total control over the Apple ecosystem, they will refrain from fixing HTML5 sound in 2012.

Wednesday, 21 December 2011

Microsoft updates Windows Azure cloud platform

Microsoft has released new features of its Windows Azure cloud development platform, including open source capabilities and simplified billing and management.

Developers partial to open source development will benefit from the first Windows Azure software development kit (SDK) that includes language libraries for Node.JS, with support for hosting, storage and service bus.
Microsoft is delivering an Apache Hadoop-based service for Windows Azure to bolster the platform’s big data functionality, helping customers take advantage of advanced data analytics.
“These changes will help developers build applications on Windows Azure using the languages and frameworks they already know,” said Microsoft in a blog post.

As part of efforts to make it easier to get started and manage applications on Windows Azure, the update offers a free 90-day trial and spending caps that simplify the sign-up process.

Managing cloud costs

The new Windows Azure Management Portal enables customers to view real-time usage and billing details so they can more easily control how much they use and spend on the cloud platform.Microsoft said the update offers customers greater flexibility for scaling and managing databases by increasing the maximum database size for SQL Azure from 50GB to 150GB and introducing a price cap which lowers the effective cost per gigabyte for customers with large databases.

“This change allows customers with 50GB databases and larger to continue to grow without additional costs,” said Microsoft.

Securing applications against hackers

In October, Adrienne Hall, general manager of Microsoft's Trustworthy Computing group, told Computer Weekly that Azure customers are showing that cloud implementations are moving from collaboration applications only to include mission-critical applications as well.

With less than 1% of security exploits in the first half of 2011 being against zero-day or unpatched vulnerabilities, organisations can guard against most attacks by getting the basics right, she said.
This also means that by switching to cloud-based managed services, organisations have the opportunity to transfer some of the risk of common threats to service providers, said Hall.

"Most risks are manageable, but many organisations are not doing all they can to reduce attacks. Cloud-based managed services could help with that," she said.Cloud providers, such as Microsoft, are resourced to focus on security, said Hall, and in moving the management of a portion of security functions, resources are freed up to focus on other areas of security or on different IT projects altogether.

Wednesday, 14 December 2011

Working with Media in HTML5

Unless you have been living on a remote island for the past year or so, you have probably heard the buzz and hype around HTML5. No, HTML5 will not cure most illnesses, nor will it end world hunger, but it is poised to reshape the rich Internet application landscape. With all the hype over the new HTML standard, it's important to bring the discussion back down to earth. Here are the important facts you need to know about this new HTML specification:
  • HTML5 is the first new version of the specification since 1999—the Web has changed a lot since then.
  • HTML5 will be the new standard for HTML, XHTML and the HTML DOM.
  • HTML5 provides a standard way of playing media—a key benefit  because there was no standard for playing media in a Web page without a browser plug-in, and no guarantee that every browser would support the plug-in.
  • HTML5 is still a work in progress, but most modern browsers have some HTML5 tag support.
When Silverlight 1.0 shipped in 2007, Microsoft touted its video and audio playback as primary features, and a prime reason to see Silverlight as an alternative to Flash—which is supported in one version or another on 95 percent of browsers worldwide. As of this writing, Silverlight is supported on around 75 percent of browsers worldwide, or about three of every four computers. But if you’re looking to play media and you don’t want to the hassle or the dependency of a plug-in, HTML5 is the answer.
To see the difference between using the HTML5 video tag and the traditional object tag to play media, consider the example in Figure 1.
Figure 1  The HTML Video Tag vs. the Object Tag to Play Media
  1. <section>
  2.     <h1>Using the HTML5 Video tag to play video</h1>
  3.     <video src="video1.mp4" >
  4.     </video>
  5. </section>
  6. <section>
  7.     <h1>Using the Object tag to play media using the Flash plug-in</h1> 
  8.     <object type="application/x-shockwave-flash"
  9.                data="player.swf" width="290" height="24">
  10.         <param name="movie" value="player.swf">
  11.     </object>
  12. </section>
So what’s the big deal? Both examples are simple and easy to implement. But the important point here is that because the <video> tag is a standard, there will be no question that it should be used to play media. You don’t have to guess if a browser has a certain version of a particular plug-in installed to play your media. The standard part is what’s been missing from HTML.

Supported Media Formats in HTML5

To use media in your next HTML5 application, you need to know what formats are supported. HTML5 supports AAC, MP3 and Ogg Vorbis for audio and Ogg Theora, WebM and MPEG-4 for video.
Even though HTML5 supports these media formats, however, not every browser supports every format. Figure 2 shows current browsers and the media formats they support.
Figure 2 Media Support in Current Browsers

BrowserVideo FormatsAudio Formats
 Ogg TheoraH.264VP8 (WebM)Ogg VorbisMP3Wav
Internet ExplorerManual install9.0Manual installNoYesNo
Mozilla Firefox3.5No4.0YesNoYes
Google Chrome3.0No6.0YesYesYes
SafariManual install3Manual installNoYesYes
Opera10.50No10.60YesNoYes

Using the Video Tag

To play a video in an HTML5 page, just use the <video> tag, as shown here:
  1. <video src="video.mp4" controls />
The src attribute (http://www.w3.org/TR/html5/video.html#the-source-element) sets the name or names of the video to play, and the control’s Boolean switch dictates whether the default playback controls displays. You can also use two other Boolean properties—autoplay and loop—when setting up the video tag. Figure 3 lists each property attribute and its value.
Figure 3 Video Tag Properties

AttributeValueDescription
 AudioMutedDefines the default state of the audio. Currently, only muted is allowed.
 AutoplayAutoplayIf present, the video starts playing as soon as it’s ready.
 ControlsControlsAdds Play, Pause and Volume controls.
 HeightPixelsSets the height of the video player.
 LoopLoopIf present, the video will start over again every time it finishes.
 PosterurlSpecifies the URL of an image representing the video.
 PreloadPreloadIf present, the video is loaded at page load and is ready to run. It is ignored if Autoplay is present.
 SrcurlThe URL of the video to play.
 WidthPixelsSets the width of the video player.

The following code shows a few of the key properties on the video player in a common scenario that includes setting the height and width, autoplay, loop and controls properties, which will display the play, pause and volume controls as well as a fallback error message.
  1. <video src="video.mp4" width="320" height="240" autoplay controls loop>
  2.     Your browser does not support the video tag.
  3. </video>
You can also set the specific MIME typeusing the type attribute and codec in the source element. These examples use the type attribute to set the MIME type and the encoding of the media:
  1. <!-- H.264 Constrained baseline profile video (main and extended video compatible)
  2.   level 3 and Low-Complexity AAC audio in MP4 container -->
  3. <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  4. <!-- H.264 Extended profile video (baseline-compatible) level 3 and Low-Complexity
  5.   AAC audio in MP4 container -->
  6. <source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'>
You can set properties in either HTML or JavaScript. The following code shows how to set the Boolean controls property in HTML and JavaScript.
<!-- 3 ways to show the controls -->
<video controls>
<video controls="">
<video controls="controls">
// 2 ways to show controls in JavaScript
video.controls = true;
video.setAttribute
       ('controls',
        'controls');
When you don’t know whether a browser will render the page, you need a fallback mechanism to play your media. All you do is list the video formats you have rendered your video in, and the browser plays the first one it supports. You can also add text as a last resort to let the user know that the browser being used doesn’t support native HTML5 playback of video. The following code includes multiple video sources as well as a fallback message indicating no HTML5 support.
  1. <video controls>
  2.     <source src="video1.mp4" />
  3.     <source src="video1.ogv" />
  4.     <source src="video1.webm" />
  5.     <p>This browser does not support HTML5 video</p>
  6. </video>
If you want to make sure your video plays, you can include the object tag to play a Flash version as well, like so:
  1. <video controls>
  2.     <source src="video1.mp4" />
  3.     <source src="video1.ogv" />
  4.     <source src="video1.webm" />
  5.     <object data="videoplayer.swf">
  6.         <param name="flashvars" value="video1.mp4">
  7.         HTML5 Video and Flash are not supported
  8.     </object>
  9. </video>
You can also use JavaScript to check if a video format is supported by checking the canPlayType property, as follows:
  1. var video = document.getElementsByTagName('video')[0];
  2. if (video.canPlayType)
  3.    { // video tag supported
  4. if (video.canPlayType('video/ogg; codecs="theora, vorbis"'))
  5.       { // it may be able to play}
  6.         else
  7.       {// the codecs or container are not supported
  8.         fallback(video);
  9.   }
  10. }
If you want to do something more expressive than the simple fallback text, you can use the onerror event listener to pass the error to:
  1. <video src="video.mp4"
  2.        onerror="fallback(this)">
  3.        video not supported
  4. </video>
Using the poster property, you can specify the URL of an image to show in place of the video on the form. Usually you’re showing either a list of videos or a single video on a form, so having an easy way to show a preview of the video in the form of an image delivers a better user experience. Here is the poster property in action:
  1. <video src="video1.mp4" poster="preview.jpg" </video>
Finally, by using a bit of JavaScript and basic HTML, you can create a more interactive video player. Figure 4 shows how to add a video player to a form with JavaScript and how to respond to user input to the control.
Figure 4  Interacting with Video in JavaScript
  1. var video = document.createElement('video');
  2. video.src = 'video1.mp4';
  3. video.controls = true;
  4. document.body.appendChild(video);
  5. var video = new Video();
  6. video.src = 'video1.mp4';
  7. var video = new Video('video1.mp4')
  8. <script>
  9.     var video = document.getElementsByTagName('video')[0];
  10. </script>
  11. <input type="button" value="Play" onclick="video.play()">
  12. <input type="button" value="Pause" onclick="video.pause()">
For a complete list of events and capabilities for playing video, check out this section of the spec at http://www.w3.org/TR/html5/video.html#playing-the-media-resource.

Using the Audio Tag

Using the audio tag is much like using the video tag: you pass one or more audio files to the control, and the first one the browser supports is played.
  1. <audio src="audio.ogg" controls>
  2.  Your browser does not support the audio element.
  3. </audio>
Figure 5 lists the properties available in the audio tag. The control doesn’t need to display like a video player, so properties like height, width and poster are not included.
Figure 5 Audio Tag Properties

AttributeValueDescription
 AutoplayautoplayIf present, the audio starts playing as soon as it’s ready.
 ControlscontrolsControls, such as a play button, are displayed.
 LooploopIf present, the audio starts playing again (looping) when it reaches the end.
 PreloadpreloadIf present, the audio is loaded at page load, and is ready to run. It’s ignored if autoplay is present.
 SrcurlThe URL of the audio to play.

As with the video tag, you can pass multiple files to the audio tag and the first one that is supported will play. You can also use a fallback message when the browser doesn’t support the audio tag, like this:
  1. <audio controls autoplay>
  2.    <source src="audio1.ogg" type="audio/ogg" />
  3.    <source src="audio1.mp3" type="audio/mpeg" />
  4.     Your browser does not support the audio element.
  5. </audio>

Summary

HTML5 is the next standard for the Web, and depending on the browsers you’re targeting, you can start using some of the new tags, such as audio and video, right now. Be cautious when using HTML5, however, because not every browser supports the new tags, and even if one does, it might not support every media format. If you’re using a modern browser that does support HTML5, you still need to do the extra work to process your media in all formats to ensure user success. Here are some great Web resources that provide browser support information as well as all the other information you need to ensure HTML5 media success: