Monthly Archives: July 2011

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

Git: Links, News, Resources (1)

I’m used to be an SVN guy. This year, I started to use Git in customer projects, and now I have some of my personal projects at GitHub. These are some of the links I collected about Git.

Git is a distributed revision control system with an emphasis on speed.[3] Git was initially designed and developed by Linus Torvalds for Linux kernel development. Every Git working directory is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on network access or a central server. Git’s current software maintenance is overseen by Junio Hamano. Git is free software distributed under the terms of the GNU General Public License version 2.

Pro Git – Pro Git Book
How to use git without rage

C# Development and TDD: Combining TDD kata with git branching and merging

A few git tips you didn’t know about

An Intro to Distributed Version Control | I am Zef

If Version Control Systems were Airlines | The Changelog

Git Community Book

Easy version control with git

Persistent Trees in git, Clojure and CouchDB « EclipseSource Blog

Git’s guts: Branches, HEAD, and fast-forwards

Git guts: Merging and rebasing

YouTube – Tech Talk: Linus Torvalds on git

Git Evangelism

git-fundamentals-in-30-minutes-or-less.pdf (application/pdf Object)

Git for Computer Scientists

Git Evangelism: Branch remotos en git, dos pasos

Start a New Branch on your Remote Git Repository | Zorched / One-Line Fix

Help.GitHub – Import from Subversion

Git for Personal Projects | Javalobby

Trabajando con GIT, introducción al uso de los branch y git-completion.bash

Git On Windows Plain Introduction

Fukyo’s Blog: Git For Windows Developers

How I Turned Down $300,000 from Microsoft to go Full-Time on GitHub

Git is Inconsistent

Git tooling for .NET developers – Krzysztof Kozmic – – Just the Tasty Bits

A successful Git branching model

Mercurial as a Git client | IDisposable Thoughts

Git vs. Mercurial

Working with Remote Branches on GitHub

Why is Git telling me “Your branch is ahead of ‘origin/master’ by 11 commits.” and how do I get it to stop?

My Links

Keep tuned!

Angel "Java" Lopez

Domain-Driven Design: Links, News, Resources (1)

More than four years (!) ago, I wrote down a list of DDD resources:

Domain-Driven Design Resources

Now, it’s time to publish a new (partial) list of resources. First, Wikipedia definition:

Domain-Driven Design

Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts.[1] The premise of domain-driven design is the following:

  • Placing the project’s primary focus on the core domain and domain logic
  • Basing complex designs on a model
  • Initiating a creative collaboration between technical and domain experts to iteratively cut ever closer to the conceptual heart of the problem.

Domain-driven design is not a technology or a methodology. DDD provides a structure of practices and terminology for making design decisions that focus and accelerate software projects dealing with complicated domains.

The term was coined by Eric Evans in his book of the same title.[2]

My recent links:

Domain-Driven Design Community

Skills Matter : DDD eXchange 2011: Udi Dahan on Domain Model

RESTful SOA or Domain-Driven Design – A Compromise?

Review: Microsoft N Layer App Sample, Part IV-IoC FTW – Ayende @ Rahien

Aggregate | Domain-Driven Design Community

Services in Domain-Driven Design | Jimmy Bogard’s Blog

Sample Application First Steps

Composition Patterns « Caminao’s Ways

Skills Matter : DDD eXchange 2011: Patrik Fredriksson on DDD

Skills Matter : DDD eXchange 2011 10-06-11

Skills Matter : In The Brain of Greg Young: CQRS, not just f

Domain Drive Design N-Layered .NET 4.0 Architecture Guide

What is Domain Driven Design? – Jak Charlton – Insane World – – Just the Tasty Bits

Eben Roux | Aggregate Roots vs. Single Responsibility (and other issues)

Eben Roux | DDD != Aggregate Root!3d-AR.aspx

Eben Roux | Natural Aggregates vs Synthetic Aggregates

Coding Instinct: Queries & Aggregates & DDD

Repository is Dead: Long Live Repository | Greg Young

domaindrivendesign : Message: What is wrong with aggregate roots?

DDD: Specifications, Language, and Locality | Greg Young

Domain Driven Design with Spring and AspectJ – Java Code Geeks

Objects_of_Value_KevlinHenney.pdf (application/pdf Object)


HunabKu: Repository or DAO?: Repository

Example: TDD, DDD, CQRS, Service Bus, Dependecy Injection, Logging, HTTP RPC, Data Access Abstraction, Custom ORM, Composite UI

JavATE – Welcome to JavATE The domain driven framework

ndddsample – Google Code


Bastion DDD Java Framework

Sharp Architecture – S#arp Architecture

NerdDinner with Fluent NHibernate Part 1 – The domain model

From CRUD to Domain-Driven Fluency

Think DDD

My links:

Keep tuned!

Angel “Java” Lopez

Game Development: Links, News, Resources (1)

Next Post

Recently, I posted about social games programming:

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

I’m a link collector (a curator?). These are my recent game development related resources discoveries:

Windows Azure Toolkit for Social Games

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

Zynga, the Latest Cloud Computing Success | – Cloud Computing Community

YouTube – ‪T-Mobile Angry Birds Live – Behind The Scenes

YouTube – ‪T-Mobile Angry Birds Live

Gamasutra – News – Hawkins: ‘The Browser Is The Platform Of The Future’

HTML5 canvas awesomeness – games roundup – Red Team Design

La industria IT y de videojuegos porteños viajan a San Francisco buscando negocios

Games are an Abstraction of Concepts and Reality | Kapp Notes

Which game engine is compatiable with Visual Studio 2010 Ultimate and Silverlight? – Game Development – Stack Exchange

tools – How can I develop Flash games without expensive software? – Game Development – Stack Exchange

isometric – ActionScript 3 framework / engine for building social game like FarmVille – Stack Overflow

Implementing a timer thread Silverlight Tools and Features

Hello World – FlashDevelop (Flixel) – Flash Game Dojo

PushButton Engine – Modular Flash Game Development

haXe – Welcome to haXe !


11 Flash isometric engines you can use in your games

List of game engines – Wikipedia, the free encyclopedia

3d – isometric perspective in silverlight – Stack Overflow

2d – Drawing Isometric game worlds – Stack Overflow

GameSalad – Game creation for everyone ™ – GameSalad Arcade

WAR! Zynga Sues The Hell Out Of Brazilian Clone Vostu

Worms Reloaded |

How to make Angry Birds – part 1 | Paul’s blog@Wildbunny

How to make Angry Birds – part 2 | Paul’s blog@Wildbunny

Un juego online infantil con 50 millones de usuarios | TICbeat

Imagine Cup 2011 Game Design Competitor Showcase Part 4

RPG JS: Your online RPG on your browser

Start Coding For Windows Phone and XBox Live Indie Games

Lessons From FarmVille: How Zynga Uses The Cloud — InformationWeek

High Scalability – High Scalability – Zynga’s Z Cloud – Scale Fast or Fail Fast by Merging Private and Public Clouds

RedUSERS | Los videojuegos: un mercado en crecimiento para jóvenes desarrolladores

Augmented Reality RPG « I am Zef

MetaEdit+ Forum: Can I generate 2D games for iPhone from models?

Sid Meier’s Civilization Migrates To Facebook This Summer, Starts Going By Civ World

Creating 2D Games with JavaScript & HTML5 – The official Google Code blog

The second official clj3D screencast is out! « Web life between Python and lambda calculus

A look inside Origin’s amazing custom gaming PC factory

jMonkeyEngine 3.0 | Java OpenGL Game Engine

Joyride Laboratories

Tron clone in Clojure – tzachlivyatan

Playdom Social Games – Play Deep Realms

gameandgraphics: Development docs for the…

The Real Art of Video Games

Bliip Studio

Hello | resatori

Clojure Entity Component System | resatori

Slick – 2D Game Library based on LWJGL

Ruby For Kids – Teach Children Programming By Creating Games

Box2D – Home

My Links

More Social Games Programming series is coming. I should write about game development in Argentina, too.

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

Social Online Games Programming (Part 1) Introduction

Next Post

You know, I’m a big fan of Farmville. It pushed me to organize my days, using the rhythms of harvests. It’s a control of my daily agenda: if I seed in my farm, then I reserved the time to harvest. And it’s a game you can play alone, without bothering other players.

But I digress, the topic is game programming, not Farmville ;-):  the problems and challenges of programming social games. Curiously, the most successful games in industry are online games and not the most sophisticated ones: instead of 3D real time games, Farmville is a one-player, with a simple 2D rendering. The social game challenges are not in graphics and user experiences.

In this series, I want to enumerate the patterns and solutions we can use in social/online games. I’m not an expert in the topic: game development is not in my expertise (yet ;-). But for me, it’s a way to gain understanding of the problems and possible ways to solve them in such kind of development. It pushes me to learn new technologies, libraries, tools, and concepts.

Some subtopics I’m going to visit (commenting links, examples, maybe some simple code):

– Client technologies
– Server technologies
– Communication, messaging
– Cloud Computing (to assure scalability, performance, availability)
– Architectural styles and patterns to use (my preferred subtopic)
– Kind of games: single player, turn-based, real time
– Testing (TDD, other kind of tests)

Maybe I could write two simple examples (one-player,  turn-based), but I should review my schedule to have enough time for that activity. It would be a good excuse to exercise REST, Javascript, JQuery, PHP, Azure, artificial intelligence? 😉

It could be a long journey, but this is the first step 😉

Keep tuned!

Angel “Java” Lopez

REST: Links, News and resources (1)

Recently, I posted links with tutorials, examples, resources about Javascript and HTML5:

Javascript: Links, News and Resources (1)
HTML5: Links, News and Resources (1)

Now, a third important leg: REST at server. My recent links:

InfoQ: RESTful SOA or Domain-Driven Design – A Compromise?

REST en Te lo dije (Spanish blog)

Literate Programming – Nobody Understands REST or HTTP

REST using the WCF Web API – Basics (Part2)

Getting started with the WCF Web API – The Problem Solver

Using the WCF Web API in an ASP.NET MVC application – The Problem Solver

Windows Azure Storage : REST API (part 2) – Storage Client APIs – Microsoft Certification Examples, exercises, practises, tutorials, solutions about Windows

REST Services y WCF’s Web Api – ALT.NET Hispano Wiki

RestBucks on .Net; paying the order – LessonsLearnedFromFailureOfSOAP

RestBucks on .Net: Ordering Coffee

REST in Practice

Introducing RestBucks on .Net

Distributed computing fallacies and REST | Jimmy Bogard’s Blog

Writing REST services

Learn REST: A Tutorial

InfoQ: How to GET a Cup of Coffee

REST services with MVC « G# blog

Microsoft remakes WCF for REST and the web « Tim Anderson’s ITWriting

mvcConf 2 – Glenn Block: Take some REST with WCF | mvcConf | Channel 9

As usual, my links at delicious:

Keep tuned!

Angel “Java” Lopez