Homam's Mind

Monday, December 28, 2009
Tuesday, December 15, 2009

Higher spatial dimensions

A few days ago I had an interesting discussions about the existence of other dimensions. In my experience most people who have heard about Big Bang, relativity or even inflationary theory are unfamiliar with have a vague understating of this concept. Although higher spatial dimensions are extremely easy to understand and even have applications in everyday circumstances.

Most of us are familiar with the idea of flatlanders (thanks to Carl Sagan), 2-dimensional flat creatures that live on a plane, or a surface. A flatlander can never see a 3rd dimension but he can deal with it mathematically. A flatlander can certainly understand points, lines, circles and all other 2D geometrical objects. A flatlander needs 2 piece of information to identify any point in his universe: X and Y. He should have no problem in imagining line-lander creatures who need one piece of information to identify the positions in their universe: X. He can think that his flatland is made of infinite number of line-lands. To make a flatland you have to take a line-land and drag it in a direction orthogonal to it.

Flatlander knows that any position in line-land can be described by:

$latex Position_{Line} = (X)$

And any position in flatland can be described by:

$latex Position_{Flat} = (X , Y)$

Or

$latex Position_{Flat} = Position_{Line} , Y$

Y is a dimension that is unknown to line-landers and is the direction that we dragged the line-land to create a flatland.

We as 3-dimensional creatures can think that our 3D world is made of a flatland, dragged in a direction orthogonal to it. Any position in our world can be described by:

$latex Position_{Volume} = (X, Y, Z)$

Or

$latex Position_{Volume} = Position_{Flat}, Z$

Z is the new direction that is orthogonal to flatland.

You already got the picture, a 4-dimensional creature can drag our volume-land in a direction orthogonal to it to create his 4D world and so on.

$latex Position_{4D} = Position_{Volume}, W$ (W is the new dimension).

In other words:
A line-lander has no idea of a flatland. The position is only X for him. He describes a 0-land by X.
A flatlander describes a line-land by $latex Y = (X)$, a set of $latex X$s.
A volume-lander describes a flatland by $latex Z = (X, Y)$, a set of $latex (X, Y)$s
A 4D-lander describes a volume-land by $latex W = (X, Y, Z)$, a set of $latex (X, Y, Z)$s.

From elementary mathematics you must remember that a set of objects could be described by a function. For example if $latex F$ is a function defined on real numbers and for each real number that it receives it returns another real number then:
$latex y = F(x)$
Is the description of a line-land from a flatlander's point of view.
Other kinds of line-lands include:
$latex y = x$
$latex y = 4 x + 5.12$
$latex y = x^2$
$latex y = \sin(x)$
$latex y = 2(\sin(x) + \cos(x))$
And so on.

The line-lander only knows about X. If somebody tells him that his line-land is a part of a flat-land he doesn’t immediately find out what F function describes his line-land the flatland. But F is easily known to the flatlanders who are studying the line-land. Generally F describes the shape of the universe in a higher spatial dimension.

Let's talk about an interesting example. Assume that the line-land world as it is seen by our flatlanders is a circle. It means that $latex F = \pm \sqrt{r^2-x^2-y^2} $. The poor line-lander has no idea about the 2-dimensional shape of his world but he can find it out.

The line-lander finds out that his world is indeed bounded if he starts walking toward a direction and reaches the starting point.

A sphere is a 3-dimensional circle, F for a sphere is:
$latex F = \pm \sqrt{r^2-x^2-y^2-z^2} $

Let's rewrite these two equations in a more usual form:

1D Circle: $latex x^2+y^2 - a^2 = 0$
2D Sphere: $latex x^2 + y^2 + z^2 - a^2 = 0$

Look at the pattern:

































0DA Pair of Points$latex x^2 - a^2 = 0$$latex \omega_1 := \left (x^2 - a^2 \right )$
1DCircle$latex (x^2 - a^2) + y^2 = 0$$latex \omega_1 + y^2 = 0, \: \: \omega_2 := \left [ \omega_1 + y^2 \right ]$
2DSphere$latex \left [(x^2 - a^2) + y^2 \right ] + z^2= 0$$latex \omega_2 + z^2 = 0, \: \: \omega_3 := \left \{ \left [ \left ( x^2-a^2 \right ) + y^2 \right ] + z^2 \right \}$
3D3-Sphere$latex \left \{ \left [(x^2 - a^2) + y^2 \right ] + z^2 \right \} + w^2 = 0$$latex \omega_3 + w^2 = 0$
NDN-Sphere$latex \sum {X_{n^2}} - a^2, \: \: n = 0 \: to \: N$$latex \omega_{N-1} + X_N^2 = 0$

The surface of a sphere could be described by many circles. The smallest circle at the north pole is a point, the radius of the circles grows as we reach the equator and then again shrinks back to 0 at south pole. This is best described in this form of spherical coordinates:

$latex x_1 =a\cos(\phi_1)$ is a circle. A sphere is a collection of circles stacked on each other. The circles at north and south pole have 0 radius and the radius of the circle at equator is maximum (a). We can think that the radius of these circles change by: $latex r = a\cos(\phi_2)$. This $latex \phi_2$ is orthogonal to $latex \phi_1$ (and is in the new dimension).

So $latex x_2 =a\cos(\phi_2)\sin(\phi_1)$ describes a sphere.

In the same sense you can think that a circle is made of many pairs of points. At the top of the circle the distance between the pairs is 0, it reaches a maximum in equator and again 0 in the bottom.

Now we can extend this model to higher dimension spheres. Take a 3D sphere with radius 0, increase the radius to a maximum and then shrink it back to 0; you have a 3-sphere.

$latex x_3 = a\cos(\phi_3)sin(\phi_2)\sin(\phi_1)$ is a 3-sphere (a 4 dimensional sphere)

This way you can make other higher dimensional shapes. Note that here we only talked about spatial dimensions.
For example a stack of lines in Y-direction makes a square, a stack of flat squares in Z direction makes a cube and a stack of cubes in W direction makes a tesseract.

Take a look at the projection of a tesseract (4D cube) in 3D space here.
Monday, December 7, 2009

Hollywood Principle

Today I was working on refactoring some names in Hyzobox In/Out API. It is my personal favorite piece of code in the whole platform. In summary it allows the publisher of the game to customize the game in runtime dynamically by injecting codes and executing some functions in the context of the game (In) and to get notified about the events that are occurring inside the game (Out).

Inversion of Control is very natural in JavaScript and it has been used extensively in In/Out API. It's quite different from popular prototype pattern but most everyday JavaScript programmers use IoC even though they don't usually notice it.

Here is a sample in our API:

We register an event listener in Hyzobox, waiting for landing view of the game to be loaded:


var hb = Hyzobox.createInstance();
var landingview_loaded = function(hbEvent) {
// do something with hbEvent
}
hb.addEventListener('landingview_loaded', landingview_loaded);


It's is clear that we don't have control over when landingview_loaded event will be fired and its handler will be called.

hbEvent argument that is of type Hyzobox.Event has a data attribute that is of type Object. In this example the data is a LandingView instance. We can interact with this object in the event handler:


var landingview_loaded = function(hbEvent) {
var view = hbEvent.data;
view.inject('a-container-id', 'some text');
};


In this example we are injecting 'some text' to an element identified by 'a-container-id' inside landing view.

addEventListener() is part of Out and inject() is part of In API. If we want to listen to the events that are occurring inside a particular view, we should register their halnders after the view has been loaded:


var landingview_loaded = function(hbEvent) {
var view = hbEvent.data;
view.attachEventListener('playNow', function playNowHandler(playNowHbEvent) {
// do something with playNowHbEvent
});
};


And so on, we can have many nested Ins and Outs.

It's easy to see that in these examples the control has been transferred to the event handlers. The caller raise the events but it's the responsibility of the handlers to control the functionalities.

I don't want to go into the the details now, because the work hasn't yet been finished on these APIs. Once released, we will post them in Hyzobox documentations and Hyzonia tech blog in the following weeks.
Sunday, November 29, 2009

Microfinancing, Lending vs donating

I want to talk about what the brilliant idea microfinancing is.

I grew up in an Islamic family - however in my childhood they were not as conservative as they are now. It's a tradition in Iran and I think it is also an Islamic rule to donate some portion of your surplus to poor people; usually the people you know from your work, or in the neighborhood. Currently in Iran there is a well systematic Islamic donation process, and I think people are obliged to donate one fifth of their yearly surplus to this system. And no matter where you are, we are all used to see charities everywhere and in different occasions (like thanks giving or new year). Just a disclaimer that I'm by far not an expert in this area, but I've always believed charities are not a solution to poverty, they make it worse, they distribute poverty. They keep poor people poor. If the poor person is jobless, donations don't help him in getting hired, and if the poor person is receiving a very low wage, the charity doesn't urge the employer to pay more.

During the past months there were times that I was finding myself dangerously inclined toward social ideas and then I was swinging back to 'prosperity' and capitalism. But this issue that you have to always start form some place bigger than zero to have a life in a capitalistic society had been bothering me. Now I think microfinancing is a reasonable solution for this problem.

Why do you want to donate to somebody and loose some money? Why don't you lend him the money so he can start a business and pay you back? I understand that charities might be vital for some regions of the world, but I'm sure most of the donations that my family is doing in Iran will not be used in those regions.

'Carlos needs $1,100 to buy some pigs' he will return the loan in a year, but no bank is lending him, simply because the cost of processing the loan is higher than the profit. But this website: www.kiva.org is making it possible for Carlos to raise the money in a matter of a week. Carlos will not be another homeless beggar, he is starting his own business and his future depends on how hard he works and how well he manages the business. He will not need charity and in a few months he should be able to even hire employees and extend his business.

I was impressed that my like-minded people are among the top lenders of Kiva. Yeah! I think superstitious people have a hard time digesting this idea that they, not God, can help people to stand on their own two feet and overcome poverty. And of course the LGBT community that are helping their entrepreneurs to achieve their own equality.
That’s pretty all I wanted to say, I have something beautiful to think about tonight.
Sunday, November 15, 2009

Truth vs. Hollywood

I was reading this interesting column in NY Times, Mistakes in Typography by Alice Rawsthorn. Honestly it's the first time I ever looked at typography from this point of view. I can feel her view about typographical errors, usually I feel similar when I see a scientifically incorrect assertion in a movie for example.

Sometimes I think movies are not textbooks, they just should not be too wrong. But changing the truth to make it more cinematic has been OK with me. If we want Hollywood appreciate scientific values, we have to realize its rules too.

For now, I'm just enjoying reading this article.
Sunday, November 1, 2009

Unfollow people who are not following you

Last week I learnt that one well known way to increase the number of followers in Twitter is to follow as many people as you can. Chances are that finally a ratio of them (in our experiment something around one third) will follow you back.

The problem is that you cannot hide the truth, anybody who visits your Twitter page, will see the number of following is much bigger than the followers.

SocialOOMPH has a tool that automatically unfollows people who unfollow you. Assuming that some of our followers are using this tool, we should not unfollow our followers. But it seems to be perfectly safe to unfollow people who are not following you.

I spent an hour or so in the weekend to take a look at Twitter API and write a small program that does this job. I quite amazed by the simplicity of Twitter API, now I wonder why aren't we in our company spending time to study it in more details. It's interesting that it seems the guys in Twitter have had similar naming problems to ours. For example in the API terminology the people who you are following, are your 'friends'.

My program is a simple C# Console application and you need .NET Framework 3.5 to run it. Download Unfollow people who are not following me program here.
Sunday, October 25, 2009

Two in morning and...

It's two in morning and I can't sleep.
Today we moved part of Hyzonia, essentially its Core and global services to a new server. Finally. It's a Windows 2008, and I quite surprised how smooth this transition was, so far.

I'm trying to stimulate! the moods in the company. I'm trying to be more passionate, talk and make people talk more. The goal is to make most of everybody's intelligence. Everyone should feel she has an effect on business decisions. I don't need man power, I need mind power. It requires quite a force to shake this high inertia, change opposing company. I'm relaxing many rules, and I'm handing over many decision making tasks to my team. We gotta be a team that play together with our minds not our muscles. I'm already seeing some results and I expect to observe a measurable improvement in a matter of few weeks. We are starting new exciting projects, some of them are just show-offs (read it releases) and some are absolutely new crazy wild ideas.

Sometime I feel I've lost much of my passions, but I'm trying hard to prove it's a wrong, evil feeling. Most of all Richard Dawkins is helping me to remember I supposed to be more a scientist than a boring business man.

My team is energized since we got somebody in NetAd to work with our game customization API. Back in two week ago I was arguing that the whole customization API was a waste of time, I was thinking nobody will use it and eventually it would be our job to customize the games. I'm happy (indeed) that I was wrong. And you know there's nothing more funnier, more relaxing than being happy because you were wrong.

Anyway, we launched HyzoGames that contains some samples of the customized games. We're trying to keep Hyzonia Twitter account active. So if you care, follow us there. :)

No, I can't take it anymore, 'night!
Monday, October 12, 2009

Accessing Remote ASP.NET Web Services using JSONP

The problem:


You cannot call remote ASP.NET web service methods from a JavaScript, AJAX client.

Example:


You have a web service, at this address: http://a.com/service.asmx and you've configured the service to work with AJAX clients:
[WebService
(Namespace = "http://www.hyzonia.com/gametypes/PopNDropLikeGame/WS2")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class GameService : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public GameSessionResponse CreateGameSession(Guid questId)
{
...
}
}
}

And it works fine when you call its methods from a web page that is in this address: http://a.com/page.htm:
$.ajax({
type: "POST",
url: "GameService.asmx/CreateGameSession",
data: "{questId: '" + questId + "'}",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
Game._onSessionGot(response.d);
}
});

But the very same client-side code doesn’t work from this address: http://b.clom/page.htm

The problem in depth:


At first I cannot hold myself and not say that it is a silly problem. web services are meant to be called by remote clients. The fact that browsers block access to web services by AJAX calls is clearly contrary to the purpose of web services.

Interestingly browser extensions like Flash and Silverlight also by default block remote web services, but they provide a work around. Unfortunately no browser by date supports this work around for XMLHTTPRequests. This "security measure" seems odder when we notice that it is perfectly correct to import a JavaScript code snippet from another domain by a script tag:
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>

 


The solution:


As it was said, Flash and Silverlight both support remote calls. You just need a clientaccesspolicy file to be hosted at the root of a.com (http://a.com/clientaccesspolicy.xml):
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="SOAPAction">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

This file allows remote calls to be made from any other domain.

But in many situations we want to call the web service methods directly by AJAX clients. This need was the cause of to the development of JSONP (JSON with padding) protocol. As it was discussed it is correct to have a <script> element that loads a script from another domain. On the other hand you may know that it is possible to load scripts dynamically by a simple JavaScript trick (writing<script> tags) or using this jQuery plug in. Now the bulbs are flickering! The solution is to access the JSON web service by the src attribute of a <script> element. This is the whole idea behind JSONP.

But there are a couple of problems needed to be solved for ASP.NET ASMX web services before we can use them in a JSONP scenario.

  1. ASP.NET web services by default only accept POST requests, a <script src=""> element, produces a GET request.

  2. The result of the web method call must conform to JSONP, and you guess, ASP.NET 3.5 by default doesn’t support it.


The solution to the first problem may seem trivial, we can easily enable GET calls to web methods using [ScriptMethod(UseHttpGet = true)] attribute. The immediate problem is that when we mark a web method by this attribute it only can be called by GET requests. And remember, other clients (actually anything other than JSONP clients) are supposed to communicate with the web service by POST requests. I usually end up inheriting from the original web service and marking web methods by [ScriptMethod(UseHttpGet = true)] attribute in the derived class. Therefore I will have two ASMX web services, one using the original class (expecting POST request) and the other using the derived class (expecting GET requests).
[WebMethod(), ScriptMethod(UseHttpGet = true)]
public override GameSessionResponse CreateGameSession(Guid questId)
{
return base.CreateGameSession(questId);
}

Note you may need to add this code snippet in web.config:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>

</system.web>

There's another problem to be addressed in the client side. The client should call the web method by a correct URL (it has to pass a correct query string that could be deserialized back to .NET objects in the server side). In case of POST requests, I'm used to JSON2 library to post data to ASP.NET ASMX web services. Jquery $.AJAX method (when it is configured to use JSONP, by dataType: "jsonp") creates query string parameters for the data object it receives. But the result is not usable for ASMX web services.

Luckily there's a ready to use JQuery plug in (jMsAjax) that has the required algorithms for serializing a JavaScript object into a query string that can be parsed by ASP.NET web services.

Using the plug in I created this function to serialize JavaScript objects into query strings:
$.jmsajaxurl = function(options) {
var url = options.url;
url += "/" + options.method;
if (options.data) {
var data = ""; for (var i in options.data) {
if (data != "")
data += "&"; data += i + "=" + msJSON.stringify(options.data[i]);
}
url += "?" + data; data = null; options.data = "{}";
}
   return url;
};


You will need jMsAjax for this code snippet to work.

Finally this is a sample of a client side code using JQuery that calls an ASMX web service using JSONP:
var url = $.jmsajaxurl({
url: "http://hiddenobjects.hyzonia.com/services/GameService3.asmx",
method: "Login",
data: { email: "myemail@mydomain.com", password: "mypassword" }
});

$.ajax({
cache: false,
dataType: "jsonp",
success: function(d) { console.log(d); },
url: url + "&format=json"
});

Or equivalently:
$.getJSON(url + "&callback=?&format=json", function(data) {
console.log(data);
});

When you call an ASP.NET web service method (that is configured to receive GET requests) using a code similar to the above, it returns in XML. The problem is that the web service expects to receive a request that has a content type of "application/json; charset=utf-8" and <script> element simply doesn't add this content type to the request. There's a little thing we can do at the client side. The easiest way to resolve this problem is to use a HTTP module. The HTTP module should add this content type to the requests before they are processed by the web service handler.

On the other hand a JSONP client expects that the web service return the call by a string like this:
nameOfACallBackFunction(JSON_OBJECT_WEB_METHOD_RETURNED)

nameOfACallBackFunction must be given to the server by a parameter in the query string. Different JSONP compatible web services use different names for this parameter, but usually it is named 'callback'. At least this is what $.ajax() automatically adds to the request in JSONP mode.

I grabbed this HTTP module from a post in elegantcode.com.
public class JsonHttpModule : IHttpModule
{
private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8";

#region IHttpModule Members
public void Dispose()
{
}

public void Init(HttpApplication app)
{
app.BeginRequest += OnBeginRequest;
app.ReleaseRequestState += OnReleaseRequestState;
}
#endregion

bool _Apply(HttpRequest request)
{
if (!request.Url.AbsolutePath.Contains(".asmx")) return false;
if ("json" != request.QueryString.Get("format")) return false;
return true;
}

public void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;

if (!_Apply(app.Context.Request)) return;

if (string.IsNullOrEmpty(app.Context.Request.ContentType))
{
app.Context.Request.ContentType = JSON_CONTENT_TYPE;
}
}

public void OnReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;

if (!_Apply(app.Context.Request)) return;

app.Context.Response.Filter = new JsonResponseFilter(app.Context.Response.Filter, app.Context);
}
}

public class JsonResponseFilter : Stream
{
private readonly Stream _responseStream;
private HttpContext _context;

public JsonResponseFilter(Stream responseStream, HttpContext context)
{
_responseStream = responseStream;
_context = context;
}

public override bool CanRead { get { return true; } }

public override bool CanSeek { get { return true; } }

public override bool CanWrite { get { return true; } }

public override long Length { get { return 0; } }

public override long Position { get; set; }

public override void Write(byte[] buffer, int offset, int count)
{
var b1 = Encoding.UTF8.GetBytes(_context.Request.Params["callback"] + "(");
_responseStream.Write(b1, 0, b1.Length);
_responseStream.Write(buffer, offset, count);
var b2 = Encoding.UTF8.GetBytes(");");
_responseStream.Write(b2, 0, b2.Length);
}

public override void Close()
{
_responseStream.Close();
}

public override void Flush()
{
_responseStream.Flush();
}

public override long Seek(long offset, SeekOrigin origin)
{
return _responseStream.Seek(offset, origin);
}

public override void SetLength(long length)
{
_responseStream.SetLength(length);
}

public override int Read(byte[] buffer, int offset, int count)
{
return _responseStream.Read(buffer, offset, count);
}
}

This HTTP module will be applied to each request to a .asmx file that has a format=json in its query string.

Note that you have to update web.config:
<system.web>

<httpModules>

<add name="JSONAsmx"/>
</httpModules>
</system.web>

For IIS6 and
<system.webServer>
<modules>

<add name="JSONAsmx"/>
</modules>

</system.webServer>

For IIS7.

Now to test is open your web service in your browser, in my example:

http://hiddenobjects.hyzonia.com/services/GameService3.asmx/Login?email=e@e.com&password=p

It should return in XML

And

http://hiddenobjects.hyzonia.com/services/GameService3.asmx/Login?email="e@e.com"&password="p"&format=json&callback=myCallBackFunc

Will return:
myCallBackFunc({"d":{"__type":"HLoginResponse",
"isSuccessful":false,"error":false,"authSessionId":null,"nickName":null,"score":0}});

Don't worry about myCallBackFunc, JQuery nicely manages it, so that the whole business is behind the scene and you can use $.ajax success callback the very same way you use it for a normal AJAX call.

We should note that JSONP has its own problems, especially… yes... in IE! All versions of Internet Explorer has a 2083 character limit for the URL of a request. It means that you cannot send large data in GET requests to the server. Sometime this limitation leaves us with no choice but to use Flash or create a proxy to the remote web service in the local domain.
Friday, August 14, 2009

Why make an advergame for Hyzonia?

We have been working on a few cool features of Hyzonia in the past weeks. Hyzonia is a next generation internet ad service. Like traditional ad services Hyzonia receives advertisements from advertisers and distribute them in websites. But the ad materials in Hyzonia are not in the form of traditional banner or text ads. The ads would be placed inside games, in a way that players would interact and engage with the promoted subjects. This kind of games is being called an advergame. I don't want to dig into the marketing stuff, but it worths mentioning that one interesting feature of Hyzonia is that it makes it easier for advertisers to utilize the power of advergaming, for less, as Hyzonia is providing a rich set of ready-to-use advergames. Using Hyzonia customers do not need to pay big moneys to interactive software companies to make and host an advergame as part of their online campaign.

We already have built a number of  favorite games, but Hyzonia is extensible by nature, meaning that it is easy to create an advergame for Hyzonia or integrate an already built game into it. Like almost every big web business we know, we found it is crucial for Hyzonia to be extensible and customizable. Hence we spent the last few weeks on making final touches on the first version of our APIs, improving security and testing it all by making sample games.

It's no myth that most succesful indie developers are game makers. If you have some good ideas, you may find your two-week project shining on the top lists in Xbox Live or Apple Store.

In comparison with those programs, in Hyzonia you will start earning from the moment your game is added in the system. It would be based on a revenue sharing model, so as long as your game is attractive for promoters there would be some campaigns active in some instances of your game and a revenue stream for you. On the other hand contrary to Miniclip or Pogo, Hyzonia is not a single game portal, your game eventually will be displayed in our publishers' websites. Hyzonia is a service that provides the infrastructure needed for this communication among advertisers, publishers, and developers to happen.

Currently in addition of standard Web Service interfaces we are providing .NET libraries that encapsulate all the basic functionalities that an advergame in Hyzonia platform should support. One exciting news is that you don't need to make everything from scratch using Hyzonia APIs, but the required functionalities of an advergame in Hyzonia have been designed in a way to make it possible to take virtually any game, wrap it inside a shell (we call Island) and have it added in Hyzonia. The .NET libraries that we are shipping as part of the API have all the functionalities needed by this shell.

Because of its service oriented architecture, Hyzonia advergames (Islands) could be anywhere in the internet. But currently we are only activating the games that have been hosted physically in our datacenters, although exactly like a banner ad (hosted let's say by DoubleClick) they could be displayed on other websites.

Obviously not any game can be converted into an advergame. This is another issue that we are adderssing it in the guidelines that will be released alongside the APIs.

A thousand words: Hyzonia connects developers, advertisers and websites.
Thursday, July 9, 2009

Returning Anonymous Types in Web Services

When coding an AJAX app that makes relatively many calls to the server in short periods of time, the main concern is to minimize the bandwidth it consumes. For example think of an AJAX chat application. For it to look like a real time app we have to query the server every few seconds.

If you're using .NET, you already knew how easy it is to return objects and have them serialized in JSON in Web Services. All we need to do is to deal with the logics and .NET does all the things and tricks related to the communication. For our example, this is the method that needed to be called periodically from the client:

[WebMethod]


public IEnumerable<ChatMessage> GetMessages()


{


var currentPlayer = OnlinePlayers.Single(p => p.Id == CurrentPlayerId);


var messages = Messages.Where(m => m.DateSent > currentPlayer.DateSynced);


currentPlayer.DateSynced = DateTime.Now;


return messages;


}



The problem is that .NET really serializes everything. If we have the following definitions:

[Serializable]


public class Player


{


public Player() { }


public string Name { get; set; }


public string Id { get; set; }


public string PhotoUrl { get; set; }


public DateTime DateSynced { get; set; }


// other properties


}



[Serializable]


public class ChatMessage


{


public ChatMessage() { }


public Player Sender { get; set; }


public string Message { get; set; }


public DateTime DateSent { get; set; }


}



It is certainly not desirable to send a Player object back to the client by every ChatMessage. Assuming that the client already knows all the Players involved in the Chat, the ChatMessage object that is being sent to the client only needs to have a Sender ID property. One obvious solution that is very familiar for hardcore client-server developers is to have another type, let's say ClientChatMessage that only contains the required information. If you're taking this approach remember ClientChatMessage should be a struct type:

[WebMethod]


public IEnumerable<ClientChatMessage> GetMessages()


{


//...


return messages.Select(m => (ClientChatMessage)m);


}



[Serializable]


public struct ClientChatMessage


{


public string SenderId;


public DateTime DateSent;


public string Message;



public static explicit operator ClientChatMessage(ChatMessage m)


{


return new ClientChatMessage()


{


DateSent = m.DateSent,


Message = m.Message,


SenderId = m.Sender.Id


};


}


}



When we are targeting only AJAX clients it's very handy to return anonymously typed objects. Anonymous objects cannot be serialized by XML serialization, but JavaScript (JSON) serializer is able to serialize them. I prefer it:

[WebMethod]


public IEnumerable<Object> GetMessages()


{


//...


return messages.Select(m =>


new {


s = m.Sender.Id,


m = m.Message,


d = m.DateSent


});


}



Here I've shortened the names of the properties, hey it is AJAX, we should save bandwidth by every mean possible.

We've used this trick in many places of the games we are developing for Hyzonia, as the current games only will be available for JavaScript clients. We found another similar trick very handy: a web method can take an object as an argument; if you send a JSON serialized object from the client to these methods, you'll have a Dictionary<String, Object> in the server side.
[WebMethod]

public IEnumerable<ChatMessage> GetMessages()

{

var currentPlayer = OnlinePlayers.Single(p => p.Id == CurrentPlayerId);

var messages = Messages.Where(m => m.DateSent > currentPlayer.DateSynced);

currentPlayer.DateSynced = DateTime.Now;

return messages;

}
Saturday, July 4, 2009

Lecture in UOWD

Reza, our business dev manager, has a lecture on advergaming in UOWD. Everybody's welcome to join: http://blog.hyzonia.com
Saturday, June 27, 2009

Don't put comments at the first line of a HTML document

Here's a funny problem we faced:

When Lionel, a graphic designer in the company, added new graphics to a page of the website he noticed that there's something terribly wrong in IE. All the contents of the page had been aligned left, and the layout has been disturbed. The diagnostic process was straightforward, because all the other pages were working properly before, we started removing the contents of this new page, to find what exactly caused the problem.

After the page's been nearly totally robbed, and we didn’t find a clue, we noticed the only difference between it and other pages was that this page had a comment line automatically being generated at the first line. So that's it, don't put any comment before the declaration in HTML.

[caption id="attachment_128" align="aligncenter" width="480" caption="This is what happens when you have a comment in the first line"]This is what happens when you have a comment in the first line[/caption]
Sunday, June 21, 2009

The fate of Iran is linked to Twitter

I know it may seem rude for Iranians but it's funny and true.

"The fate of Iran, is strangely entwined with the sleep schedules of the geeks that maintain the servers at Twitter and YouTube" - Hodgman (aka the PC)
Friday, June 19, 2009

Iran, Internet, People and Me

Honestly, nobody knows how much I love to sit somewhere in the darkness and think. Thinking about the past, the mistakes I've done, I'm making and thinking and thinking of every aspect of life that matters for me. Not surprisingly it's often very sad, hey common it's life, sometimes I blowup, sometime I wish I had belief in a superstition, a religion, you know something to rely on.


I was thinking on how internet influenced these current events in Iran. Yes I know I'm not the first one here, but given the fact that Iran was the nation I flee from, simply because I wasn't able to fit in the society, the behaviors, the beliefs of the people and the society as a whole was unacceptable for me, and vice versa I've seen myself totally unacceptable for the society, my family and even some of my close friends, and when I think of why and how that difference originated, I find internet was very influential on me, this subject that how these days internet is so significant in Iran is very interesting for me. I remember I was spending all my after-school time in my uncle's office to browse the web and Yahoo clubs. My English was terrible, I had to print my e-mails, and read them at home using a dictionary. I started learning how life is outside Iran. What's important for people in the world and you can expect by the world I mean the US. Almost every resource that was interesting for me and available in English, every Yahoo club I joined, every website I browsed was in the US. As a matter of confession, the internet has changed my life twice: first when it opened my eyes to the more-real-world and second when I found online dating. Simply I met people who I had much in common. The ones I felt I was comfortable with happened to be in two groups: people like me who’d started using internet in Iran early, before the censorship starts, they like me have been really influenced by the net, and the people who were living or had been lived in the west. It was me a to-some-extend virgin high school student facing a world very different than what I've learnt it is and the people who I was most comfortable with, more than I was in the family.


OK, It can be a long story, I just wanted to say the internet made me think twice about the customs, especially the strict religious ones, internet helped me know myself, gave me confidence, internet was where I first tasted the feeling of self expression, being myself, I have my life, my love, my job because of the internet.


I'm certainly pessimistic about what's happening in Iran, people there aren't ready for a reform, at least something that make me trust my nation again. The internet hasn't had an influence on them similar to what it has done to me. People are not using internet to see what the world really is, they’re just joining local communities, browsing Persian language resources. I think Iran cannot have a democratic government, Iran is years back to have basic civil rights recognized in, not because a strong Islamic system is governing now, but because it is the will of people. People are not ready to accept a more liberal style of governance and especially its consequences. Don't forget people of Iran, including my very family are very religious, and they strongly believe in Shia thesis.


For now, for people like me, it doesn't really matter what would be the outcome, I believe whatever it would be it hardly affect my view on Iran (and vice versa), I can't live a safe, enjoyable life, with the people I love in my preferred life style there.

Sunday, June 14, 2009

How to use cursors in web pages, painless

The shortcoming of current edition of HTML and the whole technologies we build the user interface of our websites on is no secret. Here is an example: If you want to put a custom cursor on an element use this markup:
element { cursor: url('pointer.cur'), default }

I know you may think custom cursors are not being supported in FireFox, but it's not the case if you append a ', default' (or any other standard CSS cursor value instead 'default').

If you are looking for a painless software to create mouse cursors, we fond AniTuner easy and useful. Don't get it wrong it can be easily used to create static .cur files that can be displayed in major browsers.

Generally as a user experience point of view, it is not a good idea to have custom cursors  in web pages, but when you are developing an online game, a smart use of cursors can make it simply more attractive.
Saturday, June 6, 2009

When was the last time somebody told you that destiny is not determined by forces beyond our control

Human destiny is not determined by forces beyond our control. You remind us that our future is not shaped by mere chance or circumstance. Our history has always been the sum total of the choices made and the actions taken by each individual man or woman. It has always been up to us.

Can it come out of an atheist mouth?
Friday, June 5, 2009

Parental rights

I dont know about other animals, but in human societies, if you see yourself are belonging to a minority, you learn protecting your rights as a homo species creature, is the most crucial matter in your life.



I always have thought pinguines and humans are alike. Back in years ago I never thought I find myself have this much common with these lovely, lonely pingus.


They are fighting over an stolen egg.

Friday, May 29, 2009

Service Provider Pattern Part II

Read the first part

At first I found it is generally a good advice to store the configuration in a static, read-only property somewhere. And there's no better place other than the configuraiton class itself:
static MyServicesConfigurationSection _Value;
public static MyServicesConfigurationSection GetValue()
{
if (_Value == null)
{
_Value = (MyServicesConfigurationSection)
System.Configuration.ConfigurationManager.GetSection("myServices");
}
return _Value;
}

Here we assume that we always define the matching element to be "myServices" in the configuration file. It makes sense because it makes it easier for us to find the element in different configuration files. We can always access the value using:
var config = Configuration.MyServicesConfigurationSection.GetValue();

Modularizing is the obvious upgrade we are goging to make to the Service Provider Pattern Part I. I can find three distinct components:

Service-Provider-Pattern-Ar 

  • Service Provider Pattern contains all the logic required by the pattern to work. You alway reference it everywhere you want to use the pattern.

  • Service Definitions is where we define our services.

  • Implementation of the Services contains  concrete classes and implementations of (some of) the services that have been defined in Service Definitions module. In a real application you may end up with many Implementation components each containing the implementation of a one or few number of services.


As before the configuration file of the Host Application maps the definitions (abstract services) to implementations (concrete services).

It's clear that using this architecture we can have host applications that are hosting different implementations of the services.

Configuring the Services


Till now the only purpose of the configuration file was to store the mapping between the definitions and the implementations. But we can use it in order to actually configure the services. For an example it's very likely that the FTPFileStorageService that we defined in the previous part, needs a FTP account credential to work. In this case the <add> element (that maps FileStorageService to FTPFileStorageService) may look like:
<add def="MyServiceDefinitions.FileStorageService"
impl="MyServiceImplementations.FTPFileStorageService,
MyServiceImplementations
"
host="ftp://ftp.wingooli.com" username="wingooloi"
password="password" />

Both the abstract service definition and the concrete implementation can implement IServiceBase interface:
public interface IServiceBase
{
void Initialize(Configuration.ServiceProviderSettings settings);
}

This interface just has one method, Initialize, that takes a ServiceProviderSettings (the <add> element). We can read the additional attributes of the <add> element using a code like this:
settings.Properties["host"]

The logics in the Service Provider Pattern component automatically call the Initialize method if this interface has been implemented in the definition the  implementation of the service.

Here is the design:

Service-Provider-Pattern

Now our Service Provider Pattern has nothing less than ASP.NET Provider Pattern but it is easier to implement.

Using all these modules we can reduce the code needed to instantiate a service (this code snippet should be placed in the abstract service definition class):
static FileStorageService _Instance;
static object _InstanceLocker = new object();
public static FileStorageService Instance
{
get {
if (_Instance == null) {
lock (_InstanceLocker) {
_Instance = ServiceModel.ServicesHelper
.GetServiceInterface<FileStorageService>();
}
}
return _Instance;
}
}

Because it is a repeatable pattern and to make it all more developer friendly, I created a C# code snippet that generates a similar code automatically.

You can download the whole things here.
Monday, May 25, 2009

JQuery Auto Ellipsis Plugin

It is one of my most favorite JQuery plugins I coded for Dig and Win. As Dig and Win is a AJAX game, we have developed many JavaScript snippets including JQuery plugins and controls and behaviors for Microsoft AJAX Framework. And I had much fun working on JavaScript, honestly I didn't know how powerful and how interesting this language is before working on the Dig and Win game. Check out Auto Ellipsis in my homepage or its JQuery page.
Wednesday, May 20, 2009

Service Provider Pattern, Part I

Read the Second and final part

Hyzonia is made of dozens of services running in many machines and app domains all over the internet. One problem we faced early in designing Hyzonia was the need to have different implementations for the a service and the ability to switch between the implementation as the need arises in the run time.

ASP.NET has already had a well-established Provider Pattern. But soon it turns out that it is not the best solution in our case. It seems ASP.NET Provider Pattern is not that developer friendly especially when you have dozens and increasing number of service definitions; because you have to code a new configuration class, create an abstract class, its implementation and a static helper class and it means you have to write the same methods in at least three places.

I wanted to let our developers to be able to add new services very fast. Here is a description of the provider pattern I came with.

Here I assume that services are stateless singleton objects, that is a true assumption in the context of Hyzonia and most of service oriented applications. That's also true about ASP.NET providers. The main reason lies in the SOA paradigm, as in service oriented architecture we think of an operation as something that when it is given its required input arguments it does all the job and returns a success or a failure message. When a client calls an operation it passed all the job to the service and basically it disconnects and waits until the operation returns. The operations that perform an a business object should perform a meaningful business process. It means that those operations must transfer a business object to consistent state.

It is guaranteed that by obeying such those rules you will have a clear separation between your service/business logic and the clients (that are the users of the services).

How to


For adding a new service you need to create the service definition that is an abstract class. Here as a rule we store the service definitions in a seperate assembly that could be shared among many app domains. For our pattern to work we need to add a static getter member to the abstract definitions, just like what you may do for creating a singleton object. Let's name it Instance, that is a getter-only property of the type of the abstract class itself. It's obvious that we are going to load, instantiate and return the concrete implementation here. Let's talk about it a bit later.

For an example, suppose that we are building a File Storage Service. There's no doubt that the main functionalists of such this service are Storing and Deleting the files. So here is the service definition:
public abstract class FileStorageService {
public static FileStorageService Instance {
get { // I told you, we talk about it later }
}
public abstract string Store(Byte[] bytes, string extension);
public abstract bool Delete(string url);
}

Suppose we have a FTP implementation the service: FTPFileStorageService:
public class FTPFileStorageService : FileStorageService {
//...
}

Now if we want to instantiate the FTPFileStorageSerivce in a host application, we need to modify the configuration file of the host app in a way to relate the service definition to our desired implementation. Here is the way we do it:
<service def="FileStorageService" impl="FTPFileStorageService"/>

Now let's back to where we left our discussion about the static Instance property in the service definition class. We need to somehow read the configuration file, find the active implementation, instantiate and return it here. Here is the code:
static FileStorageService _Instance;
public static FileStorageService Instance {
get {
if (_Instance == null)
{
var name = (typeof(FileStorageService)).FullName;

var myAppConfiguration =
(MyApp.Configuration.MyAppServiceConfigurationSection)
System.Configuration.ConfigurationManager
.GetSection("myAppConfig");

var services = myAppConfiguration.Services;

ServiceProviderSettings config = null;

foreach (var s in services)
{
var serviceConfig = (ServiceProviderSettings)s;
if (serviceConfig.Definition == name)
{
config = serviceConfig;
break;
}
}

if (config == null)
throw new Exception(@"A service mapping is
missed in the configuration file");

var type = Type.GetType(config.Implementation);
_Instance = (FileStorageService)Activator.CreateInstance(type);
}
return _Instance;
}
}

You may want to download a demo project here.

If you're new to .NET configuration you'll find the download a good demonstration for starting working with custom configuration classes.

In the second and the final part of this discussion you'll see how we convert a good idea to a working one. The most obvious issue with the code above is here
System.Configuration.ConfigurationManager.GetSection("myAppConfig")

where we are coupling the abstract class (the service definition) and the configuration of the host application. I'm advocating the idea that service definitions must be and are in nature independent of their host.

I will talk about such these issues and making the whole thing more developer friendly in the next part. We will also add more features and try to make it really like a pattern.

Read the Second and final part
Sunday, May 10, 2009

JQuery Wingooli Photo Gallery

I just want to introduce a JQuery photo gallery plugin I developed fro my profile. My main motivation for building this plugin was that I wanted it to be search engine friendly therefore I needed a clear separation between the photo gallery functionalists and the data describing the photos and the gallery. It is something that is easy to achieve using JQuery.

BTW these days I spend a part of my time discussing and teaching OOP JavaScript to our fellow programmers in RENA. It's interesting for me to discuss the somewhat weird features of JavaScript for these guys who are already well experiencedand talented .NET developers. I try my best to convince them JavaScript is so fun when you get used to it, so fun and so powerful that you end up you want to kiss all the ASP.NET AJAX and UI functionalists a goodbye and develop the effects yourself and see how much you can improve the performance and the branding of your application.

We in RENA are looking for a Web UI Developer to handle such those tasks, it came out to be a very hard job finding a person for this position, mainly because it requires you to be a JavaScript God! to pass the first step in the recruitment process. Drop us a message if you fit the position.
Monday, May 4, 2009

They kill people like us

I just wanted to share and save this article: They kill people like us, says gay Iraqi. This is exactly what life is for gays living in the middle east.

One evidence that make me think this situation would not be eased by years, is where Moyad says something like "my future is in the hand of God". As long as middle eastern gays think there's a God who has control over their life, the shall see no optimism for the future. All these troubles have been caused by the name of God and will be easily resolved if people simply loose their faith in God. I believe the first groups who should start thinking twice when they hear the word God are the ones who have suffered because of the belief in God in general and particularly sexual minorities.
Friday, May 1, 2009

Award for Best Website Developed on Microsoft Technology

DSC_0185

Hmm, Thanks for these awards I have cool subjects to post.

It’s a few days I’m receiving e-mails from a girl, saying we both were going to the same kindergarten :-) My mom was working there. I enjoyed the conversation so far, it’s interesting to find a person who seems to know you after years, whilst you remember nothing at all.

I had time to watch some shows of American Idol today, comparing to the last year I totally missed it, and not surprisingly I found myself a fan of Adam.

I am getting worried about the path the business people are taking in our company, in many ways I am completely in disagreement with them. This week I have to concentrate to bring some changes to the company business. Actually I started by changing the layout (physical!) of my department; we changed the position of tables, we bought a whiteboard and for the first time I have a well-defined schedule covering all the days till the end of the week. But still I have to force the business to take a look at the state and the way they are taking from an outsider perspective. For me it’s very wrong, I have to fix it.

Thursday, March 26, 2009

Curing

I thought all gays in under development and developing countries, have at least once thought how life would be if they weren’t gay, and how they could cure themselves and feel heterosexual.

Today when I was reading this news article I was thinking that I have learnt if I love my life, when I love the way I am, why ever do I need to be cured. Even if it’s a disease I love to be patient and suffer. Call it BDSM! but it’s more for me ‘love’.

Monday, March 9, 2009

How we are wasting personnel time

It's a few week most of the company's personnel (of course except me) have almost nothing to do in their daily schedule. I really don't like it, I believe they could be very useful handling many long overdue jobs, but there's not much things I can do when bosses themselves are away and just come to the office one-day a week or so. This is not a position I expected our company to be a few months after (a more formal) establishment, I know it must be fixed and much like any other thing that should be fixed in our lives, it could not be fixed by anyone other than me. I wish and I hope to find someone who could help me reducing some of my to-dos so I could focus more on such these issues.

Thursday, March 5, 2009

I was there

It's sad, someday I will be telling the stories of of how gay community struggled and worked hard to overturn a ban on gay marriage in California. A move that started a broader movement among all gay people all around the world, including me, and I will say I was there sitting at my desk, reading the news!

I wish I could be there, organizing events, communicating with people, trying to change their minds toward acceptance, fighting for my rights and for a better future, fighting for the next gay children to have an easier life than I had.

It's sad, here I even can't talk about it. Here is the story I will someday post on my facebook for all the people who "think" they know me, see what's behind this closet life and what makes me cry.

Saturday, February 21, 2009

US-China

I think my friends have no doubt how I wanted to see Hillary Clinton as the president of the US. Anyway I'm happy to see her in this position, traveling round the world and spreading a better image of the US. I was supporting her because I thought she would be a better president in pursuing human rights and civil rights in comparison with Barack Obama. For nearly two decades people like me, have considered Clinton as a civil rights icon. By the way what she is doing in China, putting aside human right concerns in the sake of economic goals, will not change my view. It is just another indication of how deep this crisis is, that makes Clinton to retreat from the usual powerful position US diplomats take and even technically asks China not to withdraw its investments in US treasury.

I don't feel good about all these events, I used to and wish to see a strong United States that is a symbol of hope and dreams to all the world. On the other hand, to be optimistic (something that it seems Obama has been missed), it seems that this crisis has created some new opportunities for traditionally different west and east to cooperate on something, and I would call it a victory if the west emerge as the more powerful, more influential part. I will say that people in the more liberal west,x create and resolve their problems. Here is something to follow that confirms my statement that all the people of the US are taking part in recovering from the problem. Even if it seems they are not contributing or they are swimming in the wrong direction, but at least they have a chance to express and examine their ideas.

Thursday, February 19, 2009

XM Radio Sucks!

I used to listen XM in office, but recently the more I listen to my old favorite channels, the more I get bored. It seems they just have a very limited set of musics and play 'em just randomly in they various channels.

I loved XM 20on20 but this new good morning program really really sucks.