Having fun with Adobe AIR

Hi All,
this post will be in Italian, in particular is dedicated to the whole community of Italian mobile developers.
Having fun with Adobe AIR is a free event in 6 different Italian cities where people will learn how to create or improve own cross platform applications made with Adobe AIR for mobile devices.
For any question feel free to leave a comment to this post or drop me an email.

logoOfficial

Ciao a tutti,
mi chiamo Luca Mezzalira e sono l’organizzatore di “Having fun with Adobe AIR” un evento dedicato a tutti gli sviluppatori mobile che vogliono avvicinarsi ad una tecnologia cross-platform, come Adobe AIR, per la realizzazione delle proprie app o game su smartphone o tablet.
In collaborazione con alcuni importanti sponsor, come Adobe e BlackBerry per esempio, che ringrazio innanzitutto, sono riuscito ad organizzare 6 tappe in giro per l’Italia dove in una giornata andremo a scoprire le potenzialità di Adobe AIR, andremo a sviluppare degli esempi pratici che possano far vedere il workflow per la realizzazione di un’applicativo mobile.
Infatti l’evento è basato sulla formula BYOL (Bring Your Own Laptop) dove ogni participante dovrà portare il proprio computer con installato Flash Builder dove potrà creare i proprio applicativi e installarli poi nel proprio tablet o smartphone.

Se ti stai chiedendo se è una perdita di tempo perchè Flash è “morto”, beh credimi, non è così.

Infatti Adobe sta continuando a sviluppare questa tecnologia dando nuove potenzialità per la creazione di applicativi mobile e desktop, dall’accelerazione in GPU all’integrazione con Native Extension e molto altro ancora!

Durante l’evento avremo la fortuna di avere con noi degli speaker Adobe, in alcune tappe, che ci daranno la possibilità di scoprire su cosa si sta concentrando Adobe e quale sarà il futuro della piattaforma.
Un evento totalmente gratuito che credo possa far piacere in Italia a molti sviluppatori che vogliono iniziare a muovere i primi passi nel mondo mobile oppure quelli che già ci lavorano ma vogliono alternative valide con cui sviluppare.
L’evento avrà un massimo di 20 partecipanti circa per tappa e sarà di una giornata, le città in cui si svolgerà saranno Milano, Torino, Bolzano, Padova, Firenze e Bari.
La registrazione è obbligatoria e dev’essere fatta tramite il sito dell’eventohttp://www.havingfunwithadobeair.com/
Se invece preferisci seguirci direttamente sulla nostra pagina facebook ecco l’indirizzo: https://www.facebook.com/pages/Having-fun-with-Adobe-AIR/430003473713246

Per qualsiasi dubbio o domanda non esitare a contattarmi via email o lasciando un messaggio su questo post.
Spero di vederti ad una delle tappe del tour!
A presto

Luca

How to install Apache Flex 4.8.0 SDK in Flash Builder

In this post I’ll explain in an easy step by step tutorial how to install Apache Flex 4.8.0 in Flash Builder, I know that it’s not rocket science but maybe newbie developers could need more information to start play with new SDK.

The new SDK is more or less the same of 4.6 but under Apache flag, like you can read at Spoon website, but we hope people behind the project could give us new opportunities for our RIAs and Mobile projects.

So let’s start!

First of all download Apache Flex 4.8.0 binaries for your operating system (in my case OS X), keep attention, you need the binaries release not the source one.
After unzip the downloaded file create a folder called 4.8.0 in /Applications/Flash Builder 4.5/sdks

Then download playerglobal.swc for Flash Player 11 on Adobe website.

Save it in /Applications/Adobe Flash Builder 4.5/sdks/4.8.0/frameworks/libs (it could be better create a folder called “player” or as you want, in my case I use “11.1″ and save the swc inside).

Finally, open Terminal navigate trough your folders and position it to this location /Applications/Adobe Flash Builder 4.5/sdks/4.8.0/frameworks then launch this ANT command:

ant thirdparty-downloads

After 10 minutes you will download everything:
. OMSF dependencies
. TLF framework
. Flex 4.6 SDK and so on

Last but not least, in Flex 4.8 SDK folder you will find a env-template.properties, you have to duplicate the file, call env.properties and set the right path for each folder:

env.AIR_HOME= path to AIR SDK on your filesystem

env.FLASHPLAYER_DEBUGGER = path to Flash Player Debugger, if you have Flash Pro installed you can find a version in Players/Debug/Flash Player Debugger

env.PLAYERGLOBAL_HOME= path to playerglobal.swc (it’s not an absolute path, it’s relative and starts from frameworks folder in Flex SDK!!!)

env.PIXELBENDER_HOME= path to Pixel Bender Toolkit 2 (it’s not important to set if you don’t use it)

env.ADOBE_EXTENSION_MANAGER= path to Adobe Extension Manager

Remember that in template file you can read an accurate explanation on how to set those environment variables

Then you can start to enjoy the new Flex SDK.

The team behind Flex in Apache is working on a new AIR application that will help you to install in Flash Builder the SDK but it’s not released yet… we hope to have it soon, in the meanwhile I hope this tutorial could help you to set your IDE.
There is another way to install the SDK trough an AIR app that you can download from here: http://people.apache.org/~bigosmallm/installapacheflex/
If I forgot some steps in my description please comment to this post to help everybody to enjoy Apache Flex, thank you in advance.

Dynamic embedding fonts without using Flash or Embed Metadata

I’m working in a new project where we have to automate the integration of fonts loaded on a server by users and integrate them in a Flash / AIR project.
In the most cases, if you search online, you can find 2 main solutions:
1. first one is embedding fonts in a class with [Embed] metadata
2. second one is create a swf file and instantiate the class of Font embedded inside (this method require Flash Pro)

Searching well you can also find a solution with swfmill but there are some problems to integrate with AS3 projects.
Like you know, in my spare time, I’m playing with Haxe and Corona SDK and in this case Haxe help me to accomplish my task.
I found a great library called hxswfl made with Haxe that allow me to create a swf or swc file directly from an XML, there are many other usage of this library that are described on online repository of this project, but what I need this time is use it to create a library with embedded fonts inside with a class name assigned to each font.

So first of all, following the library XML schema, I create a lib with a list of fonts in this way:

<lib>
 <font file="Palatino-Bold.ttf" class="com.insideabit.PalatinoBold"/>
 <font file="Palatino-BoldItalic.ttf" class="com.insideabit.PalatinoBoldItalic"/>
 <font file="Palatino-Italic.ttf" class="com.insideabit.PalatinoItalic"/>
 <font file="Palatino-Roman.ttf" class="com.insideabit.PalatinoRoman"/>
 <font file="Verdana-Bold.ttf" class="com.insideabit.VerdanaBold"/>
 <font file="verdana.ttf" class="com.insideabit.Verdana"/>
</lib>

Any node has 2 attribute, file attribute where I set the path to find my font on filesystem and the class where I set the class name of my font that I’ll use in my actionscript class later.
After download source of hxswfml library (and obviously before anything I’ve installed Haxe in my computer), I go with Terminal in bin/neko folder and I launched neko file (hxswfml.n) with those parameters:

neko hxswfml.n xml2lib librarySWF.xml lib.swf

I’m telling to my neko program that it has to convert my xml to a swf library, embedding inside all fonts described in the XML file with that class name.

Now we have our SWF file with fonts, we can create our Actionscript project and load with a loader object our swf file.
Then, when SWF file is loaded, we have to register our fonts inside the SWF library, you can accomplish this task like this:

 for(var i:int = 0; i < _fontsArr.length; i++){
 var FontLib:Class = _loader.contentLoaderInfo.applicationDomain.getDefinition(FONT_NAME) as Class;
Font.registerFont(FontLib);
}

Ok, now you can use any fonts that you have in your SWF without install them in your laptop and without create any AS3 class, this is a really easy way to work with external fonts in a dynamic way.


Obviously I prepare a sample to download if you have any questions feel free to leave me a message to this post.

It’s not finished yet, because I’ve a question for you: what happens if I use the same technique for different devices?
On web and desktop (AIR application) there are any problem because I can load any external SWF file, the same on Android and Playbook but on iOS?
With iOS you can a SWC file instead a SWF file so your SWC library will be embedded at compile time in your application for iOS and you can access to fonts more easily instantiate directly your class name.


For more information about this technique I suggest to read this article on Adobe DevNet.

Introducing Starling: book review

Hi All,

first of all I apologize with people that usually read this blog if I didn’t insert any new post since last year but I’m working a lots in these few months to open a new market opporunity for my company out of Italy and I’m totally absorbed in this new activity, but in the meanwhile I’m studying during my spare time and I’d like to share with you my thoughts about “Introducing Starling”.

This book is for any Flash Platform developer that is looking to create next generation of mobile and desktop apps (or games).
It’s a book so practical that introduce you to the Starling framework, explaining how it works with simple examples of code that you can put in practice in a while.
Thibault guides you showing each object presents in this framework, that is an abstraction of Stage3D API introduced with Flash Player 11 and AIR 3.
With Starling you can aim better performance in your 2D applications thankfully the GPU acceleration added on Stage3D, with this book you can discover what there is behind and starting to develop with it.

Flash Platform Galaxy: why choose Flash Platform

In those days I’m reading a lots of mailing lists, forums, blogs and so on where Flash Platform supporters are so disappointed about the latest marketing movement of Adobe.

In fact yesterday Adobe announced that they stop the development of Flash Player on Mobile devices (on Desktop they are going ahead).
The road is clear HTML 5 inside the browser and Flash Platform for RIAs, Games and out of browser in combination with Adobe AIR.

For me Adobe for the second time (the first one was during Adobe MAX) has totally mistaken how to communicate this news and obviously tech blogs bring this announcement like the end of Flash…
Personally I don’t think that is the end of Flash but I think that Flash is moving on a new position in multimedia world probably out of browser.
I’m an Adobe addicted, like you know, and in particular I’m a Flash Platform supporter, so I think that we have to move on and make something to spread the word about this foggy situation, guys, Flash Platform is ALIVE!
To do this, I start making a pdf file called Flash Platform Galaxy that could help people to have an idea of what is Flash Platform and why choose it ( I know, I’m not a graphic designer but I think it could be useful), if you want to add more informations or change something feel free to leave a comment at this post or drop me a line via email.
Let’s go guys, we have a platform to save ;)

Playing with Google+ API and Actionscript 3

Yesterday I saw that Google has released Google+ API, so I started to played with in my favorite part of the day: the night!

For now Google has published only public APIs that allow you to retrieve user’s informations and his activities list, all API are made in RESTful and JSON that are so easy to add in your project.
When Google will release next APIs, I hope soon, you can consume them with an oAuth 2.0 authentication, like Facebook.
I made a simple example to retrieve data from my Google+ profile in Actionscript for Android, you can download the source files directly from here.

If you want to play with Google+ API, first of all you have to request your Google+ API key; to do that go to Google API console and activate Google+ service, then in the details page you can find your key.

Google+ RESTful services get us a JSON response, to read it in your Flash/Flex application remember that you need as3corelib that have the JSON deserializer, for example you can push in a generic Object all data retrieved from Google+ service or if you prefer you could create a Value Object that it could be more useful.
In this case I decode directly in a generic Object, like you can see in this code snippet:

var data:Object= JSON.decode(dataToRead, true);

then now you can easily access to informations:

var icon:String = data.image.url;
var name:String = data.displayName;
var tagline:String = data.tagline;
var description:String = data.aboutMe;

Another easy feature that you can add in your Google+ application is a static image of the map, like in your web page, using Google Maps Static API.
You can easily make a query to Google Maps passing in GET params like: the dimension of image, the location and the zoom; you can also add more params that you find in the docs of Google Maps Static API.
Here a code sample to add this feature in your Flash application, in those line I request for an image with width 480px, height 200px, with roadmap skin and with a zoom of 15x:

var mapLoader:Loader = new Loader();
//city is a variable with the name of the place that you have to retrieve.
mapLoader.load(new URLRequest("http://maps.googleapis.com/maps/api/staticmap?center="
+city+"&zoom=15&size=480x200&maptype=roadmap&sensor=true"));
mapLoader.y = this.stage.stageHeight - 200;
addChild(mapLoader);

Like you can see work with those APIs are pretty easy, so now we have to wait for final release and then we can start to create our Google+ integration with the Flash Platform.

Multicast UDP socket in Adobe AIR with Python

In my last project I solved a big issue that I needed to receive notification from an hardware via a Multicast UDP socket.
If you want to know more about Multicast and Unicast in Flash Platform I really suggest to read Flashrealtime blog.
Like you know the Flash Platform can use multicast with RTMFP protocol so you can use it Flash to Flash or Flash to Flash Media Server but not Flash to hardware for example.

In my case I needed a Multicast UDP socket in a local application that communicate with an hardware that was my server, so I thought to realize a Python application for Mac OS X and Windows that could help me to solve this problem.
Python is my second favorite programming language after ActionScript (obviously) and this time Python saves me to accomplish my project.
I want to start with Python side, my goal is to connect to a multicast socket and get all data and then send them to a unicast UDP socket server that we will create in Adobe AIR in next example.

#!/usr/bin/env python
# encoding: utf-8

import socket, select

ANY = '0.0.0.0'
MCAST_ADDR = '239.0.1.1'
MCAST_PORT = 10300

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((ANY,MCAST_PORT))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
status = sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(MCAST_ADDR) + socket.inet_aton(ANY));

sock.setblocking(0)
print 'socket UDP multicast ready'

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

while 1:
	ins, outs, errs = select.select( [ sock ] , [], [], 1.0)
	try:
	    data, addr = sock.recvfrom(1024)
	except socket.error, e:
	    pass
	else:
	    print data
	    udp.sendto(data, (socket.gethostbyname('127.0.0.1'), 10303))

socket.close()

First few lines we define the multicast socket server ip (that in my case is pointing to the hardware) and the socket port to communicate with.
Then I create the UDP multicast socket and the UDP unicast socket (udp var); in the while loop I set the socket timeout and if I receive data trough the multicast socket I send everything to unicast one.
After that to create an application without any dependency in Windows or Mac OS X, you need to use a couple of Python libraries called py2app and py2exe.
Both allow you to create an executable file from your Python script for mac or win without any dependencies, in Windows side you have only to remember which kind of Python dll you have to incapsulate in your AIR application but we take a look at that in a while.
To create the executable file you have to create a setup script in Python for both operating systems, I suggest to create something like that:

FOR WINDOWS:

from distutils.core import setup
import py2exe,sys,os

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
        if os.path.basename(pathname).lower() in ("msvcp71.dll", "dwmapi.dll"):
                return 0
        return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

setup(windows=['myPythonScript.py'])

FOR MAC:

from setuptools import setup

APP = ['myPythonScript.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True}

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

Then if you want to create your executable files you have only need to launch the command on command prompt or terminal (you can find more informations on how to customize those setup scripts in each library’s website):
FOR WINDOWS:

python setup.py py2exe

FOR MAC:

python setup.py py2app

Now we can start with the AIR part, like you know with AIR 2 you can work with Native Process and this is the case to use them:

const WIN_PATH:String = "win/socket.exe";
const OSX_PATH:String = "socket.app/Contents/MacOS/socket";

var nativep:NativeProcessStartupInfo = new NativeProcessStartupInfo();

var finalPath:String;

var f:File
if(Capabilities.os.substr(0, 3) == "Win"){
   finalPath = WIN_PATH
}else{
   finalPath = OSX_PATH
}

f = File.applicationDirectory.resolvePath(finalPath);

nativep.executable = f;

var process:NativeProcess = new NativeProcess();

process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);

process.start(nativep);

var udp:DatagramSocket = new DatagramSocket();
udp.addEventListener(DatagramSocketDataEvent.DATA, getData);
udp.bind(10303);
udp.receive();

function getData(e:DatagramSocketDataEvent):void{
	trace(">>>>>" + e.data.readUTFBytes( e.data.bytesAvailable ))	
}

function onOutputData(event:ProgressEvent):void{
   trace(process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable)); 
}

function onErrorData(event:ProgressEvent):void{
    trace(process.standardError.readUTFBytes(process.standardError.bytesAvailable)); 
}

function onExit(event:NativeProcessExitEvent):void{
   trace(event.exitCode);
}

function onIOError(event:IOErrorEvent):void{
  trace(event.toString());
}

In this simple script I’m choosing the right executable file for the operating system where my AIR application is working on and then I launch the native process to start the multicast socket.
Finally I listen for the unicast socket and I trace on the output panel the messages that I receive from the hardware.
I think this is an interesting way to extend Adobe AIR with Python that open new possibilities on the desktop side, think for example to create a Python bluetooth extension for Adobe AIR, it could be so interesting add this feature to AIR apps isn’t it?

Presentation Model design pattern: multiple screen solution – part 1

Today I’d like to talk about Presentation Model design pattern because it’ll be so useful for anyone that is working on multiple screen project with Flash or Flex.
In latest months we lived in phrenetic mobile world where we have tons of new and powerful devices on the market with different screen sizes, different hardware and so on, on the other hand we have clients that are looking for new business opportunities and they are seeking a way to spend less but earn more.
So, one way to solve those problems could be find a way to deploy with the same technology in different devices (tablets, smartphones, computers…) saving time with great results!
That’s not a dream, it could be made with knowledge, architecture and a good developer or a team!

Our goal

For a developer find a way to have a good project architecture to maintain it’s so important, usually when you start a project you try to define the parts that could be re-usable in different part of the same project or in different project too.
So our aim is find a way to write less code but it will cover the project needs and that could be portable in different screens / operating systems easily.

What is Presentation Model design pattern?

My mentor Martin Fowler describes it with those words: “Represent the state and behavior of the presentation independently of the GUI controls used in the interface”  (here the full article of Martin Fowler).
In fact with this pattern we divide UI (components, movieclips, sprites…) from their behaviors; each view will have one and only that one presentation model and only the presentation model will interact with the whole architecture (like with model or proxy…).
Probably with this image you can easily understand better this concept (from Martin Fowler website):

Like you can see we have 3 class, AlbumTitle that is a view with a textfield, AlbumPresentationModel that is the presentation model of AlbumTitle and it has the copy of the view but storing datas inside and finally the main model Album where we have the data that could be used for the whole application.
There aren’t any connection trough the views and the application model because only the presentation model has access to the whole project, so the view is only a bunch of components and custom graphics, this it means that if you have to change UI on a mobile project for a different device, changing the views and anything else, you will have done your job.
In fact with this easy technique you perfectly solve our problem and you should create the same content for different devices changing only the views.
Probably your application in different devices will have the same functionalities but with a different UI dedicated for the OS is running on.
With this sample design pattern you’ll have a solid infrastructure that will solve the big problem to port the same application in different screen sizes.
So in next paragraph we can take a look on how to organize our files project.

Manage a project for different screen sizes

Another important thing before starts the project is understand how to organize the project for different OS, in fact if you work with Adobe AIR on Android you’ll have only the XML descriptor with Android permissions described in this file, on Playbook you’ll have another XML file dedicated to this platform and so on.
So, my suggestion is to organize the project in different projects that work together.
In this image you can see how I organize it for our final scope, I’ve a common project (Runtime Shared Libraries in this case but you can use also an Actionscript or AIR project if you work with Flash for example) where I’ll put all classes that are common for different target, so in my case all the presentation models, main models, utils classes, my notification bus and views that are common for different projects like components for example.

In the target device projects I add only what I need for that device, in this case only a couple of views and assets but in big projects could be more stuff that those one:

When you have a specific behavior only for a target device, you can easily extends the common presentation model and add new functionalities or create a side class that you’ll add in the specific view.
So with this infrastructure you can solve bugs and change stuff directly on the common project and all the platforms will be ready to package the project and upload to their store. That’s cool, isn’t it?

Summary

So in this post I hope to give you some ideas on how to solve the big problem to create a common base code that could be useful for different purpose.
In next post I’ll show you how to implement it in practice, for now if you have any feedback or suggestions for the second part of this article please add a comment to this post.

Flash Camp Milan review

Yesterday in Milan we had the Flash Camp about Mobile topics and then we had the Flash Camp Party at NH Hotel… really wonderful time.
Like you know, in Italy it’s not so easy to organize those kind of events because usually people don’t move to another city like other foreign countries but Flash Camp had a great success.
This camp was organized in the same place of WhyMCA the mobile revolution, an italian conference focused on mobile topics.
We had 50/60 people per session and I’m glad to say that my session had 80 people so I’m happy about this little success.
All the sessions surfed in deep about CG, design patterns, video optimization for mobile, flex on mobile and so on, so I was really excited to take part in this event.
My session was about Design Pattern for Mobile, I talked about 3 design patterns: Singleton, Observer and Presentation Model.
With a couple of samples (that you can download from this link) and few slides I made an application that run with the same base code on tablet and smartphone; this is an hot topic now on mobile world in particular on Flash Platform side.

In next few weeks I’ll make a post about Presentation Model to share my thoughts about this argument and how to use it in your project , but if you want to start with this topic, take a look at this great post on RIArockstars.

Finally I’d like to thanks the Flash Mind, Adobe Flash Platform User Group Italy, to give me this opportunity, WhyMCA staff for the amazing organization, other speakers of Flash Camp for great time spent together and people that came to talk with us during the Flash Camp and to the beer party too.
I leave also a link to some photos took during Flash Camp in Milan.

Flash Camp in Milan

I’m glad to announce an interesting Flash Camp that will take place in Milan this month at 20 and 21.

All the topics of the Flash Camp will be focused on mobile side, so Flex for mobile device, iOS, Android and Playbook development, code technique for mobile applications, optimizing video content for mobile, design pattern and architecture for mobile project.
Flash camp will be hosted by the whymca the mobile developer conference, that for the second year will show the mobile opportunities not only with Flash Platform but with any technology could be use for mobile purpose.
The event will be in Milan in Milanofiori (Assago), you can find more information on whymca web site.

Back on the Flash Camp side, speakers will be:

Mihai will talk about Flex on mobile devices and how to deploy a content on multiple devices, in the afternoon he has a live coding session where show how to create a mobile application with Actionscript 3.
My good friend Fabio will talk about video encoding optimization for mobile devices, Andrea will show how to create a game cross-platform with Flash Platform and Piergiorgio will give us great suggestions on how to optimize our code and improve the performance of mobile solutions.
Finally me, I’ll talk on how to organize a multiple screen development with Design Pattern and Architecture to re-use code and have great performance on mobile solutions.
For a limit number of people we are organizing a post event for the evening so try to come from the beginning of the Flash Camp and you’ll receive more information about it or keep update reading this blog.
See you there Flashers!!!