Apr 28, 2011

Loading pictures from Facebook

I ran into flash security problem when as3 application tried to load users profile picture. It seems started after Flash Player 10.2 update today.

If you get error like this:

SecurityError: Error #2122: Security sandbox violation: LoaderInfo.content: http://mydomain.com/my.swf cannot access https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/1234_1424341323_7322_s.jpg. A policy file is required, but the checkPolicyFile flag was not set when this media was loaded.

You need to load policy file from facebook by

Security.loadPolicyFile("https://fbcdn-profile-a.akamaihd.net/crossdomain.xml");

Before today it was enough to load it from here
Security.loadPolicyFile("http://profile.ak.fbcdn.net/crossdomain.xml");

Waiting for news from Facebook or Adobe about these changes.

Apr 7, 2011

Facebook apps OAuth 2.0 authorization

As you know Facebook implemented OAuth 2.0 authorization for the applications. I recommend you to start learning about this method from http://developers.facebook.com/docs/guides/canvas/#auth.
Here, I want to describe authorization process for client-server Facebook Canvas application assuming that server part is written on Java (JSP / Servlets).

When user tries access your app first time he should be redirected to special dialog to authorize your app and allow it to access your facebook user account data. To show this OAuth dialog you need to redirect user here
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE

But how to detect if user is not authorize your app yet? We'll use base64url encoded parameter "signed_request" that is passed to you using HTTP POST method.
Please note: You need to enable "OAuth 2.0 for Canvas" parameter in your app settings on "Advanced" tab.

If user authorized your app then signed_request parameter will have user_id, oauth_token and other attributes. So we need to check if any of that attributes is present and redirect the browser to the dialogue otherwise.

Here is JSP page code example:

<head>
<%
    JSONObject signedRequest = FacebookProvider.decodeSignedRequest(request.getParameter("signed_request"));

    if(signedRequest.has("user_id") == false)
    {
%>
  //Redirect to OAuth dialog using javascript
  <script language="JavaScript" type="text/javascript">
   appId = "12345678"; //Change to your own
   appURL = "http://apps.facebook.com/exampleapp/"; //change to your own
   
   top.location.href = "https://www.facebook.com/dialog/oauth?client_id=" +
                     appId  + "&redirect_uri=" + appURL;
  </script>
  </head>

<%
    }
    else
    {
%>
</head>
 // You are athorized!
... here is your html text ...

<%
 }
%>

Apr 4, 2011

Facebook Graph API init problems

When we turn to the new Graph API for our facebook applications we were faced with the problem of actionscript API initialization on some web browsers like Internet Explorer and Opera. You can find actionscript Graph API here http://code.google.com/p/facebook-actionscript-api/

After detailed studying of source code of that library we discovered that the problem is in Facebook Javascript SDK events. It is due to actionscript library is actually based completely on javascript SDK.
If you'll look into "api\com\facebook\graph\core\FacebookJSBridge.as" file you'll see how FB.init() method implemented:

init: function( opts ) {
FB.init( FB.JSON.parse( opts ) );

FB.Event.subscribe( 'auth.sessionChange', function( response ) {
FBAS.updateSwfSession( response.session );
} );
}


Even if you use Javascript SDK you won't catch events you subscribed on.

Solution of this problem was found in Facebook app settings. 
You need to fill in both fields "Site URL" and "Site Domain" on "Web Site" tab in you app settings.

Very strange that this problem manifested itself only on the IE and Opera browsers.
Anyone knows why?

Feb 10, 2010

Publish post to facebook Wall (News feeds) from actionscript

This article shows two ways how to make publish to stream Wall (News feeds) from flash facebook application or game:

  • Publish post to stream with no user actions (using Stream.publish)
  • Publish to stream from rendered Feed form (using Facebook.streamPublish)

1. Publish to stream using Stream.publish method

You can find detailed description of this method here http://wiki.developers.facebook.com/index.php/Stream.publish

That is very detailed description and I only want to show how to use it from actionscript 3.
Most probably you use actionscript facebook API client libraries from here.
When I have found description of Sream.publish method on page above and understood that I need to use it (without feed form rendering) I couldn't find any appropriate actionscript method in documentation. Only digging of client library source code helped me to find PublishPost class that allows calling Stream.publish method.

Here is example how to use this method from actionscript 3:

private function publishToStream():void{
var message:String = "Stream.publish example";
var attachment:Object = {media: [{
type: "image",
src: "http://novacoders.com/design/img/logo.gif",
href: "http://novacoders.com/"
}]};
var actionLinkData:ActionLinkData = new ActionLinkData();
actionLinkData.href = "http://novacoders.com/services/flashdevelopment/";
actionLinkData.text = "Flash games development";
var post:PublishPost = new PublishPost(message, attachment, [actionLinkData], fbook.uid);
post.addEventListener(FacebookEvent.COMPLETE, onPublish);
var call:FacebookCall = fbook.post(post);
}

private function onPublish(e:FacebookEvent):void{
if(e.error!=null){
// fbook.grantExtendedPermission("publish_stream");
trace("Publish to stream: " + e.error.errorMsg);
}else{
trace("Publish to stream: onPublish " + e.data);
}
}


2. Publish to stream from feed form using Facebook.streamPublish method

to be continued

Feb 8, 2010

Verify whether flash swf file is loaded from Facebook

This article describes how to verify that Flash object was loaded from Facebook web page.

There are official detailed instructions on facebook page you can find here:
http://wiki.developers.facebook.com/index.php/Fb:swf

Here are main points:

For security, this technique does not embed your secret key in your Flash app:
  1. Get all the parameters whose names start with fb_sig. (Do not include the fb_sig parameter itself.) In Flex use Application.application.parameters to do this.
  2. Strip the fb_sig_ prefix from all parameters.
  3. Create a string of the form param1=value1param2=value2param3=value3, etc., sorted by the names (not the values) of the parameters. Note: Do not use ampersands between the parameters.
  4. Separately pass this string and the fb_sig parameter itself to your server, where your secret key is stored.
  5. On your server, append your application secret key to the string that was passed in. The following is returned: param1=value1param2=value2param3=value3myappsecret
  6. On your server, create an MD5 hash of this string.
  7. On your server, compare the generated hash with the fb_sig parameter that was passed in. If they are equal, then your Flash object was loaded by Facebook.

After reading that article, many developers try to use fb_sig_ parameters which are listed here
and it doesn't work.
The right way to generate string from point 3 above is to use all parameters with prefix "fb_sig_" because those can be changed anytime by facebook.

Here is Actionscript 3 code that implements this technique:

private function encodeFlashVarsString(parameters:Object):String{
var keyArray:Array = new Array();
for (key in parameters) {
keyArray.push(key);
}
keyArray = keyArray.sort();
var hashString:String = "";
while (keyArray.length > 0) {
var key:String = keyArray.shift();
if (key != "fb_sig" && key.substring(0, 6) == "fb_sig") {
var param:String = parameters[key];
hashString += key.substr(7) + "=" + param;
}
}
return hashString;
}

You can acces parameters from loaderInfo field of stage or other MovieClips. For example:
parameters = stage.loaderInfo.parameters;


Now, you need to send generated hash string to your server where it will be merged with Facebook Application Secret Key and MD5 hash should be calculated. Then you need to compare MD5 code with fb_sig parameter to determine if swf file was loaded and run from Facebook page. So, don't forget to send "fb_sig" parameter to the server as well.

Here is server side java code that makes MD5 hash calculation and compares result with result received from client side.


import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* Check if client application run from facebook page
* @param paramsString String generated on client side
* @param appSecretKey Your application's secrete key
* @param resHashString String we should receive after paramsString MD5 hash calculation
* @return true if swf file was loaded from Facebook page
*/

public static boolean checkHashString( String paramsString,
String appSecretKey,
String resHashString
) {
if(paramsString == null || resHashString == null){
return false;
}
try {
String srcString = paramsString + appSecretKey;
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] src = srcString.getBytes();
byte[] res = md5.digest(src);
String resStr = new BigInteger(1, res).toString(16);
return resStr.equals(resHashString);
} catch (NoSuchAlgorithmException ex) {
System.out.println("md5 exception:"+ex.getMessage());
}
return false;
}


Hope it is helpful article :)

Nov 28, 2009

The main stages of the custom mobile applications development

Stages of the outsourcing project

Introduction

In this article I have tried to describe all the main stages through which every custom mobile outsourcing project passes. I divided them into 5 stages. This article is based on my personal experience as developer of mobile applications, as Lead Programmer, as Project Manager and as Business Development Manager (BDM). At the moment I am working in the Novacoders company. This article mainly describes the approaches to the management of the mobile project outsourcing, applied in our company. I understand that there are many alternative schemes for the implementation of projects that deserve attention, but the basic approach remains unchanged.

The main purpose of this article is to give customers a mobile application or game, an understanding of how exactly we, outsourcing companies, develop custom projects, and which main processes and stages each outsourcing project pass through. This article will also help to novice outsourcing developers to understand the process of the mobile software development.

Most likely, all described in this article holds true for the outsourcing projects that is not for mobile platforms, but I do not presume to judge other software industry, because my specializing exclusively in mobile software.

So imagine that you are a customer and you have an idea how to create an application or game for mobile phones. You have access to the market, but there is no team and there is no knowledge how to develop a mobile software. In this case, you can start to search workers in the Internet or prepare a team of professionals (make interview with each team member and allocate work place for each of them), and then manage this team yourself until successful (or not) project completeness. It is possible to describe the reasons why our customers trust application development outsourcing company for a long time, but here we have omitted the enumeration of these causes, and imagine that you finally decide to dedicate your mobile application development to outsourcing company.

It is good practice to to sign a NDA (Non Disclosure Agreement – NDA) before exchanging of any information about the project. The signing of this document provides assurance that the disclosure of information by the customer or client does not pass out of the outsourcing company and does not fall into the hands of competitors.

Stage 1. Description of the application and its requirements.

At this stage, I suggest you have a clear vision of your mobile application or game and you have some understanding of mobile platforms or, at least, a list of phone numbers or operators that need to be met. It is better to spend a little time to sketch and description of the application as detailed as possible. Make a list of the functionality that must be implemented in your application, and, preferably, to find some links in the Internet to similar applications, which you like best. Writing such document is to clear thinking regarding the project and introduce new, bright ideas. It sometimes even helps avoiding of “stupid” ideas.

Of course, this stage can also be placed onto the shoulders of an outsourcing company, describing your idea only superficially and expecting that developer will prepare description of your idea, a list of functionality and technical requirements (TDD). Obviously, the cost for the compilation of documentation will be included in the cost of the project (more on that in step 2), but the cost of the project, most likely, will also include additional risks for the implementation of a high probability customer's feedback. My own experience shows that not well thought-out project by the customer at this stage, entails a lot of changes at the design stage, often that even wasn't estimated by the developer. Of course, if new requirements appear, the developer estimates the cost of additional work and the customer decides whether to make these changes in the program or not. Additional work is also entail a changes to delivery dates of the project. If the customer's description of the application does not allow estimating of the whole project development then development of design document, especially for games, entails a separate contract. This approach reduces the risks for the developer and therefore they are not paid by the client. More information about estimation process in the next section.

I prefer to negotiate with the customer to postpone the implementation of additional ideas, if possible, before the completion of the main contract. In this case, the developer avoids additional, frequently painful, changes in the planning and to the original contract. All changes are made later so-called “change requests” and are made corresponding additions to the main contract.

As result, on the completion of this stage, the developer and the customer must be in sync (on the same page) in the understanding of the project and its requirements. Also, there should be all necessary documentation required to launch the second stage. At least following 2 documents are to be ready before second stage start:

* Design document of application or game (Application Design Document, Game Design Document), that describes the functionality of the application or the game;
* Document that describes the application screens flow (Screen flow diagram) and a list of UI elements with their appointments;

Stage 2. Estimation of project cost.

After developer has project description and its requirements, he begins research of the project's functionality dividing it into separate functional modules and estimate each of them in man-hours. In this article, I will not describe the details of estimation preparation, but I shall briefly describe the structure of the estimation document and things which customer should pay attention to.

After receive of the estimation document you will see a list of tasks, estimated in man-hours and divided into levels - super tasks and their sub tasks. Layering is the obvious thing, because it makes the document structured and facilitates its perception and analysis.

Assume, for example, that a mobile application consists of 4 screens and each screen can be split into components. In this case, estimation document will have a structure like this:

Task name

Time
(man/hrs)

Custom_mobile_application

29

Login screen

12

Enter name field implementation

2

Password field implementation

2

OK button painting

3

Cancel button painting

3

Buttons functionality implementation

1

Login screen testing

1

Info screen

17

Text file loading

2

Text parsing

4

UI elements drawing

6

UI functionality implementation

4

Info screen testing

1


The highest level task, in this case, is the project itself. Its sub tasks are applications screens which have super-task with the name of the project (highest level task). Time for each super-task is the sum of hours of its subtasks. Thus, such document allows you to display only tasks of concrete level you need. There is one important rule that the duration of each task shall not exceed 40 hours, which is one work week. This is the upper limit of duration and depends from estimation detailing requirements, but remember - the less duration of each task the better (precisely) estimation.

Having a list of tasks evaluated in man-hours, we need to calculate total project cost. Every outsourcing company has its own cost rates for one man-hour of work. Thus, it is sufficient to multiply the number of man-hours on their rank and obtain the total cost of the project. Sometimes, outsourcing companies have different rates for each type of work. For example, the man-hour cost of artists, programmers and testers may be different. In this case, the best approach is to divide the tasks by type but super-tasks in the second level will correspond to the type of work (graphics, programming, testing, etc.) and will contain a total man-hours required for each activity. In this case, the estimation document will have a structure like this:

Task name

Time
(man/hrs)

Custom_mobile_application

29

Art

12

Login screen

6

OK button painting

3

Cancel button painting

3

Info screen

6

UI elements drawing

6

Programming

15

Login screen

5

Enter name field implementation

2

Password field implementation

2

Buttons functionality implementation

1

Info screen

10

Text file loading

2

Text parsing

4

UI functionality implementation

4

QA

2

Login screen

1

Login screen testing

1

Info screen

1

Info screen testing

1


In fact, I always use such breakdown, even if the value of all type resources is the same. It is very convenient, because each kind of work is involved to respective of separate team leader (lead artist, lead programmer, etc.) and thus it is easier to control the time, dedicated to each team.

Do not be surprised if you see a super task for such type of work as management. Some companies sell management time additionally. The number of hours allocated to the management, often just a percentage of the total production work (about 10-20%).

I would like also mention few important points for the customer regarding estimation document content. Every estimation includes additional percent of hours for possible risks, bug fixing and customer's feedbacks.

The risks are almost always included to estimation not explicitly and they are included to some specific or even to the all tasks (depending on the type of risks). Most often, the amount of risk associated with new technologies usage and developer's experience in similar projects. Thus, if the developer is not competent in this project then a lot of additional costs will be added to the estimation as risks. The number of hours dedicated for customer's feedback implementation depend on the project specification level, described in detail in the Stage 1 section. Bug fixing will be included in any project, regardless of teams competence and the ease of the project. Feedback and bug fixing are, actually, also risks, but their occurrence probability depends on other factors. Like other risks, the number of hours required for feedback and bug fixing, usually calculated as a percentage of the total production time.

I want to advise outsourcing developers to add assumptions to the estimation document. These are assumption which some of estimation points or tasks were based on. For example, developing a mobile application for navigation, you can add assumption that google static maps service will be used for map visualization. Even if all the nuances were stipulated with the customer in advance, they still should be added as assumptions. Later they will be transferred to the contract, but at the estimation discussion with the customer it is always better to have them in touch. The main sense is to have all the assumptions documented. Even if a project specification describes all requirements in details, you still need to add at least one assumption that estimation was prepared based on that design document.

Finally, in this chapter, I would like to advise customers to provide an outsourcing company so much time for estimation preparation as it needs (within reason). Often, this process requires the developer to conduct some research to answer important questions in order to avoid risks. If you put very strict time line to the developer for estimation process, the you can be sure that all unknown points will spill over in the form of additional hours on the possible risks.


Step 3. Planning project.

To be continued...