Category Archives: HTML5

Social Online Games Programming (Part 5) New Azure Toolkit

Previous Post
Next Post

Two weeks ago, a new version of Windows Azure Toolkit for Social Games was released. See @ntotten posts:

Windows Azure Toolkit for Social Games Version 1.1.1
Windows Azure Toolkit for Social Games Version 1.1

The new version implements two simple HTML5 games: tic-tac-toe and four-in-a-row, backed up by ASP.NET MVC views, WCF Web API services, ACS federated security, and Azure Storage. You can play them online at:

I think this is a more clear example than the previous one (Tankster) that was great but a bit overwhelming ;-). Let’s dive into some implementation details of this new example.

Totten wrote:

The biggest change we have made in this release is to separate the core toolkit from the Tankster game. After we released the Tankster sample game we received a lot of feedback asking for a simpler game that developers could use to learn. To meet this need we developed two simple games, Tic-Tac-Toe and Four in a Row, and included in the toolkit. The Tankster game is now available separately as a sample built on top of the toolkit.

While the new games included in the toolkit are much simpler than Tankster, they still show the same core concepts. You can easily use these samples as a starting point to build out any number of types of games. Additionally, you will find that many of the core components of the game such as the leaderboard services, game command services can be used without any modification to the server side or client side code.

In my previous post, I mentioned a minor but important change in game action processing: any game logic was removed from server code. Adopting this approach, you can write new games without changing the ASP.NET MVC code. You still can add server side code if you want (to have more control over the actions, to avoid player cheating, etc..) but it is interesting to have a base code with game-agnostic code.

Opening the solution in Visual Studio, you will find Javascript files used by the two games. You can write a new game, reusing these files:

The games are implemented as areas:

You could add new games and publish them as NuGet packages.

Visually, the client Javascript code is organized as:

Each game X (TicTacToe, FourInARow, yours) has:

XGame: the game logic

XBoard: to draw board on canvas and to detect click events on it

XViewModel: containing the player and other data to be used at view rendering (the example uses knockout.js, an MVC in Javascript)

XController: to process new events and to coordinate the above elements

The generic part:

UserService: methods related to users: login, get friends, etc.

GameService:  play moves, receives new moves, other actions.

ServerInterface: Ajax calls (using GET, POST, JSONP, Azure storage…) that are used by the implemention of User and Game Service.

Topics for next posts: analyze the Javascript code, the use of Canvas, Javascript tests using QUnit, communication with server using Ajax, change the Game Service (Javascript) to use a Node.js server.

Keep tuned!

Angel “Java” Lopez

Metro Applications (1) My First Blank Application

This week, I started to write a simple Metro Application for Windows 8, using HTML5/Javascript. It’s a customer project, and it’s a new world for me. I want to present in this post the minimal application.

Using a Windows 8 with Visual Studio 2011 Preview, you have these initial Javascript Metro application choices (you could write Metro applications with C++, C#, VB.NET, too):

If you don’t have VS 2011, you can download the generated solutions from my GitHub repo:

This is the solution of a Blank Application:

Notice the winjs folder, with js files. This is the new namespace we can use in Metro apps. Detailed info:

Windows Library for JavaScript reference

And there is a package manifest file: it’s describe the capabilities of the application (i.e: it can access Internet, it expose the search contract, etc…).

The default.html code:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script src="/winjs/js/base.js"></script>
    <script src="/winjs/js/wwaapp.js"></script>
    <!-- BlankApp references -->
    <link rel="stylesheet" href="/css/default.css" />
    <script src="/js/default.js"></script>

The ui-dark.css is used. This is the “black style” you usually see at Metro apps.

The section “WinJS references” refers the javascript files that makes the WinJS namespace. According to the WinJS documentation:

When you reference these JavaScript files in your app, you must add the references in the following order:

  • base.js
  • wwaapp.js (after base.js)
  • ui.js (after base.js)
  • binding.js (after ui.js)
  • res.js (after ui.js)
  • animations.js (after ui.js)
  • controls.js (after animations.js)
  • uicollections.js (after animations.js)

The /js/default.js is for your application/page: you can adapt it to put your own code, new namespaces definitions. You can add other javascript files, too.

Next steps: explore these Javascript files, dissecting implementation; research and use concepts like navigation, declarative binding, and more.

Keep tuned!

Angel “Java” Lopez

Windows 8 and WinRT: Links, News and Resources

This week Windows 8 was unveiled and introduced into society, at Build Conference. Some links I found interesting about Windows 8, Metro applications, WinRT and .NET programming.

WinRT demystified – Miguel de Icaza

Building Windows 8 – Site Home – MSDN Blogs

Build Conference

Some Thoughts on Windows 8

Sessions at BUILD Day 2 and Windows 8

WinRT and .NET in Windows 8

Bye Bye Brain, first game on Windows 8

The final days of Adobe Flash

Windows Developer Preview Metro style app samples
The Windows Developer Preview Samples Gallery contains a variety of code samples that exercise the various new programming models, platforms, features, and components available for the BUILD conference.

Using WinRT from .NET

WinRT is Replacing Win32

Build 2011: What Is WinRT, and Is Silverlight Dead?
The Windows Runtime library (WinRT) is the principal provider of system services for applications in Windows 8 that will be designed to incorporate the new "Metro" style

Functional Fun: Windows Runtime – Dial in the right expectations before reading up

InfoQ: WinRT: An Object Orientated Replacement for Win32
User interfaces in C++ will be written primarily in XAML.
Overlapping Windows No Longer Exist <— I remember Windows 1.0 😉
Under WinRT all APIs are exposed as objects that C# and VB can consume directly.
The fourth major language for Windows 8 is JavaScript.
All Metro Applications Must be Digitally Signed.

Sinofsky outlines the Windows 8 vision | News | TechRadar UK

Best place to discuss Windows 8

Metro style browsing and plug-in free HTML5

Experiencing Windows 8 touch on Windows 7 hardware

Welcome to Windows 8 – The Developer Preview

JAPF » Blog Archive » BUILD: WinRT, Silverlight, WPF, XAML

Building real-time web apps with WebSockets using IIS, ASP.NET and WCF | BUILD2011 | Channel 9

A bad picture is worth a thousand long discussions. « Doug Seven

Internet Explorer 10 Metro will not support Flash, Silverlight – Tech Products & Geek News |

C#er : IMage: Windows 8: What you Need to Know

"What’s New in the .NET Framework 4.5 Developer Preview" (and Yield is coming to VB.Net!) – Greg’s Cool [Insert Clever Name] of the Day

Guide to Installing and Booting Windows 8 Developer Preview off a VHD (Virtual Hard Disk)

A few facts about Microsoft’s new Windows Runtime « Tim Anderson’s ITWriting

OK, so I think HTML/JS for Metro apps is a good idea « codeface

I know what you’re thinking, and you’re wrong. « Doug Seven
Metro, Silverlight, .NET

Microsoft to developers: Metro is your future | ZDNet

Microsoft Unveils ‘Reimagined’ Windows 8 at Build Event — Visual Studio Magazine

Welcome to Windows 8 – The Developer Preview – Building Windows 8 – Site Home – MSDN Blogs

Delivering fast boot times in Windows 8 – Building Windows 8 – Site Home – MSDN Blogs

Windows 8 will feature Hyper-V guest OS machine virtualization | ExtremeTech

"A sort of PC": how Windows 8 will invade tablets (and why it might work)

Improving our file management basics: copy, move, rename, and delete – Building Windows 8 – Site Home – MSDN Blogs

My Links

Angel "OMGC++Again" Lopez

Social Online Games Programming (Part 4) Processing arbitrary Game Actions

Previous Post
Next Post

There is a new release of Windows Azure Toolkit for Social Games:

Let examine a key change in this version. There is a new entry at Tankster.GamePlay\Services\IGameService.cs:

[WebInvoke(Method = "POST", UriTemplate = "command/{gameId}")]
HttpResponseMessage Command(Guid gameId, HttpRequestMessage request);
[WebInvoke(Method = "POST", UriTemplate = "command/v2/{gameId}")]
HttpResponseMessage Command2(Guid gameId, HttpRequestMessage request);

There are TWO entry points to send game commands from client. Why? Having two URIs the server can be used by old clients and new ones. Note the “v2” in the UriTemplate.

The new Command2 (partial) code at implementation (GameService.cs):

// Add gameAction
var gameAction = new GameAction
    Id = Guid.NewGuid(),
    Type = commandType,
    CommandData = commandData,
    UserId = this.CurrentUserId,
    Timestamp = DateTime.UtcNow
// Cleanup game actions lists
for (int i = 0; i < game.GameActions.Count(); i++)
    if (game.GameActions[i].Timestamp < DateTime.UtcNow.AddSeconds(-10))
return SuccessResponse;

If you compare the old code (Command method) with the above code, the main difference is:

– The server doesn’t manage the logic of “who is the next player in turn”

– The server doens’t distribute the received command via a GameActionProcessor

And another change: game action type is an int, now. In the previous release, it was an enum, reflecting a fixed set of action types.

It still updates the game status blob adding the new game command (it could be a chat message, or a new shot). In this new way, THE SERVER CODE is more independent from game logic: the client code has the responsibility of select the next player. The notion of turn is leave to game client development. Now, the server code could be used for other multi-players games. Yes, we could have our own Social game! 😉

Windows Azure and worker/web roles are in charge of federated authentication, the formation of  new games, etc. But the engine is more “game agnostic” in this new release.

The client code sends commands:


1- Client code sends a new Game Action in JSON (i.e.: shot information (position, angle, force)).

2- A web role instance receives the Game Action and updates the list of actions in the corresponding game blob status (saving the actions of the last 10 seconds)

3- The other players are polling the game status, until they notice a new game action that implies turn change.

Client code could manage the case of timeout of its player, or the “going offline” of one the other browsers.


– Server code is more generic, and it could be used for other games


– The client code could be cheated (no server control, validation over game actions)

– More complexity (turn logic, timeout management, offline and latency issues, cheat control) at client code.

The litmus test: implementing a new game using the same server code. Some points to polish: skirmish mode is still hardcoded to a maximum of 5 players; the 10 seconds windows for game actions is arbitrary. Possible solutions: each game client code creates a new game (waiting for other players) specifying the minimum, maximum number of players and a timeout in seconds, and time window for game action status.

But remember, the example code is still in beta. A new version is coming.

Keep tuned!

Angel “Java” Lopez

Social Online Games Programming (Part 3) Tankster, Blob Storage and JSONP

Previous Post
Next Post

In my previous post I wrote about the Windows Azure Social Gaming Toolkit, and its example multi-player online game Tankster. See:

There are two interesting posts by @ntotten about the inner guts of the game:

Architecture of Tankster – Introduction to Game Play (Part 1)
Architecture of Tankster– Scale (Part 2)

It’s worth to mention Nathan’s text here:

Before we begin with an explanation of the implementation, it is important to know what our goals where for this game. We had three primary goals when building this game.

  1. The game must scale to handle several hundred thousand concurrent users.*
  2. The architecture must be cost effective.
  3. The architecture must be flexible enough for different types of games.

* This is the goal, but there are still some known limitations in the current version that would prevent this. I will be writing more about that later.

Now, I want to write about the use and implementation of blob storage in Tankster.

Why to use blob storage? If you play Tankster in practice mode, the Javascript client doesn’t use the Azure backend. Javascript can access web role and blob storage via Ajax/JSON calls. But in multi-player game (there is one kind of game, named Skirmish), each player client code polls the blob storage to get the game status (tank shots, chat messages, other status). But again, why blob storage? There are money reasons (cost of each access to Web Role service API vs. cost of read a blob), but I don’t know about Azure prices (you know, MVPs don’t touch the money ;-). But there is another reason: to spread the workload, given some air to web role instances.

There is an AzureBlobContainer class in Tankster.Common library project:

public class AzureBlobContainer<T> : IAzureBlobContainer<T>
    private readonly CloudBlobContainer container;
    private readonly bool jsonpSupport;
    private static JavaScriptSerializer serializer;
    public AzureBlobContainer(CloudStorageAccount account)
        : this(account, typeof(T).Name.ToLowerInvariant(), false)
    public AzureBlobContainer(CloudStorageAccount account, bool jsonpSupport)
        : this(account, typeof(T).Name.ToLowerInvariant(), false)
    public AzureBlobContainer(CloudStorageAccount account, string containerName)
        : this(account, containerName.ToLowerInvariant(), false)


The class use generics. Type T could be a Game, GameQueue or another .NET type. You can reuse this class in other projects: it’s “game agnostic” code. The many constructors add flexibility for testing purpose.

This is the code to save a typed object to a blob:

public void Save(string objId, T obj)
    CloudBlob blob = this.container.GetBlobReference(objId);
    blob.Properties.ContentType = "application/json";
    var serialized = string.Empty;
    serialized = serializer.Serialize(obj);
    if (this.jsonpSupport)
		serialized = this.container.Name + "Callback(" + serialized + ")";

The object (type T) is serialized to JSON. AND not only JSON: note that a there is a Callback (you could remove this part if you don’t need this feature in your project). Then, a game object is saved as (I stolen …errr… borrowed 😉 this code from Nathan’s post):


Why the callback? To support JSONP:

JSONP or “JSON with padding” is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from cannot normally connect to or communicate with a server other than An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

If you are a newbie to JSON and JSONP, this is a short tutorial/example using JQuery (the same library used by Tankster client code):

Cross-domain communications with JSONP, Part 1: Combine JSONP and jQuery to quickly build powerful mashup

But (you know, there is a “but” in every software project 😉 Azure blob storage doesn’t support the JSONP URL (that has a randomly generated callback id):

Query JSON data from Azure Blob Storage with jQuery

There is a proposed solution in that Stack Overflow thread. Agent Maxwell Smart would say: ah! the “old trick” of having the callback in the blob!


You can read a more detailed description of problem/solution with example code at @woloski’s post (good practice Matthew! write a post!):

Ajax, Cross Domain, jQuery, WCF Web API or MVC, Windows Azure

One problem to point: note that the callback name is “hardcoded” in blob storage. The gamesCallback present in game status blob should be the name of a global function. But you can change the blob text to whatever valid Javascript code.

And the client code? You can study the gskinner code at Tankster.GamePlay web project, under src\ui\net\ServerDelegate.js:

(function (window) {

    var ServerDelegate = function () {
        throw new Error('ServerDelegate cannot be instantiated.');

    var p = ServerDelegate;

    p.BASE_API_URL = "/";
    p.BASE_BLOB_URL = "";
    p.BASE_ASSETS_URL = "";
    p.load = function (type, data, loadNow) {
        var req;
        if (p.CLIENT_URL == null) {
            p.CLIENT_URL = window.location.toString();

There is an interesting switch:

switch (type) {
    //Local / config calls
    case 'strings':
        req = new ServerRequest('locale/en_US/strings.js',
		   null, 'jsonp', null, 'stringsCallback'); break;
    //Game calls
    case 'endTurn':
        req = new ServerRequest(apiURL+'Game/EndTurn/',
		    null, 'xml'); break;
    case 'leaveGame':
        req = new ServerRequest(apiURL+'Game/Leave/',
		    {reason:data.reason}, 'xml', ServerRequest.POST); break;
    case 'playerDead':
        req = new ServerRequest(apiURL+'Game/PlayerDead/',
		    null, 'json'); break;
    case 'gameCreate':
        req = new ServerRequest(apiURL+'Game/Queue', data,
		    'xml', ServerRequest.POST); break;
    case 'usersGame':
        req = new ServerRequest(blobURL+'sessions/'+data,
		    null, 'jsonp', null, 'sessionsCallback'); break;
    case 'gameStatus':
        req = new ServerRequest(blobURL+'games/'+data,
		    null, 'jsonp', null, 'gamesCallback'); break;
    case 'gameQueueStatus':
        req = new ServerRequest(blobURL+'gamesqueues/'+data,
		    null, 'jsonp', null, 'gamesqueuesCallback'); break;
    case 'notifications':
        req = new ServerRequest(blobURL+'notifications/'+data,
		    null, 'jsonp'); break;

    //User calls
    case 'verifyUser':

See the ‘gameStatus’ polling: it uses ‘jsonp’ as format. My guess: the ‘gamesCallback’ parameter is not needed: you can use any other name, the function to call resides in the blob content.

I think there are alternatives to game status. The blob reflects the Game entity (see Tankster.Core\Entities\Game.cs). But it could be implemented in two blobs by game:

– One, having the initial status (players, positions,etc…) and the list of ALL the history of the game (think about to implement a chess or go game, you need to save the history).

– Another one, having the “news” (last 10 seconds of game actions). So, the data to poll should be shorter.

The price to pay: web role service should update both. But that update only occurs when a player sends a move (shot, chat…). The poll of game status occurs in every client, triggered by a repeated timeout. Actually, the game blob keeps the last 10 seconds actions AND initial status, weapons, etc…. Each client polls that info. In case a client disconnects and reconnects, it could poll the “complete game” blob to be in sync again.

The separation of that info in two blobs should improve the scalability of the solution. But you know: premature optimization is the root of all evil ;-). If you take that way of store and retrieve games, you should run some stress or/and load tests to have a really measure of such decision impact.

More Tankster code analysis, patterns, and social game dev in general: coming soon.

Some links:

WAT is to Social Gaming, as Windows Azure is to… | Coding4Fun Blog | Channel 9

Thanks! They mention my post 😉

Episode 52 – Tankster and the Windows Azure Toolkit for Social Games | Cloud Cover | Channel 9

Microsoft tailors Azure cloud services to social game developers | VentureBeat

Windows Azure Toolkit for Social Games Released to CodePlex – ‘Tankster’ Social Game Built for Windows Azure

Tankster, a Social Game Built for Windows Azure | Social Gaming on Windows Azure | Channel 9

Social Gaming on Windows Azure | Channel 9

Build Your next Game with the Windows Azure Toolkit for Social Games

Microsoft delivers early build of Windows Azure toolkit for social-game developers | ZDNet

Keep tuned!

Angel “Java” Lopez

Social Online Games Programming (Part 2) Tankster and Windows Azure Toolkit For Social Games

Previous post
Next post

Yesterday, July 20th, Microsoft released a preview version of Windows Azure Toolkit for Social Games, and published a beta version (with code) of a first demo game.

You can download the code from Codeplex:

You can play the game at:

The current solution main projects:

Tankster.GamePlay is a Web Role. The only worker role is Tankster.WorkerRole. Tankster.Core is a class library. There are interesting code at Tankster.Common: Azure utilities to access repositories, a job engine; all its code is game-agnostic.

These are my first short comments about the code and implemented features (remember, is a beta! Some of these features/implementations could change in the next release):

– Client technology: HTML5, Javascript, EaselJs (for canvas programming).
– Server technology: ASP.NET MVC 3, some Razor test views (interesting topic: how to test the game without the REAL game), WCF Web API (another interesting topic to discuss: alternative technologies to received the game activity)
– There is a client game model and entities in Javascript. See src/model, src/game.

– There is a server game model (see Tankster.Core class library project)

– You can play in single player mode, but you can choose multi-player online. Then, the game uses ACS Portal to login using Federated Authentication:

– The client code resides in a single page: index.html (with lot of referenced javascript files)
– Client code sends JSON data (commands) to WCF Web API endpoints, using Ajax/JQuery. There are services published, exposing a REST-like interface


– Most of the game activity is send to game/command service. The service updates the game status residing in a blob at Azure Storage. Code excerpt:

// Add gameAction
var gameAction = new GameAction
    Id = Guid.NewGuid(),
    Type = commandType,
    CommandData = commandData,
    UserId = this.CurrentUserId,
    Timestamp = DateTime.UtcNow
// Cleanup game actions lists
for (int i = 0; i < game.GameActions.Count(); i++)
    if (game.GameActions[i].Timestamp < DateTime.UtcNow.AddSeconds(-10))

– The game status is polled by javascript clients from blob storage. In this way, the ASP.NET MVC web role has less workload.

– The blob resides in the same domain, so no cross-domain JSON call is needed. But the game is prepared to use cross-domain Ajax call, replacing the XmlHttpRequest object by a Flash component.

– The Skirmish game mode (five players in a game) is made queuing the new players in a Game Queue, managed at worker role.

– The Statistics are processed at worker role: some game actions are sent to Azure queue, so the statistics process doesn’t disturb the client game.

– User status, Game status, Skirmish Game Queue status are blobs.

– Statistics data uses SQL Azure.

– There only worker role use a Job Engine to process many tasks, example:

// Game Queue for Skirmish game
    .SetupContext((message, context) =>
         context.Add("userId", message.UserId);
        new SkirmishGameQueueCommand(userRepository,
            gameRepository, workerContext))

There are a lot of points to comment and discuss, feed for upcoming posts. Surely, the solution will evolve and new versions will be published (this week? next week?). But it is interesting to have a published game online AND the code to analyzes it.

Keep tuned!

Angel “Java” Lopez

HTML5: Links, News and Resources (1)

According to Wikipedia:

HTML5 is a language for structuring and presenting content for the World Wide Web, a core technology of the Internet. It is the fifth revision of the HTML standard (originally created in 1990 and most recently standardized as HTML4 in 1997[1]) and as of June 2011[update] was still under development. Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers etc.). HTML5 is intended to subsume not only HTML4, but XHTML1 and DOM2HTML (particularly JavaScript) as well.[1]

We are no more in Kansas, Dorothy!

And yes! I have a collection of links related to HTML5, too ;-). These are my recent selections:

InfoQ: HTML5 and the Dawn of Rich Mobile Web Applications

Code & Beyond: Recursos sobre HTML5 (Spanish Text, English Links)

InfoQ: Tomorrow’s Tech Today: HTML5

The ultimate HTML5 resource guide | Webdesigner Depot

Build Web applications with HTML 5

How to create offline HTML5 web apps in 5 easy steps |

Free HTML5 Tutorials

InfoQ: Mobile HTML 5.0

Back to Basic – Writing meaningful, accessible and semantic markup in Html5 – Kazi Manzur Rashid’s Blog

15 Excellent Step by Step HTML5 Website Coding Tutorials | Web Designer Aid

How to Create an HTML5 3D Engine

HTML5, Viewports, CSS3 y otras yerbas

24 ways: “Probably, Maybe, No”: The State of HTML5 Audio

MediaElement.js – HTML5 video player and audio player with Flash and Silverlight shims

Why Microsoft has made developers horrified about coding for Windows 8

YouTube – Isogenic Engine: HTML5 Canvas Isometric Game Engine

Automatoon- Easy Animation For The Web!
It uses Clojure at server

Chris Love’s Official ASP.NET Blog : Windows 8: I Don’t Think I Could Be More Excited

Microsoft Delivers Internet Explorer 10 Platform Preview 2

html5-canvas-graphics – Sample graphics using the HTML5 canvas element – Google Project Hosting

Using the HTML5 Canvas Tag

Using Clojure, NoSQL Databases and Functional-Style JavaScript to Write Gext-Generation HTML5 Apps

Ajaxian » An Implausibly Illustrated Introduction to HTML5 Web Workers

Google Code Blog: HTML5 Rocks!

Infografía de HTML5: Análisis y características

Build Web applications with HTML 5

Google Swiffy
Swiffy converts Flash SWF files to HTML5, allowing you to reuse Flash content on devices without a Flash player (such as iPhones and iPads).

GameSalad – Game creation for everyone ™ – GameSalad Arcade

Introducing SkyDrive for the modern web, built using HTML5


My Links:

More links are coming soon. Keep tuned!

Angel “Java” Lopez