Using Zend_Amf with Flex

We have to do the following from flex script
1. Setting a target url
There are different ways to do it and I share one of them.
We need to create service-config.xml and save that in the project src folder.
Ex:
services-config
services
service id="amfphp-flashremoting-service" class="flex.messaging.services.RemotingService" messageTypes="flex.messaging.messages.RemotingMessage"
destination id="flex_amf"
channels
channel ref="my-zend"
channels
properties
source*Flex Compiler settings.
Ex:-locale en_US -services service-config.xml
3. In your mxml file add RemoteObject component
Ex:

In this source is the class name that you are using in PHP and destination refers to destination tab in the service-config.xml file
4. Create a button to execute the click function and in that call the function you need to execute in the class file.
zendRemoteObject.functionName(parameters)
5. You will get the amf response in the result or fault event functions

You have to do the folloing in PHP class to return the amf response.

1. Include the Zend_Amf library
Ex:
require_once 'Zend/Amf/Server.php';
2. Create object of amf server
$server = new Zend_Amf_Server();
3. Set the class that we need to map with
$server->setClass("className");
4. Map ActionScript value objects to the PHP value objects.
$server->setClassMap("className", "className");
5. Then print the handle response.
Ex:echo ($server->handle());

Create associative array in Flex

It's not possible to create array like array('branchId'=>1,'order'=>2)
For that first we have to define a variable as array
Ex:
var attr:Array = new Array();
attr["branchId"] = 1;
attr["order"] = 2;

Geneate/Create ArrayCollection dynamically

var resultArr:ArrayCollection = new ArrayCollection(e.result as Array);
var careeListData:ArrayCollection = new ArrayCollection();
var resultArray:Array = new Array();
if((resultArr.length > 0) && (resultArr[0]["whoForId"] != null)){

for(var l=0; l < resultArr.length; l++){

resultArray.push({label:resultArr[l]["careeName"], data:resultArr[l]["whoForId"]})

}
careeListData = resultArray as Object;
}

Combobox with change event to get the selected item value

In the script add the following

private var listData:ArrayCollection = new ArrayCollection(
[{label:"Arun Kumar", data:"3"},
{label:"John Jose", data:"1"},
{label:"Mary Dam", data:"2"}]);
private function getSelectedCaree(event:Event):void
{
trace(event.currentTarget.selectedItem.data);
}

In the MXML add the following to show the combo-box with change event

mx:ComboBox id="comboList" change="getSelectedCaree(event)" fontSize="15" x="1000" y="50" dataProvider="{listData}"
/mx:ComboBox

Confirmation Alert box with OK and Cancel

Alert.show("Do you want to remove all the events", "Confirmation",
Alert.OK | Alert.CANCEL, this,
confirmRemove, null, Alert.OK);

private function confirmRemove(evntObj:CloseEvent):void
{
if (evntObj.detail==Alert.OK) {
//Add the code to execute if use pressed OK button
}
}

Convert Flex date timestamp to UTC timestamp

var localDate:Date = new Date();
var localTimestamp:Number = localDate.valueOf() / 1000;
//date with valueOf function returns the milliseconds and divide by 1000 to convert to seconds
var timzoneOffset:Number = localDate.timezoneOffset * 60;
//Timezone offset returns the minutes and multiply by 60 to convert to seconds to use for timestamp
var utcTimestamp = localTimestamp + timzoneOffset;

Adding Timer Event Listener

For adding or handling the time based functions we can use flex Timer Util class.

import flash.events.TimerEvent;
import flash.utils.Timer;

private var timer:Timer;

private function init():void
{
timer = new Timer(10);
timer.start();
timer.addEventListener(TimerEvent.TIMER, checkDbChange);
}
private function checkDbChange(t:TimerEvent):void
{
trace("Database updated");
}

File not found in bin-debug/*.html

It happens while we import the project. To solve the issue you can try the following way

1. Project->Build Automatically then try
2. Project->Clean the selected project then try
If the above procedure doesn't work try the following.
3. Project->Properties->Compiler Settings
Check HTML Wrapper and If Not checked checked and try.
If the HTml Wrapper is checked the un-check then save then try to run it again.It will not work then again check the HTML Wrapper and try. I got it solved the issue.

Error Cannot convert XMLList@5967b21 to Date

To convert XMLList date to date, first convert it to String then the date string into Milliseconds using the Date.parse method. Then you can convert the seconds to Date object

Ex: var dateString:String = xmlDateValue.toString();
var dateInMilliseconds:Number = Date.parse(dateString);
//date format "Wed May 4 15:30:17 GMT-0700 2011"
var curDate:Date = Date(dateInMilliseconds);

Convert String to Date

To convert string to date, first convert the date string into Milliseconds using the Date.parse method. Then you can convert the seconds to Date object

Ex: var dateInMilliseconds:Number = Date.parse("Wed May 4 15:30:17 GMT-0700 2011");
var curDate:Date = Date(dateInMilliseconds);

Convert String into Array

We can convert the String into Array with splitting it with delimiter.
Ex:
var sampleString:String = "Hello World";
var results:Array = excDate.split(" ");

How to show the recurreneRule from database in the pop-up recurrencePanel

In the Calendar Click event add code to get the rule and create and object of recurence Panel. Then set the recurrenceRule variable in recurrencePanel

Ex:
_recurrencePanel = new RecurrencePanel();
_recurrencePanel.recurrenceRule = new RRule(cal.selectedItems[0].item.@rrules);

Get and Set function declaration

Flex script has Get and Set functions that can encapsulate property access behind function calls, but without changing the property access syntax.

This tells ActionScript that the functions are for property access. While the code looks quite different than just using a public property, the usage is exactly the same.

Ex:

public class HelloWorld
{
private var _strValue:String;

public function get strValue():String
{
return this._strValue;
}

public function set strValue( value:String ):void
{
this._strValue = value;
}
}

TextInput focus in and out events

We can use focusIn and focusOut events for getting values on or out of focus.

Ex: mx:TextInput id="summaryTxt" width="100%" focusOut="summaryTxt_focusOutHandler(event)"

How to change the Calendar mode to Month view

In the IBM ILOG Calendar, the default is Week View. We can change it by adding the following code in the init() function.

cal.mode = Calendar.MONTH_MODE; //cal is the id of the ilog calendar object

Get recurring event id while editing

In the ITEM_EDIT_END event, use the below code to get the recurring event id.
var eventId:int = cal.selectedItems[0].item.@eventId.toString();
trace(eventId);

Convert Object to XML

private function convertobjectToXML(obj:Object):XML
{
var qName:QName = new QName("list");
var xmlDocument:XMLDocument = new XMLDocument();
var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
var xml:XML = new XML(xmlDocument.toString());
trace(xml);
return xml;
}

Convet AMF Object to XML

var result:Object;
var listCollection:ArrayCollection = new ArrayCollection(result as Array);

var mainXML:XML = list //root xml tag
for(var i:int=0; i < listCollection.length; i++)
{
if(listCollection[i]['event_id'] != null){
var myXML:XML = event //child xml attribute
myXML.@id=listCollection[i]['event_id'];
myXML.@s=listCollection[i]['start'];
myXML.@e=listCollection[i]['end'];
mainXML.appendChild(myXML);
}

You will get the xml data in the mainXML variable

How to use Alert.show method

mx:Script
private function showAlert():void{
Alert.show('message','title',flags,parent,clickListener,iconClass,defaultButton);
}
mx:Script close

flags - mx.controls.Alert.OK — OK button
mx.controls.Alert.YES — Yes button
mx.controls.Alert.NO — No button
mx.controls.Alert.CANCEL — Cancel button
parent - parent object
clickListener - listener function name for flags

Get event id for editing event data in the Database

you can get the event id set in the dataProvider in editItemEnd function using the below script.
trace(event.item.id);
private function itemEditEnd(event:CalendarEvent):void {

if (event.item is IRecurrenceInstance) {
//code for recurring event
}else{
trace(event.item.id);
}

}

Client.Error.DeliveryInDoubt / Channel disconnected before an acknowledgement was received

It's because of the error in the ZEND_AMF Script.

To solve this problem make sure that:

* Your Adobe Flex function parameters and PHP function parameters are of the same number.
* The parameters of your Adobe Flex function are in the same order with its PHP function counterpart.
* All the Adobe Flex function parameters are of the same data type with their PHP function parameters counterpart.
* You assign a default value to the optional parameters in the PHP function.
* You pass a value to the parameters that are not optional.
* Finally, your SQL statements should be syntactically correct.

Convert Date Object to Timestamp in Flex Actionscript

For that use the function valueOf() and it will return the timestamp in milliseconds
Ex: var now:Date = new Date();
var timestamp:int = now.valueOf() / 1000; // Divide by 1000 to convert it into seconds

Could not resolve s:Group to component implementation

It may be the issue with Flex SDK version. Please try using the latest version.

Change view using ViewStack container with selectedChild property

1. In the main.mxml file add the following

mx:ViewStack id="mainViewStack"
view:bookSearch id="bookSearch" /
view:bookData id="bookData" /
/mx:ViewStack

In the script assign the viewstack object id to the model instance in init() function
mainModel.mainView = mainViewStack; //mainModel => Binded model to change the view

2. Create canvas using the above view names and add these into cairngorm view folder
Refer the below link for creating canvas in Flex Builder
http://flextutorial4you.blogspot.com/2011/03/create-canvas-from-flex-builder.html
3. In the model add the following scripts

import mx.containers.ViewStack;

In the class file create static variable of the class name then create and instance of the class
public static function getInstance() : MainModelLocator
{
if ( modelLocator == null )
{
modelLocator = new MainModelLocator();
}

return modelLocator;
}
public function init():void
{
mainView = new ViewStack();
}
public function changeView(viewName:String):void
{
if(mainView.selectedChild.name != viewName)
{
this.mainView.selectedChild.dispatchEvent(new Event("INTERRUPT", false, false));
mainView.selectedChild = Container(mainView.getChildByName(viewName));
}

}
4. Then use the mainModel class and call the function changeView() for changing the view
Ex: mainModel.changeView("bookData");

Create canvas from Flex Builder

1. Select File => New => MXML Component
2. Enter canvas name
3. In the "Based On", click Browse then enter mx.containers.Canvas on the top text-box
4. Then Select the Canvas listed
5. Click Finish

How to use resource file in Flex Application

1. You have to add "MetaData" tag in the view file
open mx:Metadata
[ResourceBundle("ResourceFile")]
close mx:Metadata
2. Create a folder structure locate/local/en_US/ and file ResourceFile.properties
And in the file
# locale/en_US/ResourceFile.properties
main_server_url=localhost
3. In the Project=>Properties=>Flex Compiler
Add the following
-allow-source-path-overlap=true -source-path=locale/local/{locale}
4. To use it in Model
var serverName:String = ResourceManager.getInstance().getString("ResourceFile","main_server_url");

Control NetStream Volume/Sound using soundTransform

public function changeVolume(tranValue:Number):void
{
var audioSound:SoundTransfom = new SoundTransfom();
audioSound.volume = tranValue;
NetStream.soundTransform = audioSound;
}

Move Forward or Backward the Audio/Video Streams

For that we can use the NetStream.seek() function

Ex; NetStream.seek(NetStream.time + 10); //for forward
NetStream.seek(NetStream.time - 10);//for backward

Change Image source dynamically using Action Script

[Embed(source="./images/play.jpg")]
private var playBtn:Class;

private function init():void
{
var asset:BitmapAsset = new playBtn() as BitmapAsset;
play_button.source = asset; //play_button => image id attribute
}

NetStream onMetaData function call

var ns = new NetStrea();
var metaObj:Object = new Object();
ans.client = metaObj
var _playDuration:Number;
metaObj.onMetaData = function(obj:Object)
{
_playDuration = obj.duration;
trace(_playDuration);
}

Buffering Audio/Video Streams

Buffering a video stream helps ensure that the video plays smoothly, without interruption.

To create the best experience for users, monitor the progress of a video and manage buffering as the video downloads. You may need to set different buffer sizes for different users, to ensure the best playback experience. One choice is to detect a user's bandwidth (http://livedocs.adobe.com/flashmediaserver/3.0/hpdocs/help.html?content=00000070.html#1046682) and set an initial buffer size based on it.

While the stream is playing, you can also detect and handle netStatus events. For example, when the buffer is full, the netStatus event returns an info.code value of NetStream.Buffer.Full. When the buffer is empty, another event fires with a code value of NetStream.Buffer.Empty. When the data is finished streaming, the NetStream.Buffer.Flush event is dispatched. You can listen for these events and set the buffer size smaller when empty and larger when full.

Code to fit Adobe AIR application in the desktop window

To fit the Adobe Window Application in the desktop you need to call the below script in the applicationComplete event.
ie
In mxml file
applicationComplete="init()"

In the script add the below function
private function init():void
{
this.nativeWindow.maximize();
}

Calculate Audio play progressing time

private var sound:Sound = new Sound()
private var channel:SoundChannel = new SoundChannel();

sound.addEventListener(ProgressEvent.PROGRESS, onProgress);

private function onProgress(event:ProgressEvent):void{
var percentLoaded:Number = event.bytesLoaded / event.bytesTotal;
var approxProgress:Number
= channel.position / sound.length * percentLoaded;
// Update your progress bar based on approxProgress
}

How to add Browser window page title in Flex

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

How to check whether the flex array is not empty

We can check by using array length.
ie. array.length > 0

How to get the button id on click event

private function clickEvent(clickEvent:Event):void
{
var buttonName:String = clickEvent.currentTarget.id;
}
In the button call the function(clickEvent(event)) on click event

Convert Flex Object into Array

var arrCol:ArrayCollection = new ArrayCollection(obj as Array);

Flex RemoteObject property using Action Script

public function searchBooks(srchString:String):void
{

var url:String = "http://localhost/audioData/index.php?srchTxt="+srchString;
var channel:AMFChannel = new AMFChannel("my-amfphp", url);
var channelSet:ChannelSet = new ChannelSet();
channelSet.addChannel(channel);
var ro:RemoteObject = new RemoteObject("amfphp");
ro.channelSet = channelSet;
// Specify the PHP class
ro.source = "AudioBooksData";
ro.showBusyCursor = true;

ro.addEventListener(FaultEvent.FAULT, searchFaultEvent);
ro.addEventListener(ResultEvent.RESULT, searchResultEvent);
ro.getAllDeatils();
}
public function searchResultEvent(e:ResultEvent):void
{
searchResult = e.result;
}
public function searchFaultEvent(e:FaultEvent):void
{
Alert.show(e.toString());
}

Create sampe application using ZEND AMF and RemoteObject

Please check the following url.
http://www.lonhosford.com/lonblog/2010/08/26/zend-amf-action-message-format-minimalist-example-using-remoteobject-and-mysql/

How to comment the mxml code

You can use the shortcut key Ctrl+Shift+C