flash flex august 2011

55

Upload: cyberstud23

Post on 29-Nov-2014

107 views

Category:

Documents


3 download

TRANSCRIPT

Page 4: Flash Flex August 2011

4

Editor’s Note

08/2011 (26)5

08/2011 (26)

Dear Readers!We are proud to introduce the August issue of Flash & Flex Developers magazine!

The issue covers great deal of interesting topics especially around Programing and how to develop Flex applications. Both topics seem to be obligatory for people who create Flash and Flex applications.

I highly recommend you to have a look at Blitting 10,000 Sprites in Actionscript 3.0 by Craig Beswetherick, and discover the power which blitting brings to Flash games.

Moving on to the Modular Application Development by Karan Nangru, it is worth a while to get to know how to develop Modular Flex Applications usuing Cairngorm Architecture.

After familiarizing with those two articles, we can move forward to Adventures in Actionscript: A Flex FAQ Browser by Huw Collingbourne. This month author deals with displaying XML in nicely formatted way.

I also encourage you to read further articles written by professionals in Flash & Flex and graphics field. I hope that you will find the articles presented in this issue useful and that you will spend some pleasant time reading Flash & Flex Developers magazine.

We put a great effort into this magazine collecting the best articles for our readers. We hope you will appreciate the content of Flash & Flex Developers magazine.

You are welcome to contact us with your feedback.

Enjoy reading!

Enjoy reading!

Best regards,Łukasz Kośka

Publisher: Paweł MarciniakEditor in Chief: Ewa Dudzic [email protected] Editor:Łukasz Kośka [email protected] Team: Ireneusz Pogroszewski Art Director: Ireneusz Pogroszewski [email protected] in Action Section Editor: Huw CollingbourneFlash Animation Section Editor: Craig BeswetherickContributing Editors: Csomák GáborProofreaders: Betsy Irvine

Publisher: Software Press Sp. z o.o. SKul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing

Software Press Sp. z o.o. SK is looking for partners from all over the World.If you are interested in cooperating with us,please contact us by e-mail: [email protected]

Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage.All trade marks presented in the magazine were used only for informative purposes.

FFD magazine is available on iPad thanks to MONOGRAM Interactive, s.r.o.

All rights to trade marks presented in the magazine are reserved by the companies which own them.

Thanks to the most active and helping beta testers:Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-Kielland, Justus, Csomák Gábor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin Adulseranee, Sidney de Koning

To create graphs and diagrams we used program by company.

Mathematical formulas created by Design Science MathType™

ATTENTION!Distributing current or past issues of this magazine – without permission of the publisher – is harmful activity and will result in judicial liability.

DISCLAIMER!The techniques described in our articles may only be used in private, local networks. The edi-tors hold no responsibility for misuse of the presented techniques or consequent data loss.

� ���

Page 5: Flash Flex August 2011

4

Editor’s Note

08/2011 (26)5

08/2011 (26)

Influxis www.influxis.com ..........................................1, 2, 3

Streaming Mediawww.streamingmedia.com/conferences/East2011/ ............................................................................. 17

SapphireSteel Softwarewww.sapphiresteel.com .................................... 23

Kevin Rusehttp://www.kevinruse.com/ ................................ 37ActionScriptJobs www.actionscriptjobs.com ................................ 49

Erainwww.erain.com/ ................................................. 53

Locklizardwww.locklizard.com/ ......................................... 55

Sponsors of the Issue

CONTENTS

InBrief06 NewsBY CSOMÁK GÁBORThis summer Adobe has a challenge: Adobe Mobile Challenge for developers, designers and agencies around the EU territory. What’s really exciting is that you’ll get the chance to win a trip, including flight and hotel, to Adobe MAX in LA this October.

FLASH ANIMATION8 Blitting 10,000 Sprites in Actionscript 3.0 BY CRAIG BESWETHERICKIn this article we extend the code written in the last tutorial. We reuse the blitted animation to animate 10,000 sprites at 12fps, pushing the limits of what you can achieve with the Flash Player. Faster computers may be able to run more than this; I am able to run 15,000 without any drop in frame rate, so feel free to explore the upper boundary.

FLEX DEVELOPMENT18 Modular Application DevelopmentBY KARAN NANGRUWhile there are a lot of sources available online that demonstrate building flex applications using Cairngorm Architecture, not many serve the cause if you intend to develop Modular Flex Applications using Cairngorm Architecture. 24 Ioc I10n Localizing Your Apps with BabelFx BY MARC PIRESWhen developing an Application that targets a broad audience, a topic you’ll be dealing with is, localization. In this article we’ll see how to make this task much easier using the BabelFx Localization Framework.

ACTIONSCRIPT IN ACTION30 A Flex FAQ BrowserBY HUW COLLINGBOURNELast month I showed how to program an application that could both create and load XML data files. This made it easy to construct individual data records by entering text into the fields on a form and then saving a database in XML format on disk. I used the same application to load the XML data from the file. However, that application made no attempt to display the XML in a nicely formatted way. I’ll deal with that problem now.

PROGRAMING34 Objective C Fundamentals: BoxingBY CHRISTOPHER K. FAIRBAIRN, JOHANNES FAHRENKRUG, AND COLLIN RUFFENACHWhile NSNumber provides a convenient and clean interface for boxing and unboxing numerical based primitive types, NSValue allows you to box and unbox any C-style value at the expense of having a slightly more complex interface to program against.

38 Objective C Fundamentals: NSXML ParserBY CHRISTOPHER K. FAIRBAIRN, JOHANNES FAHRENKRUG, AND COLLIN RUFFENACHApple provides a class called NSXMLParser to iPhone developers. Developers use this class when parsing XML. This article from Objective-C Fundamentals shows that NSXMLParser provides delegate methods that handle every point of parsing for both XML- and DTD-based documents.

DESIGN42 How to Promote a More Seamless Designer/Developer Workflow BY PAUL TRANIOne of the biggest issues in an application UI development process is the workflow between the designer and the developer. The designer is rightly concerned about the integrity of the design, while the developer is also concerned about the functionality of the final application.

PRODUCT REVIEW46 KoolMoves 8.1.1BY PEDRO DE LA ROQUEKoolMoves is a flash authoring tool sold for fifty dollars. It offers different work environments for beginners and advanced users, so it serves almost any Flash developer. 50 The Flex KC-Calendar ComponentBY KEEPCOREKeepCore designs and develops Flex components that they sell worldwide. Their key component, the KC-Calendar is the most powerful on the market, referenced by Adobe.com on Le Tour de Flex.

BOOK REVIEW52 Flex for FunBY ALI RAZAAs of now, there are so many books available on Adobe Flex that cater the needs of both a beginner and somewhat advanced developers. However, until now, there was no book that would teach and share the visual aspects of Adobe Flex in depth.

INTERVIEW54 Interview with Johannes FahrenkrugBY FFD TEAMInterview with Johannes Fahrenkrug – One of The Authors of Objective C Fundamentals.

Page 6: Flash Flex August 2011

6

IN BRIEF

08/2011 (26)

Fash Player 11 and AIR 3 public betaSome nice awaited community features are shipping here like removing BitmapData restrictions, Socket progress events, native JSON, etc but also other awaited features like native 64-bit support or Stage3D (aka Molehill). Of course Adobe is working hard on mobile builds too, at this time the AIR 3 SDK is not available in a public beta.

There is no 64-bit debugger builds, because Flash Player is supported on 64-bit platforms for content playback. Given the architecture changes required for 64-bit debugging, support for content development will be made available in the next generation of Flash Platform tooling which is currently under development.

Finally, as 3D and security have been a topic of interest lately. The New Features in both Flash Player 11 and AIR 3

• Stage3D Accelerated Graphics Rendering – Stage3D („Molehill”) is a new architecture for hardware accelerated graphics rendering developed by Adobe. Stage3D provides a set of lowlevel APIs that enable advanced 2D/3D rendering capabilities across screens and devices (desktop, mobile, and TV). It gives 2D and 3D app and framework developers access to high performance GPU hardware acceleration, enabling the creation of new classes of rich, interactive experiences. Note: These pre-release builds include Flash Player and AIR desktop support; AIR for Android and iOS support will be enabled in a future pre-release build.

• Flash Access Content Protection Support for Mobile – Flash Access content protection support is now available on mobile devices.

• H.264/AVC Software Encoding for Cameras (desktop) – Stream high quailty video from your computer’s camera with higher compression efficiency and industry-wide support, enabling both immersive real-time communications (e.g., video chat and video conferencing) and live video broadcasts.

• Native JSON (JavaScript Object Notation) Support – Allows ActionScript developers to take advantage of high performance native parsing and generation of JSON-formatted data. Developers can integrate existing data seamlessly into their projects.

• G.711 Audio Compression for Telephony – Support interoperability with legacy phone systems via the Flash Media Gateway (FMG) and other third-party clients (through the open RTMP protocol) without the need for transcoding.

• Garbage Collection Advice – Provides smoother, more responsive user experiences by allowing developers to provide hints (through System.pauseForGCIfCollectionImminent) to optimize garbage collection scheduling.

• Cubic Bezier Curves – The Graphics.cubicCurveTo

drawing API allows developers can easily create complex cubic Beziers without requiring custom ActionScript code.

• Secure Random Number Generator – Developers can now take advantage of cryptographically secure random number generation to build more secure algorithms and protocols.

• Protected HTTP Dynamic Streaming (HDS) and Flash Access Enhancements – Protected HTTP Dynamic Streaming (HDS) provides protection for streaming video across screens while eliminating the deployment complexity of a license server. New Flash Access content protection features include key rotation support, V3 license chaining, domain support, and enhanced output protection and device filtering.

• Socket Progress Events – Improve management of data transfer using the Socket class by providing a new property to determine the number of bytes remaining in the write buffer and a new event for when data is being sent to the network layer. The new APIs (Socket.bytesPending, Event.OutputProgressEvent) allow applications can easily track progress and provide responsive feedback.

• Native Text Input UI (mobile) – Mobile apps can now take advantage of the native text input controls on mobile platforms, including platform-specific user interaction behaviors such as magnification and text selection. Native text controls are available on Android, BlackBerry Tablet, and iOS operating systems.

• JPEG-XR support – Flash Player and AIR now include support for the JPEG-XR advanced image compression standard (International Standard ISO/IEC 29199-2). The computationally lightweight JPEG-XR format provides more efficient compression than JPEG, enables both lossy and lossless compression support, and adds support for alpha channel transparency.

• Enhanced high resolution bitmap support – BitmapData objects are no longer limited to a maximum resolution of 16 megapixels (16,777,215 pixels), and maximum bitmap width/height is no longer limited to 8,191 pixels, enabling the development of apps that utilize very large bitmaps.

• High efficiency SWF compression support – Developers can now take advantage of LZMA compression for their SWF files. LZMA compression can reduce SWF size by up to 40%, enabling users to benefit from richer experiences with shorter download times and reduced bandwidth consumption. Use Tinic’s tool or a custom one to compress your SWF’s.

Page 7: Flash Flex August 2011

• DisplayObjectContainer.removeChildren and MovieClip.isPlaying – DisplayObjectContainer now implements a removeChildren API allowing developers to quickly remove all of a container’s children using a single API.

New Features in Flash Player 11

• Native 64-bit Support (Flash Player desktop) – Take advantage of native support for 64-bit operating systems and 64-bit web browsers on Linux, Mac OS, and Windows.

• Asynchronous Bitmap Decoding (new for Flash Player) – Improve app responsiveness and deliver smoother animation by decoding images on initial load instead of on demand. Images are cached as needed.

• TLS Secure Sockets Support (new for Flash Player) – Enables secure communications for client/server applications.

New Features in AIR 3• Stage Video Hardware Acceleration (new for AIR)

– Leverage hardware acceleration of the entire video pipeline to deliver efficient, best-in-class high-definition (HD) video playback experiences. Decrease processor usage and enable smoother video, reduced memory usage, and higher fidelity on mobile*, desktop, and TV devices (*supported on Android 3.1, BlackBerry Tablet OS, and iOS).

source: ByteArray.org

$200k – Adobe AIR App Challenge for Sony Tablets This summer seems like one for Flash and Mobile, so it’s great to be able to tell you that Sony, one of Adobe’s long term partners in mobile, are joining the Open Screen Project and will be a platinum sponsor of Adobe MAX in LA.

They’re announcing an exciting new Adobe AIR App Challenge for two upcoming Sony Tablet devices. It’s available to those of you in Germany, Italy, Japan, Spain, UK and USA.

There are lots of prizes ($200,000 USD) available for various categories of applications, as well as early access to the devices and Adobe AIR 3, and a paid-up trip to Adobe MAX for finalists. All that and more for optimizing your applications for Sony’s new devices.

source: ByteArray.orgource: www.flashmobileblog.com

EU – Adobe Mobile ChallengeThis summer Adobe has a challenge: Adobe Mobile Challenge for developers, designers and agencies around the EU territory. What’s really exciting is that you’ll get the chance to win a trip, including flight and hotel, to Adobe MAX in LA this October. The aim is to build applications that reach across different mobile platforms and that are published widely, on the Apple AppStore, Android Market and of course the Blackberry AppWorld for the PlayBook.You’re application can be a game or branded content, anything goes really as long as your application is available in each store by the deadline below.

source: www.flashmobileblog.com

AIR Applications Tops iOS Charts!The good news keeps rolling in about AIR on mobile. While Ponycorn Adventure Featured on the iOS App Store, Politifact is on top of charts. It was the #1 paid news application on the iOS App Store for a time. This is huge as it is more evidence of the success of real-world, paid applications built using Flex and AIR. Politifact is now the 111th top paid app in the whole app store.

source: The Flash Blog

News selected by Gábor Csomák

Page 8: Flash Flex August 2011

08/2011 (26)8

FLASH ANIMATION

In this article we extend the code written in the last tutorial. We reuse the blitted animation to animate 10,000 sprites at 12fps, pushing the limits of

what you can achieve with the Flash Player. Faster computers may be able to run more than this; I am able to run 15,000 without any drop in frame rate, so feel free to explore the upper boundary. Finally I show you how to implement hit tests within the system, so you can begin to think about how you would use this within a game, or any other project where a high amount of sprites are required.

Before attempting this tutorial make sure you have downloaded the source files. Copy the content of the files into a new folder on your computer. The fla is already set up with a document class called BlittingEngineTest.as which contains some of the code we wrote in the previous article. Note that all rendering functionality has been deleted and the blitting engine has been moved into the package shown:

com.grindheadgames.blittingsprites.BlittingEngine

I have also included all the imports we will need for the BlittingEngineTest.as:

import flash.display.Bitmap;

import flash.display.BitmapData;

import flash.display.Sprite;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.geom.Point;

import flash.geom.Rectangle;

The first task we are going to do is create and render the background within the update loop. Add the following variables to the BlittingEngineTest.as file:

private var backgroundBitmapData:BitmapData =

new BitmapData(800,600),

screenBitmapData:BitmapData,

screenBitmap:Bitmap;

Blitting 10,000 Sprites

In the July issue of Flash and Flex Development Magazine, I showed you how to create a reusable blitting class that you could use to read a spritesheet and cache the data to memory. We covered how to control the animation through event listeners, and how to render the artwork to a single Bitmap.

What you will learn…• Blitting Multiple Sprites• Collision Detection using BitmapData• Rendering all artwork a single screen bitmap

What you should know…• How to blit an animation to memory• How to control the animation frames• How to render the cached animation to the screen

in Actionscript 3.0

Listing 1. Initializing the screenBitmap

//create a bitmapData for the

displayed test animation;

screenBitmapData = new

BitmapData( 800,600, true);

screenBitmap = new Bitmap(

screenBitmapData );

addChild( screenBitmap );

Page 9: Flash Flex August 2011

Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 9

screenBitmap variables. We will use these variables to render all the content to the screen, instead of having multiple sprites added to the display list.

We first create a background BitmapData() the same size as our stage, and store it in the backgroundBitmapData variable. Also add a the screenBitmapData and

Listing 2. BlitSprite.as

package com.grindheadgames.blittingsprites

{

import flash.display.BitmapData;

import flash.display.Sprite;

import flash.events.MouseEvent;

public class BlitSprite extends Sprite

{

private var spriteArray:Array = [];

private var isPlaying:Boolean = false;

private var idx:int;

public var frame:BitmapData;

public function BlitSprite(spriteArray:Array)

{

super();

this.spriteArray = spriteArray;

frame = spriteArray[spriteArray.length-1];

}

public function playAnimation():void

{

idx = 0;

frame = spriteArray[0];

isPlaying = true;

}

public function update():void

{

if( isPlaying)

{

frame = spriteArray[idx];

idx += 1;

if(idx >= spriteArray.length)

{

idx = 0;

isPlaying = false;

}

}

}

}

}

Page 10: Flash Flex August 2011

08/2011 (26)10

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 11

Within the init function, add the following lines to initialize the screen bitmap, and add it to the display list, as shown in Listing 1.

Our next task is to update the loop function, so that we copy the background bitmap to the screen on each ENTER_FRAME event. Add the following lines to the loop() function:

screenBitmap.bitmapData.copyPixels(backgroundBitmapData,

new Rectangle(0,0,800,600),new Point(0,0));

Our project, if tested, will now blit the spritesheet from the previous tutorial to memory, but it will not display the animation. The screenBitmap will be updated with every ENTER _ FRAME event with the cached background we stored inside the backgroundBitmapData variable.

Great. Now lets create some sprites to animate over that background we now have working. Create a new class called BlitSprite.as in the:

com.grindheadgames.blittingsprites

Listing 3. The update loop

public function update():void

{

if( isPlaying)

{

frame = spriteArray[idx];

idx += 1;

if(idx >= spriteArray.length)

{

idx = 0;

isPlaying = false;

}

}

}

Listing 4 Creating Multiple Sprites

var xLoc:int,

yLoc:int;

for(var i:int = 0; i < 12000; i ++)

{

var animation:Array = blitEngine.animationList["testSpritesheet"];

var sprite:BlitSprite = new BlitSprite( animation );

spriteList.push( sprite );

sprite.x = xLoc;

sprite.y = yLoc;

xLoc += TILE_WIDTH / 2;

if(xLoc > stage.stageWidth - TILE_WIDTH )

{

yLoc += TILE_HEIGHT / 2;

xLoc = 0;

}

}

Page 11: Flash Flex August 2011

08/2011 (26)10

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 11

We will use BlitSprite.as for each of the sprites we animate and use it to control their individual states. We pass to the BlitSprite class the array of frames contained within the animation, which it will store for later. The entire code for this new class is contained in Listing 2.

You will notice several variables at the top of this class. Inside the constructor, an array of frames is received and stored into the spriteArray variable. We then set the frame variable which a reference to the current frame to be rendered. In this case is the last frame of the animation.

The idx variable is an index used to specify which frame we want to display. We increment this value as we loop through each frame in the cached spriteArray. The animations in the final project do not loop indefinitely, so we use the idx variable to calculate if we are at the end of the animation cycle. The isPlaying Boolean controls the state of the sprite, and is set to false if the animation has completed.

To tell this sprite to play, we need to call the playAnimation() function. The code can be found below:

public function playAnimation():void

{

idx = 0;

frame = spriteArray[0];

isPlaying = true;

}

This function resets the current index to be displayed to 0. The frame variable is set to the first frame of the animation, and the Boolean variable is set to true.

The BlitSprite class finally needs an update function, so that we can check the state of the sprite an update the frame variable as required. The code for the update() function can be found (see Listing 3).

Inside the function, we first check to see if the sprite is currently playing. If it is playing, then we update the frame variable with the correct animation frame from the spriteArray. We increment the index by 1, and then check to see if we are at the end of the animation. If we are at the end of the animation, and the index is greater than the total number of frames there are to display, then we must set the index back to 0 and set the isPlaying variable to false. This changes the state of the sprite and will stop the animation from playing at the end of the cycle.

That’s all there is to the BlitSprite.as class. It is used to store the information about which frame of the animation it needs to display, and to control the state of the sprite. Now that it is complete, lets put it to good use and see what it can do.

We are now going to create 10,000 BlitSprites, and animate them with the blitted animation we created in

Listing 5. Updating and drawing each sprite

for each( var bs:BlitSprite in spriteList )

{

tempPoint.x = bs.x;

tempPoint.y = bs.y;

screenBitmap.bitmapData.copyPixels( bs.frame,spriteR

ect,tempPoint,null,null,true);

}

Listing 6. Adding a custom cursor

private var crosshair:Crosshair_PNG = new Crosshair_

PNG(50,50);

private var crosshairRect:Rectangle = new Rectangle(0

,0,50,50)

private var mousePoint:Point = new Point();

Listing 7. Adding mouse listeners

stage.addEventListener( MouseEvent.MOUSE_DOWN,

mouseDown,false,0,true);

stage.addEventListener( MouseEvent.MOUSE_UP,

mouseUp,false,0,true);

private function mouseDown(e:MouseEvent):void

{

mouseIsDown = true;

}

private function mouseUp(e:MouseEvent):void

{

mouseIsDown = false;

}

Listing 8. Scrolling Detection

up = false

down = false;

if( this.mouseY < 50 )

{

up = true;

}

if( this.mouseY > 550 )

{

down = true;

}

Page 12: Flash Flex August 2011

08/2011 (26)12

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 13

the first tutorial. Open up BlittingEngineTest.as and add the following variables:

private var spriteList:Array = [];

private var spriteRect:Rectangle =

new Rectangle(0,0,TILE_WIDTH,TILE_HEIGHT);

private var tempPoint = new Point();

The spriteList variable is an array used to store all the BlitSprite instances that we create. The spriteRect is a rectangle we use in copyPixel() operations to specify the size of the animation we are drawing to the screenBitmapData(). We also create a tempPoint to use in later copyPixels() operations to specify where each BlitSprite should be drawn. We use these variable within the update method, so creating the Point() and Rectangle() classes here is a simple optimization to avoid creating new instances within the update loop.

Now the variables created, we can add the code to create the 10,000 explosion BlitSprites. Add this code to the init function, after the animation has been blitted by the blitEngine, as shown in Listing 4.

The code loops through and instantiates 10,000 BlitSprites, placing them evenly down the screen. We

increment the x and y positions set the positions of the blitSprites, and make sure they cascade vertically. Each sprite is pushed into the spriteArray, so we can loop through them in the update function. Notice that the BlitSprites are not added to the displayList.

Now we can update the loop() function to draw each sprite to the screenBitmapData. Add the following code to the loop function, after you have drawn the background to the screenBitmapData variable, as shown in Listing 5.

Now we have all the BlitSprites drawn to the screen, we can add a bit of functionality to control their behavior, and detect hit tests against the sprites.

Lets start by adding a crosshair that follows the mouse. Add the following variables near the class definition, as shown in Listing 6.

The crosshair variable is used to hold a Crosshair PNG from FLA included with this issue. The crosshairRect is used to specify the size of the crosshair and like the mousePoint variable, is created here to avoid being instantiated within the update loop. Again, this is a simple optimization.

We need to update the position of the mousePoint within the update function. Add the following lines to the top of the loop() function:

Listing 9. Scrolling and collision detection

for each( var bs:BlitSprite in spriteList )

{

bs.update();

if(down)

{

bs.y -= 10;

}

if(up)

{

bs.y += 10;

}

tempPoint.x = bs.x;

tempPoint.y = bs.y;

screenBitmap.bitmapData.copyPixels( bs.frame,spriteRect,tempPoint,null,null,true);

if(mouseIsDown && bs.frame.hitTest( tempPoint,255, crosshair, mousePoint, 1))

{

bs.playAnimation();

}

}

Page 13: Flash Flex August 2011

08/2011 (26)12

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 13

Listing 10a. BlittingEngineTest.as

package

{

import com.grindheadgames.blittingsprites.BlitSp

rite;

import com.grindheadgames.blittingsprites.Blittin

gEngine;

import flash.display.Bitmap;

import flash.display.BitmapData;

import flash.display.Sprite;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.geom.Point;

import flash.geom.Rectangle;

//[SWF(width="800", height="600", frameRate="25",

backgroundColor="#FFFFFF")]

public class BlittingEngineTest_Example extends

Sprite

{

private static const TILE_WIDTH:int

= 256,

TILE_HEIGHT:int = 256;

private var backgroundBitmapData:

BitmapData = new

BitmapData(800,600),

screenBitmapData:BitmapData,

screenBitmap:Bitmap;

private var spriteList:Array = [];

private var spriteRect:Rectangle

= new Rectangle(0,0,TILE_

WIDTH,TILE_HEIGHT);

private var tempPoint = new Point();

private var crosshair:Crosshair_PNG = new Crosshair_

PNG(50,50);

private var crosshairRect:Rectangle

= new Rectangle(0,0,50,50);

private var mousePoint:Point = new

Point();

private var mouseIsDown:Boolean =

false;

private var up:Boolean;

private var down:Boolean;

public function BlittingEngineTest_

Example()

{

//test the engine

runBlitToScreenTest();

}

// ******************

** testing

****************************

private function

runBlitToScreenTest():void

{

this.addEventListener(Event.ADD

ED_TO_STAGE, init);

}

private function init(e:Event):void

{

this.removeEventListener(Event.

ADDED_TO_STAGE, init);

//create a new blittingEngine

var blitEngine:BlittingEngine =

new BlittingEngine()

//create a spritesheet from the

library.

var testSpriteSheet:BitmapData

= new Tilesheet_JPG(2048,2048);

//pass the spritesheet to

the bliting engine. Define

the animationName:String,

spritesheet:BitmapData, numCol:

int, numRow:int, colSize:int,

rowSize:int, numTiles:int

blitEngine.blitSprites

heet("testSpritesheet",

testSpriteSheet,8, 4, TILE_

WIDTH,TILE_HEIGHT,25 );

var xLoc:int,

yLoc:int;

Page 14: Flash Flex August 2011

08/2011 (26)14

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 15

Listing 10b. BlittingEngineTest.as

for(var i:int = 0; i < 12000;

i ++)

{

var animation:Array = blitE

ngine.animationList["testSprite

sheet"];

var sprite:BlitSprite = new

BlitSprite( animation );

spriteList.push( sprite );

sprite.x = xLoc;

sprite.y = yLoc;

xLoc += TILE_WIDTH / 2;

if(xLoc > stage.stageWidth

- TILE_WIDTH )

{

yLoc += TILE_HEIGHT / 2;

xLoc = 0;

}

}

//if you like, trace out the

number of frames to make sure

its correct.

trace( "ANIMATION FRAME COUNT =

", animation.length );

//create a bitmapData for the

displayed test animation;

screenBitmapData = new

BitmapData( 800,600, true);

screenBitmap = new Bitmap(

screenBitmapData );

addChild( screenBitmap );

addEventListener(Event.ENTER_

FRAME, loop);

stage.addEventListener(

MouseEvent.MOUSE_DOWN,

mouseDown,false,0,true);

stage.addEventListener(

MouseEvent.MOUSE_UP,

mouseUp,false,0,true);

}

private function mouseDown(e:

MouseEvent):void

{

mouseIsDown = true;

}

private function mouseUp(e:

MouseEvent):void

{

mouseIsDown = false;

}

private function loop(e:Event):void

{

screenBitmap.bitmapData.copy

Pixels(backgroundBitmapData,n

ew Rectangle(0,0,800,600),new

Point(0,0));

up = false

down = false;

if( this.mouseY < 50 )

{

up = true;

}

if( this.mouseY > 550 )

{

down = true;

}

mousePoint.x = mouseX-

crosshairRect.width /2;

mousePoint.y = mouseY-

crosshairRect.height/2;

for each( var bs:BlitSprite in

spriteList )

{

bs.update();

if(down)

{

bs.y -= 10;

}

if(up)

{

bs.y += 10;

}

Page 15: Flash Flex August 2011

08/2011 (26)14

FLASH ANIMATION Blitting 10,000 Sprites in Actionscript 3.0

08/2011 (26) 15

Listing 10c. BlittingEngineTest.as

tempPoint.x = bs.x;

tempPoint.y = bs.y;

screenBitmap.bitmapData.copy

Pixels( bs.frame,spriteRect,temp

Point,null,null,true);

if(mouseIsDown &&

bs.frame.hitTest( tempPoint,255,

crosshair, mousePoint, 1))

{

bs.playAnimation();

}

}

screenBitmap.bitmapData.copyPix

els( crosshair,crosshairRect,mou

sePoint,null,null,true);

}

}

}

Listing 11. BlitSprite.as

package com.grindheadgames.blittingsprites

{

import flash.display.BitmapData;

import flash.display.Sprite;

import flash.events.MouseEvent;

public class BlitSprite extends Sprite

{

private var spriteArray:Array = [];

private var isPlaying:Boolean =

false;

private var idx:int;

public var frame:BitmapData;

public function

BlitSprite(spriteArray:Array)

{

super();

this.spriteArray = spriteArray;

frame = spriteArray[spriteArray

.length-1];

}

public function playAnimation():void

{

idx = 0;

frame = spriteArray[0];

isPlaying = true;

}

public function update():void

{

if( isPlaying)

{

frame = spriteArray[idx];

idx += 1;

if(idx >=

spriteArray.length)

{

idx = 0;

isPlaying = false;

}

}

}

}

}

Page 16: Flash Flex August 2011

08/2011 (26)16

FLASH ANIMATION

mousePoint.x = mouseX-crosshairRect.width /2;

mousePoint.y = mouseY-crosshairRect.height/2;

Then, add the end of the loop function, add the following code:

screenBitmap.bitmapData.copyPixels( crosshair,crosshairR

ect,mousePoint,null,null,true);

This will draw the crosshair BitmapData to the screenBitmapData, in the position of the mouse. We use the crosshairRect variable to define the area of the crosshair, and the mousePoint variable to define the location. We add the copyPixel() operation to the end of the function because we want the crosshair to be drawn on top of the sprites, which are drawn to the screenBitmapData within the for each function.

The crosshair should now follow the mouse around the screen, and be drawn above the sprites, and over the background. We want to be able to make the barrels explode when we click on them, and to do this we need to detect when the mouse is down, and also if the crosshair is hitting a barrel. There is also another problem of being unable to view all 10,000 barrels, so we need to add some functionality to be able to scroll through them.

First, lets add the code to detect if the mouse is down, and to scroll the barrels. Add the following variables to the top of the BlitEngineTest.as class:

private var mouseIsDown:Boolean = false;

private var up:Boolean;

private var down:Boolean;

The mouseIsDown variable is a simple Boolean to define if the mouse is down or not. We will use the up and down variables to decide if the barrels should move up or down. Add the following event listeners to the init function, to pick up the mouse events, and to set the mouseIsDown variable, as shown in Listing 7.

To set the up and down variables, add the following code to the loop function, as shown in Listing 8.

At the start of each loop, we set up and down to false, to stop any scrolling that we do not want to occur. If the mouse is at the top or the bottom of the screen, then we set up or down to true respectively.

We now need to edit the code, to move the sprites if the user the scrolling. We are also going to add the functionality to detect the collision between the crosshair and the BlitSprite animation. To do this, edit the for each statement in the loop() function so it appears like the Listing 9.

The first edit is to move each BlitSprite in the correct direction if the user is scrolling. We next add the if statement check to see if the mouse is down. We check

the mouseIsDown variable first, so that we do not make unnecessary hitTest calls.

To make the hit test work, we set the tempPoint position to the position of the BlitSprite. We test the blitSprite frame hitting against the crosshair, at the position of the mouse stored inside the mousePoint variable. If the hitTest returns true, then a hit has been detected, and we tell the BlitSprite() to play the animation by calling the playAnimation() method.

The both classes should appear like Listing 10 and 11.

If you run this code, you should be able to play the demo, scroll through each barrel created and make each barrel explode. I encourage you to explore the maximum number of BlitSprites your computer can handle, as this will vary depending upon your hardware. You could also try create a simple vector animation test, by creating a timeline animation and then multiple instances to the display list. Comparing the results will be interesting, please get in touch with your results.

These tutorials should have given you an understanding of how to begin creating sprites that use a blitted animation to render their artwork to a single bitmap. They should have explained to you the power of blitting, and how to perform collision detection using BitmapData. There are many more features and improvements you could make to this code, this is only a basic example. I encourage you to take blitting further, and create much more complex BlitSprites and applications from the lessons learnt here.

CRAIG BESWETHERICKCraig Beswetherick is a casual games developer from Cornwall, UK. Currently based in London, Craig works for Substance during the day creating games for the �lm industry and by night he works on his own indie games projects under the name Grindhead Games.Follow Craig on twitter - @grindheadgames

Page 18: Flash Flex August 2011

08/2011 (26)18

FLEX DEVELOPMENT

Modular Application Development Over the past few years, Cairngorm architecture has been hugely embraced for developing enterprise Flex applications.

What you will learn…• How to design enterprise �ex applications.• How to merge applications built on Cairngorm architecture.• How to modularise the Cairngorm architecture.

What you should know…• Knowledge of Flex 3• Basic knowledge of Cairngorm Architecture• Knowledge of OOPS concepts

Using Cairngorm Architecture

Figure 1. Directed network

Page 19: Flash Flex August 2011

Modular Application Development Using Cairngorm Architecture

08/2011 (26) 19

Brief Description of Flex Modules:Flex Modules are code functionality compiled to dynamically-loadable SWF files that can be loaded and unloaded by an application at run-time.

Modules let you split your application into several pieces, or modules. The main application, or loader, can dynamically load other modules that it requires, when it needs them. It does not have to load all modules when it starts, nor does it have to load any modules if the user does not interact with them.

Pictorial Description of Cairngorm ArchitectureConsider the following scenario: Your team is working on a flex project that is part of the bigger picture (a baseline Flex Application). You might develop your project using an independent cairngorm architecture (One that does not interact with the bigger picture). Concisely, you are developing a flex module that will be called from a flex application.

In such scenarios, if the module does not have much dependency on the parent application then the module-application integration is many a times postponed till the module starts bearing the fruits, thereby delaying the bitter task of merging architectures (This should generally be a task that should be initiated as soon as you analyze the module design).

While there are a lot of sources available online that demonstrate building flex applications using Cairngorm Architecture, not many

serve the cause if you intend to develop Modular Flex Applications using Cairngorm Architecture.

Listing 1. Controller Impl

package xyz

{

import com.adobe.cairngorm.control.FrontController;

import mx.collections.ArrayCollection;

import .......control.*;

import .......commands.*;

import .......CommandDesc;

public class BaseApplicationController extends

FrontController

{

public function BaseApplicationController()

{

initialiseCommands();

}

public function initialiseCommands() : void

{

//Add all the application level commands

addCommand( baseEventName1, baseCommandClass1 );

addCommand( baseEventName2, baseCommandClass2 );

addCommand( baseEventName3, baseCommandClass3 );

addCommand( baseEventName4, baseCommandClass4 );

}

//Add all module level commands

public function addCommands(commandList:

ArrayCollection):void{

for(var i:int=0;i

var commDes:CommandDesc =commandList.getItemAt(i) as

CommandDesc;

this.addCommand(commDes.getEventName(),commDes.getCo

mmand());

}

}

//Remove all module level commands

public function removeCommands(commandList:

ArrayCollection):void{

for(var i:int=0;i

var commDes:CommandDesc =commandList.getItemAt(i) as

CommandDesc;

this.removeCommand(commDes.getEventName());

}

}

}

}

Listing 2. Command Impl

package abc

{

import com.adobe.cairngorm.commands.Command;

public class CommandDesc

{

private var eventName:String;

private var command:Class;

public function getEventName():String{

return eventName;

}

public function setEventName(eventName:String):

void{

this.eventName = eventName;

}

public function getCommand():Class{

return command;

}

public function setCommand(command:Class):void{

this.command = command;

}

}

}

Page 20: Flash Flex August 2011

08/2011 (26)20

FLEX DEVELOPMENT Modular Application Development Using Cairngorm Architecture

08/2011 (26) 21

While merging Flex Modules and Application that are independently designed using Cairngorm Architecture, following classes should be paid attention to and handled as follows:

ControllerThe Controller is the most sophisticated part of the Cairngorm architecture. The Controller layer is implemented as a singleton FrontController. The FrontController instance, which receives every View-generated event, dispatches the events to

the assigned Command class based on the event’s declared type.

Modules can use the controller of the base class. In such a case, all commands of the module need to be registered with the main controller at the time of module load, and, should thereby be removed when the module is unloaded.

Where CommandDesc.as contains the module level event name and the corresponding Command class: Listing 2.

ModelIn a Cairngorm Model, related data are stored in Value Objects (VOs), while simple variables can be stored as direct properties of the ModelLocator class. A static reference to the ModelLocator singleton instance is used by the View layers to locate the required data.

The modelLocator directive is such, that, its always better not to merge modelLocator implementations of the module and the application (since modelLocator contains a lot of contextual information).

Following is a change that needs to be incorporated on the module side, as well as the application sideSince modelLocator is singleton, we should create a modelLocator implementation in the interface gateway (generally compiled as a SWC) that is used for the

Listing 3. ModelLocator(Interface level) Impl

package externalInterface

{

import com.adobe.cairngorm.model.ModelLocator;

public class InterfaceModelLocator implements com.a

dobe.cairngorm.model.ModelLocato

r

{

public static var interfaceModelLocator:

InterfaceModelLocator;

private var _modelMap:Object = new Object();

public function addModel(key:String, model:

Object):void{

_modelMap[key] = model;

}

public function getModel(key:String):Object{

return _modelMap[key];

}

public function deleteModel(key:String):void{

_modelMap[key] = null;

}

public function InterfaceModelLocator(){

if(interfaceModelLocator != null){

throw new Error( "Only one ModelLocator

instance should be instantiated"

);

}

}

public static function getInstance():

InterfaceModelLocator{

if ( interfaceModelLocator == null )

{

interfaceModelLocator = new

InterfaceModelLocator();

}

return interfaceModelLocator;

}

}

}

Listing 4. ModelLocator (Application level) Impl

[Bindable]

public class ApplicationModelLocator extends

InterfaceModelLocator

{

private static var modelLocator :

ApplicationModelLocator;

public static function getInstance() :

ApplicationModelLocator

{

if ( modelLocator == null )

{

modelLocator = new ApplicationModelLocator();

InterfaceModelLocator.getInstance().addModel(

"ApplicationLevelModelName",mode

lLocator);

}

return ApplicationModelLocator(

InterfaceModelLocator.getInstance().getModel("Ap

plicationLevelModelName"));

}

}

Page 21: Flash Flex August 2011

08/2011 (26)20

FLEX DEVELOPMENT Modular Application Development Using Cairngorm Architecture

08/2011 (26) 21

Listing 5. Module Loader Impl

<xml version="1.0" encoding="utf-8"?>

<xmlns:mx="http://www.adobe.com/2006/mxml"

width="400"

height="300"

implements="..........ApplicationGateway"

xmlns:control=".......control.*"

xmlns:business="......business.*"

creationComplete="{initApp()}"

show="{loadModule()}"

>

BaseApplicationController id="baseApplicationCon

troller"/>

<mx:Script>

<!--[<span class="hiddenSpellError"

pre="">CDATA</span>[-->

import mx.utils.StringUtil;

import mx.core.Application;

import mx.collections.ArrayCollection;

import mx.modules.ModuleManager;

import mx.managers.PopUpManager;

import mx.events.CloseEvent;

import mx.modules.Module;

import mx.modules.IModuleInfo;

import mx.containers.TitleWindow;

import .............SampleGateway;

// SampleGateway is the

communication interface

import mx.events.ModuleEvent;

protected var _moduleInfo:IModuleInfo;

public var moduleTitleWindow:

ModuleTitleWindow;

private var sampleGateway:SampleGateway =

null;

private function initApp():void {

_moduleInfo = ModuleManager.getModule("Yo

urModule.swf");

_moduleInfo.addEventListener(ModuleEvent.R

EADY, onModuleReady);

_moduleInfo.addEventListener(ModuleEvent.U

NLOAD, onModuleUnload);

}

private function loadModule():void {

_moduleInfo.load();

}

private function onModuleReady (e:

ModuleEvent):void {

var moduleInfo:IModuleInfo =

e.currentTarget as ImoduleInfo;

var module:Module = (moduleInfo.fact

ory.create () as Module)

sampleGateway = module as

SampleGateway;

sampleGateway.setApplicationGateway(t

his);

//THE NEXT LINE IS A TYPICAL IMPLEMENTATION FOR

CREATING STATIC CUSTOM POPUPS

moduleTitleWindow = PopUpManager.crea

tePopUp(DisplayObject(Applicatio

n.application),

ModuleTitleWindow, true) as ModuleTitleWindow;

moduleTitleWindow.addChild(module);

PopUpManager.centerPopUp(moduleTitleW

indow);

var commandList:ArrayCollection =

SampleGateway.getCommands();

//THE NEXT LINE ADDS ALL MODULE COMMANDS TO THE

APPLICATION CONTROLLER

baseApplicationController.addCommands

(commandList);

}

public function unloadModule(event:Event):

void {

var cmdList:ArrayCollection;

sampleGateway.cleanup();

cmdList = sampleGateway.getCommands();

//THE NEXT LINE DELETES ALL MODULE COMMANDS FROM THE

APPLICATION CONTROLLER

baseApplicationController.removeCommand

s(cmdList);

baseApplicationController.removeAllChil

dren();

_moduleInfo.release();

PopUpManager.removePopUp(moduleTitleWin

dow);

}

public function onModuleUnload (e:

ModuleEvent) : void {

}

public function returnToTarget(target:*):

void{

unloadModule(target);

}

]]>

</mx:Script>

</mx:Canvas>

Page 22: Flash Flex August 2011

08/2011 (26)22

FLEX DEVELOPMENT

application-modules interaction. Since this interface is used by the application SWF to communicate with all module’s SWF that it needs to use, a singleton modelLocator in the interface is maintainable and can contain various modules and the application specific modelLocator. (I will soon be posting a blog on modular interaction using SWC gateway interfaces).

Interface level ModelLocator that should implement com.adobe.cairngorm.model.ModelLocator: Listing 3.

Application level ModelLocator that should use the interface level ModelLocator: Listing 4.

The module level ModelLocator should be coded on similar lines.

StylesCSS usage varies from project to project. All CSS related changes of the application and the module could be kept in a single .css file (If that does not bloat).

CommandThe Command class processes the event by running the Command class’ execute() method, which is an ICommand interface method. The event object may include additional data if required by the developer. The execute() method can update the central Model, as well as invoke a Service class which typically involves communication with a remote server. The IResponder interface, which is also implemented by the Command class, includes onResult and onFault methods to handle responses returned from the invoked remote service.

Commands imbibe business logic, thus should be unique.

Module LoaderMXML residing in the main application and used to load the child module. This is the module wrapper that is called from the main application and handles all the module loading/unloading etc related events.

ServicesAll remote objects of the application as well as the module should be declared here: Listing 6.

RemotingAll destinations pertaining to the application as well as the module level remote objects should be declared here: see Listing 7.

Post the above mentioned considerations, merging Cairngorm specific modules and applications should be a hassle free process......

To interact with the author regarding this article, kindly visit http://xebee.xebia.in/2010/10/11/flex-modular-application-development-using-cairngorm-architecture/.

KARAN NANGRU Consultant @ Xebia IT Architects (http://www.xebiaindia.com/), RIA and Cloud computing enthusiast.IIT Delhi Certi�ed Software Engineering Management Consultant CSM ®

Listing 6. Services.mxml

<RemoteObject id="applicationRemoteObject"

destination="applicationRemoteObjectJavaDelegate"

showBusyCursor="true"

result="event.token.resultHandler( event );"

fault="event.token.faultHandler( event );">

RemoteObject>

<mx:RemoteObject id="moduleRemoteObject"

destination="moduleRemoteObjectJavaDelegate"

showBusyCursor="true"

result="event.token.resultHandler( event );"

fault="event.token.faultHandler( event );">

</mx:RemoteObject>

[/sourcecode]

Listing 7. Remoting-con�g.xml

<destination id="applicationRemoteObjectJavaDelega

te">

<properties>

<source>.....ApplicationRemoteObjectJavaDeleg

ate</source>

</properties>

</destination>

<destination id="moduleRemoteObjectJavaDelegate">

<properties>

<source>.....ModuleRemoteObjectJavaDelegate</

source>

</properties>

</destination>

Page 24: Flash Flex August 2011

08/2011 (26)24

FLEX DEVELOPMENT

For the propose of the article, we will localize an application that you be developing in upcoming articles. For now, this app does nothing, all we

have is a very basic UI.I made it simple to demonstrate that as the application

involves, the localization process will continue quite easy and will need no change on our source code.

Localization the Standard Approach The standard maneuver is as follow:

• Create the properties files: used to manage the key-value pairs of content for each locale.

• Compile the properties files into a ResourceBundle.• Embed the ResourceBundle into the application.• Trigger a locale change.• Update your application with localized content.

This approach works very well, but soon you see that, as the application becomes more and more complex, we have to alter every view UI control to pull the localized content and apply it to every every property needed.

Using BabelFx will be injecting the localized content in a very straight forward and sim-ple manner.

IoC l10n

When developing an Application that targets a broad audience, a topic you’ll be dealing with is, localization. In this article we’ll see how to make this task much easier using the BabelFx Localization Framework.

What you will learn…• Work with resource bundles• Localize applications• Create LocalizationMap

What you should know…• Intermediate knowledge of Actionscript• Create basic components• Basic Undertanding of design patterns

Localizing Your Apps with BabelFX

Figure 1. Chat Application UI Figure 2. Components ids

Page 25: Flash Flex August 2011

IoC l10n

08/2011 (26) 25

Injecting the ContentAfter we created the app UI and downloaded the library from repository, extract it and copy the Framework_BabelFx.swc from the bin directory to the libs of our app.

Now let’s create the properties files that will contain our localized content. For this app, we will localizing it to English (en_US),Portuguese (pt_BR) and Japanese (ja_JP). For the japanese location i will be inserting some dummy text in the property file.

The propertie file contains a key that match each component id of our app and the localized value for it (Listing 1 and 2).

After that save each file in src/l10n/locale/en_US/

main.properties and src/l10n/locale/pt_BR/main.properties and src/l10n/locale/ja_JP/main.properties.

Note that the structures for filename, folders and key/value pairs are required by Flex in order to build and compile all property files in a single resource bundle.

BabelFx FrameworkIn short, the BabelFx uses Inversion of Control, to provide a powerful and easy framework for easy run-time injection of localized resources (strings, bitmaps, skins, etc.) into Flex GUI views and non-DisplayObject models and business classes.

We can use it with other frameworks like Swiz, Mate and so on, and it proves to be the ideal solution because it speeds up the localization process.

First and foremost let’s obtain the BabeFx framework from its repository (located at https://github.com/BabelFx/AS3-Flex-Library), after that create an AIR appli-cation like the one shown in Figure 1.

Assign the following ids to each component as shown in Figure 2. There’s no need to provide text to each controls, because it will be injected by BabelFx at runtime. Figure 3 shows the Injection Process in detail.

Figure 3. Injection Process in detail

Page 26: Flash Flex August 2011

08/2011 (26)26

FLEX DEVELOPMENT IoC l10n

08/2011 (26) 27

Resource Bundle CompilationAfter creating the .properties files for each locale, we have these files into resource bundles. Here we can:

* Use the Flex Builder to embed it into the deployed application

* Use ANT when loading bundles dynamically at run-time

For our simple demo application we’ll be using the first approach. To accomplish this task, access the project

properties using Project>Properties>Flex Compiler and enter the following line in the Additional compiler arguments

-locale=en_US,pt_BR -allow-source-path-overlap=true -

source-path+=l10n/locale/{locale}

This will build only bundles whose files are located at /l10n/locale and also include the localized resources from the MX framework witch can be fount at <FLEX _ HOME>

/sdks/<your _ sdk _ version>/frameworks/locale. In these example i am using the two locales available in my Flex installation – en _ US and ja _ JP. I also included the pt _ BR

Listing 1. Property �le content for en_US locale

lblUser = User:

lblPassword = Password:

btnLogin = Login

lblLanguage = Language:

chkRememberMe = Remember Me

Listing 2. Property �le content for pt_BR locale

lblUser = Usuário:

lblPassword = Senha:

btnLogin = Login

lblLanguage = Idioma

chkRememberMe = Lembrar Senha

Figure 4. Additional compiler arguments

Figure 5. Application structure

Page 27: Flash Flex August 2011

08/2011 (26)26

FLEX DEVELOPMENT IoC l10n

08/2011 (26) 27

Figure 7. LocalizationMap ResourceInjectorFigure 6. LocalizationMap folder

Listing 3. Custom LocalizationMap

<?xml version="1.0" encoding="utf-8"?>

<LocaleMap xmlns="http://l10n.babelfx.org/" xmlns:mx="http://www.adobe.com/2006/mxml" >

<mx:Metadata>

[ResourceBundle("main")]

/*

Uncoment to include the menu.properties file

[ResourceBundle("menu")]

*/

</mx:Metadata>

<ResourceInjector target="{Chat}" bundleName="main">

<ResourceSetter key="lblUser" property="lblUser.text" />

<ResourceSetter key="lblPassword" property="lblPassword.text" />

<ResourceSetter key="btnLogin" property="btnLogin.label" />

<ResourceSetter key="chkRememberMe" property="chkRememberMe.label" />

<ResourceSetter key="lblLanguage" property="lblLanguage.text" />

</ResourceInjector>

<!--

Resource Injector and mapping for the menu bundle

<ResourceInjector target="{Chat}" bundleName="menu">

<ResourceSetter key="lblMenu" property="lblMenu.text" />

</ResourceInjector>

-->

</LocaleMap>

Page 28: Flash Flex August 2011

08/2011 (26)28

FLEX DEVELOPMENT IoC l10n

08/2011 (26) 29

Listing 4a. Chat.mxml

<?xml version="1.0" encoding="utf-8"?>

<mx:WindowedApplication

xmlns:mx="http://www.adobe.com/2006/mxml"

xmlns:l10n="l10n.map.*"

layout="absolute" width="300" height="450"

creationComplete="init()">

<l10n:LocalizationMap />

<mx:Script>

<![CDATA[

import mx.events.ListEvent;

import mx.resources.*;

public function init():void

{

this.cmbLocale.addEventListener(ListEvent.CHANGE, this.changeLocate);

}

public function changeLocate(event:ListEvent):void

{

switch(this.cmbLocale.selectedLabel)

{

case 'ja_JP':

ResourceManager.getInstance().localeChain = ['ja_JP','pt_BR','en_US'];

break;

case 'en_US':

ResourceManager.getInstance().localeChain = ['en_US','pt_BR','ja_JP'];

break;

case 'pt_BR':

ResourceManager.getInstance().localeChain = ['pt_BR','en_US','ja_JP'];

default:

ResourceManager.getInstance().localeChain = ['pt_BR','ja_JP','en_US'];

}

}

]]>

</mx:Script>

<mx:Label x="90.5" y="180" id="lblPassword"/>

<mx:Label x="90.5" y="131" id="lblUser"/>

<mx:TextInput x="90.5" y="154" id="txtUser"/>

<mx:TextInput x="90.5" y="200" id="txtPassword"/>

<mx:CheckBox x="90" y="276" id="chkRememberMe"/>

<mx:Button x="90" y="230" width="160.5" height="33" id="btnLogin"/>

Page 29: Flash Flex August 2011

08/2011 (26)28

FLEX DEVELOPMENT IoC l10n

08/2011 (26) 29

MARC PIRESMarc Pires is a RIA Developer at RGSistemas, and is heading his Iphone de-velopment Office Taveo Mobile.Contact information: @MarcPires (Twitter)[email protected]: [email protected]

locale in the package, because my Flex Builder did not have this (Figure 5).

Creating LocalizationMapNow, we need to create a custom localization map to specify the targets for injection of the localized resources. So make the following:

• Create a new folder called map inside the src/l10n folder

• Create a new MXML component based on Canvas and name it LocalizationMap

TIP: The name of our localization map could be anything, but i think it’s better to follow a convention here because it keeps things simple. So always use LocalizationName for your localization map and keep it at a the map folder (Figure 6).

• After creating the localization map, open it and replace the code with code pre-sented in Listing 3.

Let’s dig into our localization map.

• Our custom localization map inherits from LocaleMap class provided by the BabelFX framework

• After that i embed the resource bundle unsing the metadata tag. As this application has only the main property file for each locale i’m using only one ResourceBundle tag here. If i had other properfies file fot this app i’d specify them as shown in Figure 6: (In-cluding other resource bundles).

The ResourceBunde tag informs Flex Builder to link the compile bundles to our application build.

• After that i specify a ResourceInjector that watch for any instantiation of Display Objects. It responds to addedToStage notifications from the LocaleMap for instances of MovieClip/Sprite objects and its subclasses and with creationComplete for UIComponent instances.

• Then I specify that the content store in main bundle with a given key be assigned to all instances of Chat.lblUser with the ResourceSetter tag.

Putting it All TogetherNow that we have all the necessaries part setup, it’s time to use our localization map to localize the app. For this let’s open the Chat.mxml file and do some work.

As a rule of thumb I never put any <mx:Script> inside mxml files my apps, but as it’s a very simple application that will be upgraded in future articles, I’ll open an exception.

First let’s define a new namespace called l10n that will be pointing to our Localization-Map. See Listing 4.

After that I instantiate the LocationMap with <l10n:LocalizationMap />. Then I define the init method to do any further configuration I possibly need. In this example I set an event listener for the comboBox to change the locale from within the application UI.

In the changeLocale method is where I define the locales that will used as we select another value. It’s very strait forward, just call ResourceManag-er.getInstance().localeChain = <locale values> and it’s done, our chat UI will be translated to the corresponding locale. Compile the application and see our Ioc Localization in action.

Just to make things even interesting, try this: Completely remove the init and change-Locale methods and creationComplete from Chat.mxml, compile the app again and see that the application will be localized to the default locale of our machine. Pretty amazing hugh?

Well that’s all for this article. Despite the application shown is a very very simple, note that as this app will continue to involve next article, the localization process will continue a very simple approach, for then on, it’s just a matter of creating new properties files, set our resource injectors and you’re done.

This application example will be available at https://github.com/marcpiresrj/Chat.

Any question about this article drop a line. See you next month.

Listing 4b. Chat.mxml

<mx:ComboBox x="90" y="302" dataProvider="[Select,en_US,pt_BR,ja_JP]" id="cmbLocale"></mx:ComboBox>

<mx:Label x="21" y="307" id="lblLanguage"/>

<mx:Label x="122" y="69" id="lblMenu"/>

</mx:WindowedApplication>

Page 30: Flash Flex August 2011

08/2011 (26)30

ACTIONSCRIPT IN ACTION A Flex FAQ Browser

08/2011 (26) 31

Last month I showed how to program an application that could both create and load XML data files. This made it easy to construct individual data

records by entering text into the fields on a form and then saving a database in XML format on disk. I used the same application to load the XML data from the file.

However, that application made no attempt to display the XML in a nicely formatted way. I’ll deal with that problem now.

This month I will assume that you want to load data from one or more data files. Each data file contains a number of questions and answers. Each question and

A Flex FAQ Browser

This month Huw Collingbourne show how to create an online FAQ Browser or Quiz by loading XML data files.

What you will learn…• How to load and display XML data• How to populate a DataGrid with data• How to parse text from named XML items

What you should know…• How to create an XML �le• The basics of Event handling• How to create a Flex user interface

Listing 1. The XML Data File

<QALIST>

<QA>

<QUESTION>What is the capital of France?</QUESTION>

<ANSWER>Paris</ANSWER>

</QA>

<QA>

<QUESTION>How many eggs make a dozen?</QUESTION>

<ANSWER>Twelve</ANSWER>

</QA>

<QA>

<QUESTION>Who killed Laura Palmer?</QUESTION>

<ANSWER>Beats me!</ANSWER>

</QA>

<QA>

<QUESTION>What is the sum of 2 + 2?</QUESTION>

<ANSWER>4</ANSWER>

</QA>

</QALIST>

Page 31: Flash Flex August 2011

08/2011 (26)30

ACTIONSCRIPT IN ACTION A Flex FAQ Browser

08/2011 (26) 31

event is triggered after an item is selected from the ComboBox. This is the event-handler:

private function closeHandler( event : Event ) : void {

datafileurl = ComboBox( event.target

).selectedItem.datafile;

loadXML( );

}

Here, datafileurl is a variable that stores the currently selected file name. It obtains this file name by indexing into the filenames ArrayCollection which contains a list of paired items – each of which is an associative array containing a label, which is displayed in the ComboBox, and a file name which is the name of the XML data file to be loaded when a combo box item is selected. This ArrayCollection is assigned as the dataProvider property of the loadDataCombo combo box:

each answer is written inside a pair of <QUESTION> and <ANSWER> tags and these are enclosed between a pair of <QA> tags like this:

<QA>

<QUESTION>What is the capital of France?</QUESTION>

<ANSWER>Paris</ANSWER>

</QA>

The entire database – that is, a sequence of <QA> items – is enclosed between a pair of <QALIST> tags. See Listing 1 for an example of a complete database of questions and answers. The names of the tags (QALIST, QA, QUESTION and ANSWER) are arbitrary. You could, if you wish, choose completely different names. However, when I load and use the data, my program will refer to the tags by name so if you use different tag-names in your data file you will also need to use those tag-names in your ActionScript.

The User InterfaceThe user interface I’ve decided upon uses a DataGrid to display questions and answers in columns (Figure 1), a TextArea to display the text of long answers and a ComboBox to allow the user to chose different data files. Here, I’ve used an MX (Halo) DataGrid rather than a Spark one for the simple reason that it is not only backwards compatible with Flex 3 but its MXML code is shorter, which is more convenient for the purposes of this tutorial. In your own applications, of course, you could use Spark DataGrids or other types of component for displaying data.

The ActionScript code of my application is stored in the file LoadXML.designer.as, while the user interface is defined in the MXML file, load_to_xml.mxml. In the MXMl file you’ll see that the ComboBox has been assigned an event-handler for the close event. This

Figure 2. The Amethyst Debugger shows that my XMLList contains a series of QA items containing paired questions and answers that were parsed from the loaded XML data �le

Figure 1. I’m using the visual designer of the Amethyst IDE to create the user interface. I’ve dropped on a mx.DataGrid and I’m using the column editor to adjust the column properties

Page 32: Flash Flex August 2011

08/2011 (26)32

ACTIONSCRIPT IN ACTION

filenames = new ArrayCollection(

[ {label:”Quiz”, datafile:”quiz.xml”},

{label:”General Knowledge Test”, datafile:”test.xml”},

{label:”Product FAQ”, datafile:”faq.xml” } ] );

My LoadXML() method uses a SaveLoad object to handle the loading of the XML data. SaveLoad is a class which I wrote specifically to deal with file loading. See last month’s column for an explanation. When loading is complete, the SaveLoad object dispatches an Event.COMPLETE event. My loadXML() method designates an event-listener, xmlLoaded(), to handle that event.

private function loadXML( ) : void {

sl.addEventListener( Event.COMPLETE, xmlLoaded );

sl.loadXMLData( datafileurl );

}

Displaying An XMLListOnce the data has been loaded, the XML is converted to an XMLList object. The XMLList class contains methods for working with XML elements. An XMLList object can

also be used to initialize an XMLListCollection object which lets you manipulate XML items as a collection. In the present case, I need to have an XMLListCollection in order to assign it to the dataProvider property of my DataGrid, quizgrid. In fact, it is possible to assign an XMLList as a dataProvider in which case, the DataGrid will convert it to an XMLListCollection:

private function xmlLoaded( e : Event ) : void {

xmlList = new XMLList( sl.xmlData ).QA;

xmlListColl = new XMLListCollection( xmlList );

quizgrid.dataProvider = xmlListColl;

}

Notice that I have created an XMLList by specifying the QA tag by name. This ensures that the list is created from the <QA> items (Figure 2). So my xmlList variable will be assigned a list of four items like this:

<QA><QUESTION>What is the capital of France?

</QUESTION><ANSWER>Paris</ANSWER></QA>

<QA><QUESTION>How many eggs make a dozen?

Figure 3. To show or hide the answers in the second column of the DataGrid I just click a button. This calls some ActionScript to toggle the visibility of the column

Listing 2. The DataGrid de�nition

<mx:DataGrid height="258" id="quizgrid" width="783" x="17" y="10" itemClick="quizgrid_itemClick(event)">

<mx:columns>

<mx:DataGridColumn dataField="QUESTION" headerText="question" id="question_col"

width="383"/>

<mx:DataGridColumn dataField="ANSWER" headerText="answer" id="answer_col"

visible="false" width="398"/>

</mx:columns>

</mx:DataGrid>

Page 33: Flash Flex August 2011

A Flex FAQ Browser

08/2011 (26) 33

</QUESTION><ANSWER>Twelve</ANSWER></QA>

<QA><QUESTION>Who killed Laura Palmer?

</QUESTION><ANSWER>Beats me!</ANSWER></QA>

<QA><QUESTION>What is the sum of 2 + 2?

</QUESTION><ANSWER>4</ANSWER></QA>

If I had omitted the name of the tag, that is if I had written xmlList = new XMLList(sl.xmlData), my xmlList variable would have been assigned a list containing a single item delimited by the <QALIST> tags. Refer again to Listing 1 to see the structure of my XML data.

Once it has been assigned the XML List Collection, the DataGrid is automatically populated with the data. This is explained by the fact that the two DataGridColumns of the DataGrid have been given dataFields, each of which has a name matching the XML data item to be displayed in that column – that is, QUESTION and ANSWER. See Listing 2.

By default the DataGrid displays only the questions but not the answers. That’s because I’ve set the visible property of the Answer column to false. I’ve supplied two alternative ways of displaying the answers. The simplest of these is provided by the button which simply calls a method to toggle the visibility of the Answers column of the DataGrid (Figure 3):

public function showAnswers( ) : void {

answer_col.visible = !answer_col.visible;

}

But let’s suppose that the text of the answer is too long to fit into that column. How then can I display it? Just as I was able to access a list of <QA> items earlier by using its name, so too I can access the text of an <ANSWER> item by name. I’ve decided to do this in response to a mouse click on a specific row in the DataGrid. This parses out the text from the ANSWER item of the XML and displays it in the TextArea, ta:

private function quizgrid_itemClick (event:

mx.events.ListEvent):void {

ta.text = quizgrid.selectedItem.ANSWER;

}

In next month’s article I’ll take a look at some of the classes and methods that can be used to do more complex types of XML processing.

HUW COLLINGBOURNEHuw Collingbourne is Director of Technology at SapphireSteel Software. Over more than 20 years, he has programmed in languages ranging from Ruby to C# and has been a technical columnist for computer magazines such as PC Pro and PC Plus. He is the software lead of the Amethyst Designer, the Flex user interface design environment of the Amethyst IDE for Visual Studio. SapphireSteel Software: http://www.sapphiresteel.com/

Get The Source CodeThe archive containing all the source code for this game is available for download from the SapphireSteel Software site at: http://www.sapphiresteel.com/tutorials/amethyst-tutorials/actionscript-programming/article/faq-browser

Figure 4. When the user selects a row in the DataGrid, my code locates the matching XML item, parses out the text between the <ANSWER> tags and displays it in a TextArea

Page 34: Flash Flex August 2011

08/2010 (26)34

PROGRAMING

08/2010 (26)

Within your application, you will undoubtedly need to store a number such as 3, 4.86, or even a boolean YES or NO value within a

NSArray- or NSDictionary-based data structure. You may think that we could accomplish this task via a code snippet such as the following:

[myArray addObject:5];

However, when you attempt to compile this statement, the compiler will warn you that passing argument 1 of addObject: makes pointer from integer without a cast, hinting that something is not quite right. This example is a classic demonstration of the procedural C-based side of Objective-C running up against the newer object-oriented additions to the language.

Classes such as NSArray and NSDictionary expect their keys and values to be objects of some kind. The integer number 5 is not an object; it is a simple primitive data type. As such, it is not possible to directly store an integer within an array.

Many languages such as Java 5 or C# take care of this problem automatically through a concept called auto-boxing. Behind the scenes, the primitive (non-

object-oriented) value is wrapped up inside of a container object (a box) and this container is passed around instead of the raw value. Likewise, when you attempt to access the array and extract the value, the compiler detects a boxed value and automatically extracts the primitive payload for you. This process can be conceptualized in much the same way as a gift being placed inside a FedEx box and removed from it once it reaches its destination. FedEx can only deal with boxes of certain sizes and not your oddly shaped teapot for Aunt Betty, but that doesn’t stop you from shipping it through FedEx by temporarily placing it inside a box that meets their requirements.

Unfortunately, Objective-C does not provide for the automatic boxing and un-boxing of primitive data types. This means if we want to store an integer or other primitive value within an array or dictionary we will need to perform the boxing and un-boxing steps ourselves. This is the purpose of the NSNumber class.

The NSNumber ClassNSNumber is an Objective-C class that can be used to wrap up a value of a primitive data type such as int, char, or BOOL into an object and then allows that value

Objective-C Fundamentals

Objective-C FundamentalsBy Christopher K. Fairbairn, Johannes Fahrenkrug, and Collin RuffenachWhile NSNumber provides a convenient and clean interface for boxing and unboxing numerical based primitive types, NSValue allows you to box and unbox any C-style value at the expense of having a slightly more complex interface to program against. In this article from Objective-C Fundamentals, the authors discuss how the NSNumber and NSValue take care of the problem that Objective-C can’t fix automatically. They also

explain how a similar technique allows you to store the equivalent of a nil value.

You may also be interested in…

Excerpted from

For Source Code, Sample Chapters, the Author Forum and other resources, go tohttp://www.manning.com/fairbairn/

Boxing

Page 35: Flash Flex August 2011

08/2010 (26)34

PROGRAMING

08/2010 (26)

to be extracted at a later stage. It is most useful for allowing us to place values of primitive data types into data-structures such as NSArray or NSDictionary, which can only store objects.

The process of manually boxing a primitive value into an NSNumber instance is fairly straightforward; you simply call one of NSNumber’s factory methods such as numberWithInt:

NSNumber * myNumber = [NSNumber numberWithInt:5];

There are similar factory messages, called numberWithFloat:, numberWithBool:, and so on, that allow the boxing of other common primitive data types.

Now that we have boxed the integer value inside an NSNumber (which is an object), we can finally store this value within our array as we had originally intended.

[myArray addObject:myNumber];

Boxing the integer inside an NSNumber also means that, when we go to fetch the value out of the array, we need to perform the reverse operation to extract the primitive value from the NSNumber instance. We can do this with a code snippet similar to the following, which uses NSNumber’s intValue message:

NSNumber * myNumber = [myArray objectAtIndex:0];

int i = [myNumber intValue];

The NSNumber class has various other methods that conform to the naming convention xxxValue, where xxx is replaced with the name of a primitive data type. It is not an error to box a value via numberWithInt: and then retrieve it via a method such as floatValue. Although we stored an integer and fetched a float, this is acceptable. In this scenario, the NSNumber class will perform a typecast operation to convert the value into our desired data type.

A little bit of fancy footwork was required but, in the end, boxing and unboxing primitive values so we can use them as if they were objects wasn’t too bad. What happens, however, if we want to store one or more RentalProperty structures within a NSArray? These structures are not objects either, but I doubt the NSNumber class has a numberWithRentalPropertyDetail method available for us to box them. The answer to this conundrum is another closely related class called NSValue.

The NSValue ClassNSNumber is a special subclass of NSValue. While NSNumber provides a convenient and clean interface for boxing and unboxing numerically-based primitive types, NSValue allows you to box and unbox any C-style value at the

Page 36: Flash Flex August 2011

08/2010 (26)36

PROGRAMING

expense of having a slightly more complex interface to program against.

To box the value of an arbitrary C structure or union, we can take advantage of NSValue’s valueWithBytes:

objCType: message. For example, the following code sample boxes a RentalProperty structure:

RentalProperty myRentalProperty =

{270.0f, @”13 Adamson Crescent”, TownHouse};

NSValue * value = [NSValue valueWithBytes:

&myRentalProperty

objCType:@encode(RentalProperty)];

This code snippet creates a copy of the rental property structure and places it inside the NSValue

object created by the call to valueWithBytes:objCType:. The valueWithBytes argument is the address of the value we want to store within the NSValue instance, while objCType and the strange @encode statement allow us to tell NSValue what kind of data we are wanting it to store.

The process to unbox an NSValue is equally different but still relatively straightforward. Rather than returning the unboxed value directly, the getValue message expects us to pass in a pointer to a variable it should populate with the value it contains, as demonstrated next:

RentalProperty myRentalProperty;

[value getValue:&myRentalProperty];

On return, getValue: will have populated the myRentalProperty variable with the value we previously stored. Right now, you might be asking yourself, if NSNumber and NSValue allow us to get around the restriction of only being able to store objects within an array or dictionary, will a similar technique allow us to store the equivalent of a nil value? The answer is yes.

nil vs. NULL vs. NSNullnil could not be stored within an array or dictionary and nil is used to indicate the absence of a value or entry. But what exactly is nil?

With a standard C style pointer, the special value NULL indicates the absence of a value. nil represents the very same concept, except applied to a variable that is designed to point to an Objective-C object.

Due to nil’s representing the absence of a value, it cannot be stored within an array or a dictionary. However, if we really want to store an empty or nil value, we can use a special class called NSNull. You can conceptualize NSNull as being another kind of boxing, similar to NSNumber or NSValue but this time specialized for storing nil.

To store a nil value within an array or dictionary, we can use the null factory method located on the NSNull class, as demonstrated below:

NSNull myValue = [NSNull null];

[myArray addObject:myValue];

An instance of the NSNull class is an object, so it is able to be stored within an NSArray or NSDictionary instance or used anywhere else an object is expected. Because an NSNull instance represents the absence of a value, the class doesn’t provide any way in which to extract a value, so when it comes time to pull our NSNull value out of an array, we can simply compare it against itself, as demonstrated below.

id value = [myArray objectAtIndex:5];

if (value == [NSNull null]) {

NSLog(@”The 6th element within the array was empty”);

}

else {

NSLog(“@The 6th element within the array had the

value %@”, value);

}

The statement [NSNull null] does not create a new object each time it is called. Instead, [NSNull null]

always returns the memory location of a sole instance of the NSNull class. This means that two variables that are storing a pointer to an NSNull value will have an identical address and, hence, the == operator will consider them the same. This is an example of the so-called singleton design pattern.

SummaryObject-oriented programming as implemented by Objective-C has many advantages over procedurally-based languages such as C. The ability to combine data with logic means that we can encapsulate common functionality and avoid developing the same algorithms for enumeration and searching within each application we develop. This enables you to concentrate on the aspects that differentiate your product and avoid common types of bugs. Nothing comes for free, however, and we have seen a number of limitations where the procedural world meets the object-oriented, such as the challenges of storing values of primitive data types such as int within an object. But there is a solution, and we showed you how you can fix that problem.

Page 38: Flash Flex August 2011

08/2010 (26)38

PROGRAMING Objective-C Fundamentals

08/2010 (26) 39

Apple provides a class called NSXMLParser to iPhone developers. Developers use this class when parsing XML. Several open source

alternatives to NSXMLParser are available and used by many developers, but we are going to look at the delegate methods of the standard Cocoa XML Parser.

There is no <NSXMLParser> protocol; you will receive no warning if you do not declare this in the header of the application you are creating. NSXMLParser is a fringe design class that follows the principles of protocol design but doesn’t explicitly define a protocol. An NSXMLParser object has a parameter called delegate, which needs to be defined. Whatever object is defined as the delegate has the option of implementing a collection of 20 different delegate methods. NSXMLParser provides delegate methods that handle every point of parsing for both XML- and DTD-based documents.

XML is a type of file that can hold data in a very structured manner. As a quick introduction, XML uses the syntax of HTML to create unique data structures. An example of an XML element that describes a person is shown in Listing 1.

XML is a very common means of getting data from online sources such as Twitter. XML is also used to

facilitate the data required to run your specific iPhone project. iPhone development relies heavily on PLISTS. These files are really just XML.

DTD stands for Document Type Definition. This is a document that would describe the structure of the XML

Objective-C Fundamentals

Objective-C FundamentalsBy Christopher K. Fairbairn, Johannes Fahrenkrug, and Collin Ruffenach

Apple provides a class called NSXMLParser to iPhone developers. Developers use this class when parsing XML. This article from Objective-C Fundamentals shows that NSXMLParser provides delegate methods that handle every point of parsing for both XML- and DTD-based documents.

You may also be interested in…

Excerpted from

For Source Code, Sample Chapters, the Author Forum and other resources, go tohttp://www.manning.com/fairbairn/

NSXMLParser

Listing 1. An author in XML

<Author>

<name>Collin Ruffenach</name>

<age>23</age>

<gender>male</gender>

<Books>

<Book>

<title>Objective C for the

iPhone</title>

<year>2010</year>

<level>intermediate</level>

</Book>

</Books>

</Author>

Page 39: Flash Flex August 2011

08/2010 (26)38

PROGRAMING Objective-C Fundamentals

08/2010 (26) 39

that you are going to work with. The document type definition for the XML in version 7.4.3.1 would be:

<!ELEMENT Author (name, age, gender, books_list(book*))>

<!ELEMENT name (#PCDATA)>

<!ELEMENT age (#PCDATA)>

<!ELEMENT gender (#PCDATA)>

<!ELEMENT Book (title, year, level)>

<!ELEMENT title (#PCDATA)>

<!ELEMENT year (#PCDATA)>

<!ELEMENT level (#PCDATA)>

For some applications, examining the structure of the XML they are receiving will change the manner in which the application parses. In this case, we say that the XML will contain an element called Author. An Author will be defined by a name, age, and gender, which will be simple strings. An author will also have a list of Book elements. A Book is defined by a title year and level that are all simple strings. This ensures that the NSXMLParser knows what to do.

The majority of the time when you parse XML, you will be aware of its structure when writing your parser class. For these instances, you will not need to investigate the XML feeds DTD. An example of this would be the Twitter XML feed for a timeline. We will assume we know the XML structure for our XML and only implement the parsing functions of the NSXMLParser delegate to parse the Author XML we have already looked at.

Parsing an author with NSXMLParser delegateThe first step when implementing NSXMLParser is to create a class that will contain the parser object and implement its delegate methods. Let’s create a new view-based project called Parser_Project and create a new NSObject subclass called Parser. The only instance variables we are going to declare for the Parser class is an NSXMLParser and an NSMutableString to help. Make Parser.h look like the following.

#import <Foundation/ Foundation.h>

@interface Parser : NSObject <NSXMLParserDelegate> {

NSXMLParser *parser;

NSMutableString *element;

}

@end

We are going to need to have an XML file to parse. You can take the XML in Listing 2 and place it in a regular text file. Save the file as Sample.xml and add it into the project. This will give us a local XML file that we can reference to parse.

Listing 2. Parser.m Initializer

-init {

if(self == [super init]) {

parser = [[NSXMLParser alloc]

initWithContentsOfURL:[NSURL

fileURLWithPath:[[NSBundle

mainBundle] pathForResource:

@"Sample" ofType: @"xml"]]];

[parser setDelegate:self];

[parser parse];

}

return self;

}

Listing 3. NSXMLParser Methods

- (void)parser:(NSXMLParser *)parser

didStartElement:(NSString

*)elementName namespaceURI:

(NSString *)namespaceURI

qualifiedName:(NSString

*)qualifiedName attributes:

(NSDictionary *)attributeDict {

NSLog(@"Started Element %@", elementName);

element = [NSMutableString string];

}

§ - (void)parser:(NSXMLParser *)parser

didEndElement:(NSString

*)elementName namespaceURI:

(NSString *)namespaceURI

qualifiedName:(NSString *)qName

Listing 4. NSXMLParser Methods

- (void)parser:(NSXMLParser *)parser didEndElement:

(NSString *)elementName

namespaceURI:(NSString

*)namespaceURI qualifiedName:

(NSString *)qName {

NSLog(@"Found an element named: %@ with a

value of: %@", elementName,

element);

}

§ - (void)parser:(NSXMLParser *)parser

foundCharacters:(NSString

*)string

Page 40: Flash Flex August 2011

08/2010 (26)40

PROGRAMING

Now we need to fill in Parser.m. Parser.m will contain an initialize and the implementation of the three most common NSXMLParser Delegate methods. Let’s start with the initializer method and add the code shown in listing 2 into XMLParser.m.

Here we are going to initialize our NSXMLParser parser using a file URL pointing to our Sample.xml file that we imported into our project earlier. NSURL is a large class with all sorts of initializers. In this case, we are telling it that we will be providing a path to a file URL, or a local resource. With that done, we tell the NSXMLParser that this class will be the delegate of the parser and, finally, we tell the NSXMLParser we are ready to parse by sending the parse exam.

Once the parse method is called on the NSXMLParser, the parser will begin to call its delegate methods. The parser reads down an XML file much like Latin/English characters are read: left to right, top to bottom. While there are many delegate methods, we will be focusing on three of them.

- (void)parser:(NSXMLParser *)parser didStartElement:

(NSString *)elementName namespaceURI:(NSString

*)namespaceURI qualifiedName:

(NSString *)qualifiedName attributes:(NSDictionary

*)attributeDict

While this method has a lot of parameters passed into it, it is actually quite simple for our purposes. This method is called when an element is seen starting. This means that any element (between <>) that does not have a /. In this method we will first print the element we see starting and we will clear our NSMutableString element. You will see upon implementing the new methods that we use the element variable as a string that we add to as delegate methods are called. The element variable is meant to hold the value of only one XML element. So, when a new element is started, we make sure to clear it out. Fill out the following, shown in listing 3, for this delegate method.

This method is called when an element is seen ending. This means when an element has a / this method will be

Listing 5. NSXMLParser Methods

- (void)parser:(NSXMLParser *)parser

foundCharacters:(NSString

*)string

element = [[NSMutableString alloc] init];

[element appendString:string];

}

Listing 6. Initializing the Parser

- (BOOL)application:(UIApplication *)application

didFinishLaunchingWith Options:

(NSDictionary *)launchOptions {

// Override point for customization after app

launch

[window addSubview:viewController.view];

[window makeKeyAndVisible];

Parser *parser = [[Parser alloc] init];

return YES;

}

Listing 7. Parser Output

Parser_Project[57815:207] Started Element Author

Parser_Project[57815:207] Started Element name

Parser_Project[57815:207] Found an element named:

name with a value of: Collin

Ruffenach

Parser_Project[57815:207] Started Element age

Parser_Project[57815:207] Found an element named:

age with a value of: 23

Parser_Project[57815:207] Started Element gender

Parser_Project[57815:207] Found an element named:

gender with a value of: male

Parser_Project[57815:207] Started Element Books

Parser_Project[57815:207] Started Element Book

Parser_Project[57815:207] Started Element title

Parser_Project[57815:207] Found an element named:

title with a value of: Objective

C for the iPhone

Parser_Project[57815:207] Started Element year

Parser_Project[57815:207] Found an element named:

year with a value of: 2010

Parser_Project[57815:207] Started Element level

Parser_Project[57815:207] Found an element

named: level with a value of:

intermediate

Parser_Project[57815:207] Found an element

named: Book with a value of:

intermediate

Parser_Project[57815:207] Found an element

named: Books with a value of:

intermediate

Parser_Project[57815:207] Found an element named:

Author with a value of:

intermediate

Page 41: Flash Flex August 2011

Objective-C Fundamentals

called. When this method is called out NSMutableString element variable will be complete. We will simply print out the value we have seen (see Listing 4).

This method is called when the parser sees anything between an element’s beginning and ending. We will use this entry point as a way to collect all the characters that are between an element; this is done by calling the appendString method on our NSMutableString. By doing this every time, this method is called; by the time the didEndElement method is called, the NSMutablrString will be complete. In this method, we first make sure that we have initialized our NSMutableString element and then we append the string we are provided, shown in Listing 5.

Now all that is left to do is create an instance of our Parser and see it go. Go to Parser_ProjectAppDelegate.m and add the code shown in Listing 6 into the already existing method.

If you run the application and bring up the terminal window (shift + apple + r), the output shown in Listing 7 should be generated.

You can see that using the NSXMLParser delegate methods we successfully parsed all of the information in our XML file. From here, we could create Objective-C objects to represent the XML and use it throughout

our application. XML processing is a vital part of most applications that get their content from some kind of web source; Twitter Clients, News Clients, or YouTube.

SummaryProtocols are all over the place when developing for the iPhone. They are one of the foundation design decisions for the majority of the classes the Apple provides. With attentive coding, the usage of these protocols can make your application efficient and error proof. Through a proper understanding and implementation of the protocol design method, you can ensure a well-designed application.

NSXMLParser is a fringe design class that follows the principles of protocol design but doesn’t explicitly define a protocol. An NSXMLParser object has a parameter called delegate, which needs to be defined. Whatever object is defined as the delegate has the option of implementing a collection of 20 different delegate methods. NSXMLParser provides delegate methods that handle every point of parsing for both XML- and DTD-based documents.

a d v e r t i s e m e n t

Page 42: Flash Flex August 2011

08/2011 (26)42

DESIGN

The problem? Maintaining the integrity of the original design could literally take hours for a developer. So how can a team streamline the

workflow to not only maintain the artistic integrity of a design, but also reduce headaches and hiccups during development? This article takes a project through this process from design, to interactive prototype, to full-

fledged application, all while keeping the design intact and the development hours short.

Design to PrototypeFor the designer, the first step would be to create designs using Adobe Photoshop or Adobe Illustrator, which would then be shown to the client for approval.

How to

One of the biggest issues in an application UI development process is the workflow between the designer and the developer. The designer is rightly concerned about the integrity of the design, while the developer is also concerned about the functionality of the final application.

What you will learn…• That the work�ow between designer and developer doesn’t

have to be �lled with compromises and/or long hours. • With the right tools, it can truly be a seamless process, with

projects that are completed quicker, with better results, and that leave everyone involved in the process much happier and more productive.

• This article takes a project through this process from design, to interactive prototype, to full-�edged application, all while keeping the design intact and the development hours short.

What you should know…• The application UI development process, speci�cally the

work�ow between the designer and the developer.• Adobe technologies, namely Flash Builder and Flash Catalyst.• Design/Developer work�ow issues – the designer is rightly

concerned about the integrity of the design, whereas the developer is also concerned about the functionality of the �nal application.

Promote a More Seamless Designer/Developer Workflow

Figure 1. Layers named and organized appropriately Figure 2. Controlling layer visibility in Flash Catalyst

Page 43: Flash Flex August 2011

How to Promote a More Seamless Designer/Developer Workflow

08/2011 (26) 43

Creating an Interactive PrototypeImporting

• Starting in Illustrator CS5, create each state of the application on its own layer. Make sure all the layers are named appropriately (Figure 1).

• Open the Illustrator file in Flash Catalyst CS5. Notice how Flash Catalyst keeps the design and layers intact.

Creating PagesFlash Catalyst has a Pages/States panel that allows users to define different pages of the project. By default the first page is named Page 1. Whatever content on layers that have their visibility turned on will be seen when the user is on Page 1.

• To set up the main page, rename Page 1 to main and then toggle the eyeball icon to make the main folder visible (Figure 2).

• Make additional pages by clicking Duplicate State.• Rename the new state company and in the layers

panel turn on the visibility of the company folder and hide the main folder.

• Do the same thing to create the other pages in the sections folder. Make sure the corresponding layer folder is turned on for each page and the others are turned off (Figure 3).

The issue with static designs is that it doesn’t show how the application will work from one screen to the next. Using Adobe Flash Catalyst CS5, an interactive prototype can be created from the same file that made the designs. This allows for user group testing or a more accurate review by the stakeholders. Finding out what works and what doesn’t early in the process will save development time. Also, once the prototype is approved, the same file can be used in development.

Figure 3. Pages in Flash Catalyst

Figure 6. Viewing the Source code

Figure 4. Converting a graphic to a button

Figure 5. Adding interactivity to a button

Page 44: Flash Flex August 2011

08/2011 (26)44

DESIGN How to Promote a More Seamless Designer/Developer Workflow

08/2011 (26) 45

Creating ButtonsIn order for the user to navigate to the different pages, buttons need to be created.

• Select the Main text in the top bar. The Flash Catalyst Heads UP Display (HUD) will appear.

• Click Convert Artwork to Component and choose Button from the component list.

• Do the same for the remaining text objects in the top bar.

Adding Interactions to ButtonsOnce buttons are created, interactions can be added to them.

• Select the Main button and in the Interactions panel click, Add Interaction.

• From the Choose State dialog, select Main. When the Main button is clicked, the Main content will be shown (Figure 4).

• Add interactions to the other buttons to jump to their corresponding page when they are selected (Figure 5).

• Run the project by going to File>Run Project. The project will be displayed in your default web browser.

Additional features can be added to a Flash Catalyst project such as transitions, audio, video, data lists, scrollbars, and even SWF content created in programs like Flash Professional CS5.

From Interactive Prototype to Final DevelopmentThe great thing about making an interactive prototype in Flash Catalyst is that the same file can be opened in Adobe Flash Builder 4. Flash Builder helps software developers rapidly develop cross-platform RIAs and content. It includes support for intelligent coding, debugging, and can easily connect to Web services or databases.

Opening a Flash Catalyst �le in Flash Builder

• In Flash Builder, open a Flash Catalyst project by going to File>Import>Import Flex Project (FXP)…

• Once imported, expand the src folder and look in the default package where you will find the Main.mxml file. Double click it to open.

• Click Source view to see the MXML code created in Flash Catalyst, such as the button functions (Figure 6).

• Click on the Design view to see and further edit the design, and even toggle between the pages using the States panel.

Figure 7. Connecting to data or services

Figure 8. De�ning the XML Source

Figure 9. Data/Services panel in Flash Builder

Figure 10. Getting data when a button is clicked

Figure 11. Code Snippets in Flash Professional

Page 45: Flash Flex August 2011

08/2011 (26)44

DESIGN How to Promote a More Seamless Designer/Developer Workflow

08/2011 (26) 45

Connecting to Dyanamic DataYou can easily use data from many different types of sources.

• Using the Data/Services panel, select Connect to Data/Service to specify the data source you want to use. In this case it will be an XML type (Figure 7).

• To invoke a Twitter feed http://search.twitter.com/search.atom?q=Traveller and get the entry node (Figure 8).

• To use the data service just drag and drop the getData() function call onto the (Twitter feed; see Figure 9).

• Change the text provider to title so the title is displayed in the text box.

• For the getData() call enter Traveller as a sample parameter to search for. Now, save the project and select Run>Run Main to test in a browser. Any Twitter feed containing the word Traveller will now be listed on the main page (Figure 10).

This is only one of many features of Flash Builder 4. Note that Flash Builder allows for the creation of rich applications based on the Flex Framework, complete with imported graphics and SWF files. It can also be used to write ActionScript for Flash Professional projects, complete with code hinting and code completion.

Publishing the ApplicationOnce the application is complete, it can be delivered as a Web or desktop application. The Web application would use the cross-browser Flash Player runtime, while the desktop application would use the Adobe AIR runtime.

Creating Rich, Immersive ExperiencesIn some cases you might want even more control over graphics, animation, video, audio and other elements. If that’s the case then Flash Professional might be in order. Not to worry – Flash Professional follows a similar workflow. Just import the PSD or AI file directly into Flash Professional. The integrity of the design will be maintained, complete with layers and editable text if so desired.

Adding InteractivityOne new feature in Flash Professional is the ability to add pre-written ActionScript by using the Code Snippets panel. Simply select the button or movie clip you want to add a code snippet to and double click the code snippet you’d like to add. Not only can you add code snippets, you can also save code snippets back to the same panel for use later (Figure 11).

The Flash Builder ConnectionMore experienced Flash developers can use Flash Builder as their coding environment to write ActionScript. They can, for instance, create an external document class in Flash Builder that is referenced in Flash Professional to control interactivity (Figure 12).

Once the project is complete with interactivity, animation, video, and/or audio, it can be deployed as SWF files for the Web, desktop or mobile application using the AIR runtime.

ConclusionThe workflow between designer and developer doesn’t have to be filled with compromises and/or long hours. With the right tools, it can truly be a seamless process, with projects that are completed quicker, with better results, and that leave everyone involved in the process much happier and more productive.

Figure 12. Write ActionScript in Flash Professional or Flash Builder

PAUL TRANIPaul Trani, Flash Platform Evangelist for AdobePaul started his design experience from humble beginnings with Play-Doh and now has evolved into a passionate 15-year veteran of the interactive design and development industry. As an Adobe Flash Platform Evangelist, Paul has earned a reputation as a dynamic and respected speaker drawing from his experiences as a presenter, Adobe Certi�ed Instructor, courseware developer, and Lynda.com trainer. From his Flash Professional “Training with Trani” videos on AdobeTV to his many tips and tricks on his blog, Paul is here to show you how to create your content for web, mobile and everything in between.Follow Paul on Twitter and check out these other great resources:http://www.paultrani.com/blog/http://designupdate.com/blog/http://www.lynda.com/home/ViewCourses.aspx?lpk1=202http://tv.adobe.com/show/training-with-trani/

Page 46: Flash Flex August 2011

08/2011 (26)46

PRODUCT REVIEW

KoolMoves is a flash authoring tool sold for fifty dollars. It offers different work environments for beginners and advanced users, so it serves

almost any Flash developer. It supports AS3 scripting, motion tweening, and bone animation and features a proprietary 3D engine. With that said, it is hard to figure out why people are not using it everywhere by now.

Even though KoolMoves is officially meant for Windows systems, I tried running it on my Acer Aspire One with the latest Ubuntu version, and, to my surprise,

it runs. It was just a matter of opening the Software Center and downloading the Wine compatibility layer and Gnash, which is a GNU standalone Flash player that is needed to run your stuff, well, in a standalone player. This is very significant for Linux users, as it means there is finally a complete Flash IDE for those on the penguin side and it is not very resource demanding, as a modest netbook managed to give it a go. Just remember to save frequently, as the program has tends to crash and close from time to time in such a set up.

The drawing tools are surprisingly effective. Vectors are mainly edited by adjusting the position of two types of handlers, one for edges and another for curves. This approach is somewhat different from what the Flash IDE presents, but it is easy to get used to and produces similar results. It would be nice to have intersecting lines crating point over the points of contact, though. Another feature I miss is an adjustable smoothing algorithm, since I am not very precise drawing free-hand.

Being so, if you find the tools provided with the program lack resources you need, at least you can rest assured many vector formats are supported, which means you can create anything in your vector editor of choice and then import your artwork into KoolMoves and have it fully editable as if it were created there in the first place. You can also import raster graphics, but bear in mind KoolMoves will not be able to much more than scaling it, so a good external image editor is necessary for modifying raster graphics.

KoolMoves supports AS1 and AS3, but not AS2 – which is

KoolMoves 8.1.1

Figure 1. The basic workspace of KoolMoves

Figure 2. The built-in script editor

Page 47: Flash Flex August 2011

KoolMoves 8.1.1

08/2011 (26) 47

a moderate drawback for coders that still have not migrated to AS3 but may also serve as motivation for them to get updated. Nevertheless, you can rely on its compatibility with actual Actionscript, as there are no dialects or specific commands to replace the ones you are already used to – SWiSH Max 4, which is also an excellent tool but a three times more expensive and focused on AS1 and AS2, uses SWiSH Script, which occasionally forces the coder to use exclusive commands in place of the usual ones (such is the case of the SWiSH Script onSelfEvent() function, for instance). There are drop down menus, as one would expect, that provide access to methods and keywords but, since it merely inserts the command without its accompanying syntax structure, it serves more as a quick reference list than an actual scripting assistance tool you can use before going through the official AS reference documentation by Adobe. Unfortunately, the editor does not offer a code navigation and overview panel nor code completion and suggestion, and, strangely enough, the mouse wheel does not scroll the code, but you can

always use the free FlashDevelop as an external editor. On the other hand, it features good syntax highlighting, which makes the code more readable by humans. Indentation works just fine, which is a huge plus – and quite obvious to any programmer that ever had to work with an editor that messes up the good old four-spaces-or-TAB standard – and this also adds to the readability of the code.

Many useful components make it easy to add media players, forms, menus, buttons, spectrum analyzers, scrolling bars, color pickers, text editors, and other gadgets to your project, in case you are developing a website, Web or local application, or interactive presentation. In case you are a game developer, KoolMoves comes with a library called Necro3D which is, simply put, a 3D engine built on AS3. There are plenty of examples with source code for you to get the hang of it, which somewhat compensates for its relative obscurity, as there are not many developers currently using it. There are no modeling capabilities implemented, so you will have to import your models in one of the supported

formats, namely 3ds, ase, md2, and obj. I just wish the developers let the user place objects in 3D space through the GUI, in a world editor of sorts, for it would make the 3D development in their IDE a breeze – but, well, Necro3D is, indeed, a pretty cool feature.

The presence of an internal 3D engine is also convenient, if not necessary, because external libraries such as Sandy3D, Away 3D, and Papervision might not have all dependencies fulfilled by the AS3 implementation that powers KoolMoves. This means that, if you are considering this IDE for a project built upon one of such libraries, you really should download the demo first and verify if there are compatibility issues or not, and, in case your engine of choice does not work, if Necro3D fits your needs. If you visit www.protomnimultimedia.com, you can check out a small experiment I made importing my logo as an OBJ model and rotating it, either automatically or accordingly to mouse input (click and drag).

There are also many motion scripts and effects included, both in 2D and 3D, which are accessible through the GUI. Their

Figure 3. A motion script being applied to an imported raster image

Figure 4. 3D effects being applied to a text object

Page 48: Flash Flex August 2011

08/2011 (26)48

PRODUCT REVIEW

results are amazingly good and serve many purposes, but, thankfully, you can make your own animations and tweens by using the timeline, so, if none of the provided animations fits your needs, you are are free to make it on your own. The downside is that you cannot apply the 3D effects to shapes filled with gradients or raster images – although you can still use the motion scripts with them.

The included bone tools are very straightforward and, used properly, can lead to a significantly shorter production time for animations, depending on the style you are aiming for. Even though it is not possible to create a skeleton for a symbol, you can apply the bone structure to a shape and then convert it to a movie clip, so it is more a matter of work flow than a true limitation. Such an inexpensive piece of software featuring this sort of animation is quite amazing – specially if you take into account that it was only recently that Flash incorporated a similar technology. Another important animation feature that eases considerably the creation process is onion skinning, and, fortunately, it is present in this little box of surprises.

There are many format options for exporting, but no FlashLite support, which is a drawback for mobile developers, no doubt about it. Most raster and vector file types are included, but no animation output other than swf, so there is no direct way of exporting animated GIFs or AVI movies. The help documentation suggests you export a series of raster captures of your frames, which is simple and requires only one export process, and then use some free tool to convert all output images into a single animated GIF. Good enough for me.

Interestingly enough, KoolMoves also exports HTML5 animations. It is clearly in its early implementation stages, but it is a promising feature that may, even now in its current form, open new possibilities for mobile developers and, in a more general way, those who wish

Figure 5. Onion skinning makes animation simpler

to experiment with this exciting new version of the language.

The help system is excellent. The documentation, which can be brought up by pressing F1, is concise but comprehensive. Many windows feature question mark buttons which open a small, straight to the point list of guidelines and tutorial links related to whichever functions that window offers. There are also many tutorials for most of the tools the program features, including very descriptive and easy to understand screencasts.

The community is not huge, of course, but is active and responsive. If you cannot find help in the forums, their support e-mail is also helpful and they reply with admirable quickness and politeness.

Most panels can be accessed by pressing a keyboard shortcut of one single key, which is usually a letter that has to do with the function name – such as T for text fields, R to rotate, F to select the color of a shape, P to display or hide the object properties window, and so on and so forth. It might take a while to adapt, as is the case with almost any piece of software, but it really will not take long before you get used to pressing A for a quick change of a variable in your script editor.

All in all, KooMoves is unbelievably feature-rich and powerful for its fifty dollar price tag and and should be part of the toolset of any Flash developer that, for one reason or another, does not use the official IDE. It is wise, nonetheless, to spend some time with the demo before buying.

PEDRO DE LA ROCQUEPedro de La Rocque is a professional programmer, developer, and translator. About to graduate in Philosophy in UFRJ, he currently works for Alpha CRC and develops under his own trademark Protomni Multimedia. Even though Pedro has been working as a freelance Flash developer and AS coder for about �ve years, his acquaintance with programming dates back to green phosphor displays. These days, he has been doing most of his coding in AS3, Python, Lua, C++, and DarkBASIC. http://www.protomnimultimedia.com.

Page 50: Flash Flex August 2011

08/2011 (26)50

PRODUCT REVIEW

The flex calendar component enables developers to display events, handles users’ actions like navigation in time and event modifications.

Developed from September 2009, the component formed initially part of an internal search and development project which was extracted to make a packaged component. The KeepCore research and development team encountered some difficulties during its first development more particularly about time management and display performances. The Flex framework brings initially only few date handling methods, therefore KeepCore created its own method library to solve problems and handle calculations on time. To get the best performances, complex mechanisms of data caching have been developed to avoid useless rendering and enable simultaneous displays of large quantities of events.

It has to be noted that for the management of animations on transitions’, the component uses the excellent library tweening GreenSock.

The KC-Calendar Component was a long lasting job: it took four main evolutions to obtain a complete and efficient solution.

When the project started, using FLEX wasn’t obvious for the R&D team at KeepCore even if the majority of the company’s projects are developed with this language. In 2009, the Flex technology was only emerging, but KeepCore took the risk because this

language offers high performances, excellent graphics and user interactions (drag&drop…).

A Component for DevelopersKeepCore has designed this component to make the developers’ lives easier especially for those who need to quickly and efficiently render events in time and offer an event manager to users.

The KC-Calendar component is flexible to use and completely customizable, thanks to FLEX which offers attractive ergonomics and enables high level of interaction with users. The advantage that developers get of this language is the adaptability of the component as it runs on the majority of environments.

The component doesn’t impose a particularly type for event objects which are displayed, the choice of type is left to the developer. The developer has just to define the mapping between his data and the data required by the component for displaying these events (starting date, end date, text, colors…). Furthermore no storage intelligence is embedded in the component. It’s fed by an ArrayCollection and informs by events the possible modifications. The developer is free to stock and update data in his preferred format (memory, files, database…)

The KC-Calendar component has English and French natively embedded, and supports any other languages.

Finally, many styles and properties enable a complete customization.

The Flex KC-Calendar Component by KeepCore KeepCore designs and develops Flex components that they sell worldwide. Their key component, the KC-Calendar is the most powerful on the market, referenced by Adobe.com on Le Tour de Flex.KeepCore has recently launched the 1.5 version of the KC-Calendar available on its marketplace dedicated to Flex components: http://www.flex-component.com The demo of the KC-Calendar is here.

Page 51: Flash Flex August 2011

KeepCore

08/2011 (26) 51

of information in different views: day, week, month, year, with a possibility of innovative column view which displays different resources or a stacked view where events are stacked daily one after another.

KeepCore R&D team specially focused its work on the interaction between the component and the user, who can customize his calendar according to his needs: configuring the days, the time line color, personalizing how an event is displayed, picking the first day of the week and above all the much required Drag and Drop function.

KeepCore now sells its Flex KC-Calendar component through its Flex-component.com website and regularly offers new components for developers and companies.

The company benefits from the risk it took with the use of RIA technology which is today number one on the market.

The KC-Calendar component can be used in many different types of projects, answering planning, resource and event visualization needs.

A Wide Range of Features for the End-usersFrom the users’ point of view, the component offers many advanced and effective features like the display

Figure 2. Flexible usages of the KC-Calendar: inserting multimedia objects, editing event, selecting “day starts” and “day ends” hours…

Figure 1. Providing great UI alongside easy integration: Week view of the KC-Calendar: switching to Day, Month, Year view, personalized colors, “week start” day…

KEEPCORE

Page 52: Flash Flex August 2011

08/2011 (26)52

BOOK REVIEW

As of now, there are so many books available on Adobe Flex that cater the needs of both a beginner and somewhat advanced developers.

However, until now, there was no book that would teach and share the visual aspects of Adobe Flex in depth. A book that would teach veteran programmers who do not like flash because of its graphical interface and hence prefer Flex and who didn’t get a chance to play with all the cool parts of Flash platform. Chet Haase, a renowned Adobe engineer, has written Flex 4 Fun which talks about graphics, animations and everything between in a most humorous way ever known to Flex world.

What I like about this book is that even though it does not promise teaching hard core development (but graphics, animations of course), but it still manages to discuss almost everything.

Real fun begins right from the second chapter – Graphics – where you learn about flex drawing primitives and how you can do everything along with the help of drawing application. Then you learn about filters in great detail. Next three chapters discuss about important building blocks of a flex application which are States, Transitions and Skinning Components. Chet will teach you how to skin a component completely without using Adobe Catalyst which is a great thing. Finally

the final chapters fulfill their promise of making you an Animator without use of any visual tools. You learn not only script based animations but also be able to express your creativity with both 2D and 3D (2.5 D) effects. Also, you encounter several hidden gems here and there.

Although this book assumes basic understanding of Actionscript 3 and MXML. Personally, I think that even a newbie can start learning and enjoying this book.

In short, if you are someone whether new or advanced developer who wants to make his or her application visually appealing then this book is for you. If you are someone who has both designing and programming skills then you may not find any new thing from this book. However, being a Certified Instructor, I’ll definitely prefer this book to teach about the artistic side of Adobe Flex.

Flex 4 FunAuthors: Authors: Chet HaasePublisher: artima.ISBN: 978-0981531625Language: EnglishPages: 288 PagesWebsite: http://www.artima.com/shop/flex_4_fun

ALI RAZAAdobe Certi�ed Instructor, Microsoft Certi�ed Professional Developer, Sun Certi�ed Java Programmer, Zend Certi�ed Engineer

1. Introduction2. Graphics3. Filters: Easy Image Processing4. States5. Transitions6. Skinning Components7. Animation8. The Animation Class9. Flex Effects: The Basics10. Advanced Flex Effects11. Effect Choreography12. Picture Perfekt13. Go Have Fun

Page 54: Flash Flex August 2011

08/2011 (26)54

BOOK REVIEW

Could you please tell our readers something about yourself? What do you specialize in?I am a freelancing software developer living in Northern Germany with my lovely wife Simone. I develop elegant and easy to use applications for iPhone, iPad, Mac and the web using iOS, Objective-C, Cappuccino, SproutCore and JavaScript. I sometimes write articles for magazines and regularly speak at conferences. I also contribute to open source projects and maintain a couple of my own projects which you can see on my github page (http://github.com/jfahrenkrug).

Could you please tell us something about your book?I’ve written the chapters on Core Data, GCD and Blocks and exception and error handling. I tried to explain the topics in a simple yet in-depth way. All of the chapters of the book contain a lot of hands-on code examples. I always love that in other books I’ve read so I’m glad that this book I’m involved in turned out the same way.

To whom is your book directed?It’s directed to people who have some programming experience in a different language but are completely new to Objective-C. So it’s not an intro to programming, it’s an intro to Objective-C programming.

Objective C language recently has gained some popularity due to the success of mobile products such as iPod touch, iPhone and iPad. Can you tell our readers more about the trend of programming in Objective C language?Well, obviously the success of the iPhone and the App Store attracts a lot of people to Objective-C since that’s the language native iOS are developed in. As long as Apple keeps up that success and growth more and

more people will probably want to and/or have to learn Objective-C.

What are the capabilities of Objective C?It’s a very expressive elegant object-oriented program-ming language. It’s not as concise and dynamic as Ruby, but it’s fast and easy to read. More than the language itself Apple’s Cocoa and Cocoa Touch frameworks provide a lot of power that makes iOS and Mac development so much fun.

Is it possible to use Objective C in any other way than in the cell phone?Of course. It’s used to build Mac applications and it can also be used on any other platform that runs the gcc compiler. Although it won’t be as attractive to use on those platforms because the Cocoa frameworks don’t exists there. At least not in their entirety, just parts of them in an open source project called GNUStep.

What are the predictions for future regarding the Objective C language?It will continue to evolve thanks to the genius of people like Chris Lattner of the LLVM project who works for Apple. Since neither the growth of the Mac nor the iOS platform seems to be slowing down, I see a very bright future for Objective-C. I would not be surprised, though, if Apple would add other languages like JavaScript as a first class citizen to their platforms at some point down the road.

What would be your next step? Are you planning to write other books?Just writing a few chapters for a book is a lot of work. I think for now I’ll stick with writing articles for magazines. I won’t rule out (co-)authoring another book at some point down the road if the topic is really interesting.

Interview with Johannes Fahrenkrug– One of The Authors of Objective C Fundamentals

INTERVIEW