Abstract form

Truth vs. Hollywood

Posted in Uncategorized by Homam Hosseini on November 15, 2009

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.

Unfollow people who are not following you

Posted in Coding by Homam Hosseini on November 1, 2009

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.

Tagged with: , , , ,

Two in morning and…

Posted in Business, Company, Me by Homam Hosseini on October 25, 2009

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!

Accessing Remote ASP.NET Web Services using JSONP

Posted in Coding, Development, JavaScript by Homam Hosseini on October 12, 2009

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.

Why make an advergame for Hyzonia?

Posted in Architecture, Business, Coding, Development, Internet by Homam Hosseini on August 14, 2009

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.

Returning Anonymous Types in Web Services

Posted in Coding, Development by Homam Hosseini on July 9, 2009

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;
}

Lecture in UOWD

Posted in Company, Dubai by Homam Hosseini on July 4, 2009

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

Tagged with: , , , ,

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

Posted in Company, Internet by Homam Hosseini on June 27, 2009

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.

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

The fate of Iran is linked to Twitter

Posted in Internet by Homam Hosseini on June 21, 2009

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)

Tagged with: , , ,

Iran, Internet, People and Me

Posted in Me by Homam Hosseini on June 19, 2009

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.

Tagged with: , , , , ,