Replace strings inside a sentence using regular expressions

A classic scenario:
- you have a lot of localized sentences with a generic -USER- word (i.e. USER has been kicked, USER is very cool, and so on)
- you want replace and display these sentences replacing -USER- with the real user name
var loggedUser:String = "Fabio";
var localizedString:String = "-USER- has been kicked"

....

var myPattern:RegExp = /-USER-/g;
localizedString.replace(myPattern, loggedUser); // Output : Fabio has been kicked

Circular preloader

How to create a circular animation in As3, useful for preloaders
(tested on Flash Cs3/4 but it should works fine in Flex too)
var angle:Number = 0
var centerX:Number = 50
var centerY:Number = 50;
var radius:Number = 22;
var speed:Number = 0.1

var circle:Shape = new Shape();
addChild(circle)
circle.graphics.beginFill(0x00FF00);
circle.graphics.moveTo(centerX, centerY);

function onEnterFrame(e:Event) {

if (angle > 2 * Math.PI)
this.removeEventListener(Event.ENTER_FRAME, onEnterFrame)

trace("angle", angle)
circle.graphics.lineTo(centerX + Math.cos(angle) * radius,
centerY + Math.sin(angle) * radius);

angle += speed;
}
this.addEventListener(Event.ENTER_FRAME, onEnterFrame)

HTTPService: call a php script passing parameters and receive a response from server

How to send an user name from Flex to the PHP file and receive its email address
(naturally you could make a query to the db to get these values)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
creationComplete="init(event)" >


<mx:Script>
<![CDATA[

import mx.events.FlexEvent;

private const NOME_UTENTE:String = "Fabio Biondi";

private function init(evt:FlexEvent):void
{
phpRPC.url="assets/Es02_CheckUser.php";
phpRPC.send({ utente: NOME_UTENTE} )
}


private function viewEmail():void
{
outputArea_txt.text = phpRPC.lastResult.email
}

]]>
</mx:Script>


<mx:HTTPService
id="phpRPC"
resultFormat="flashvars"
result="viewEmail()"
/>


<mx:TextArea
id="outputArea_txt" y="20"/>


</mx:Application>


// PHP CODE
<?php

switch($_REQUEST['utente'])
{
case "Fabio Biondi":
echo "email=info@fabiobiondi.com";
break;

default:
echo "email=User not found";
break;
}

?>

Extend a Flex component in AS3 or MXML

You'll extend a VBOX class to create a new "labeled VBOX component" passing the title as new parameter.

<ui:VBoxLabeled labelVBox="MXML VBoxLabeled" width="200" height="200" />

Following two examples: in MXML and AS3
// AS3 Version
package com.domain.ui
{
import mx.containers.VBox;

public class VBoxLabeledAS extends VBox
{
import mx.controls.HRule;
import mx.controls.Label;

[Bindable]
private var _label:String;

public function VBoxLabeledAS()
{
super();
this.setStyle('backgroundColor', 0x999999)
}

public function set labelVBox(val:String):void {


// Create Title Label
var label:Label = new Label();
addChild(label)
label.text = val;

// Create HRule
var hr:HRule = new HRule();
addChild(hr)
hr.percentWidth = 100;

}



}
}


//MXML Version
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
width="100%" height="100%"
backgroundColor="#999999"
>
<mx:Script>
<![CDATA[
import mx.controls.HRule;
import mx.controls.Label;

[Bindable]
private var _label:String;

public function set labelVBox(val:String):void {


// Create Title Label
var label:Label = new Label();
addChild(label)
label.text = val;

// Create HRule
var hr:HRule = new HRule();
addChild(hr)
hr.percentWidth = 100;

}
]]>
</mx:Script>


</mx:VBox>

Using mxml transitions

Following script allows to expand and close a Flex component using a nice smooth transition
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="100"
styleName="container" currentState="closed">


<mx:Script>
<![CDATA[
import mx.effects.easing.Back;
import mx.effects.easing.Bounce;

private function onChangerClick( event:Event ) : void {

currentState = ( currentState == "open" ) ? "closed" : "open";

}
]]>
</mx:Script>




<!--STATES-->
<mx:states>
<mx:State name="open">
<mx:SetProperty name="height" value="450"/>
<mx:SetProperty target="{changeStatusButton}" name="label" value="Close"/>
</mx:State>

<mx:State name="closed">
<mx:SetProperty target="{this}" name="height"
value="100" />
</mx:State>
</mx:states>




<!--TRANSITIONS-->
<mx:transitions>

<!--Define the transition from 'open' to 'closed' state -->
<mx:Transition fromState="open" toState="closed">

<!--Parallel Transition-->
<mx:Parallel duration="500">

<!--Define RESIZE transition attributes specifing the target (the whole component)-->
<mx:Resize target="{this}"
easingFunction="{mx.effects.easing.Bounce.easeOut}"
duration="1500"/>
</mx:Parallel>

</mx:Transition>


<!--Define the transition from 'close' to 'open' state -->
<mx:Transition fromState="closed" toState="open">

<mx:Parallel duration="500">
<mx:Resize target="{this}"
easingFunction="{mx.effects.easing.Back.easeOut}"
duration="1000" />
</mx:Parallel>

</mx:Transition>
</mx:transitions>



<mx:Button id="changeStatusButton" label="Open"
click="onChangerClick(event);" />

</mx:VBox>

Dispatch Custom Event passing parameters

You can't pass parameters using dispatchEvent in As3 so the best way to do it is to create a custom class that extend the Event class.
You'll dispatch the new event in this way:

var e:CustomEvent = new CustomEvent(CustomEvent.FORM_SUBMITTED, nameTxt.text, surnameTxt.text);
this.dispatchEvent(e);


Following the CustomEvent class:
package events
{

import flash.events.Event;

public class CustomEvent extends Event
{
public static const FORM_SUBMITTED:String = "FormSubmitted"

public var name:String;
public var surname:String;

public function CustomEvent( _type:String, _userName:String, _surName:String):void
{
super(_type);
this.name = _userName;
this.surname = _surName;
}


override public function clone():Event
{
return new CustomEvent(type, name, surname);
}
}
}


Call an actionscript method from an xml file

When you load an XML file you can specify to open external links using an HTML tag inside your XML file:
< a href=" link.html > Label </a>.

In the same way you can say to Flash to call a method using:
< href="event:eventName">Label</a>


and using following actionscript code to listen for the event:
(NOTE: we are simulating the old ASFunction method used in ActionScript 2.0)
PrivatyLabel.htmlText = privacyLabel // retrieved from a previous XML loader (see description above)
PrivatyLabel.addEventListener(TextEvent.LINK, methodToCall);

public function methodToCall(e:TextEvent):void
{
// actions here
}

actionscript 3.0 and e4x: search strings inside an XML object

Find a defined string inside an XML object
// String to Find
var stringToFind:String = "Flash Media";

// XML Object
var myXML:XML =
<order>
<item id='101'>
<title>Technologies</title>
<desc>XML e4x rulez</desc>
</item>

<item id='102'>
<title>Adobe Products</title>
<desc>Flex, Flash, Air, FlashLite, Catalyst, Flash Media Server 2, ... </desc>
</item>


<item id='103'>
<title>Server Side Products</title>
<desc>Flash Media Server 3, Flash Collaborative Service, ColdFustion</desc>
</item>

</order>


// Loop over the XML items
for (var i:uint = 0; i < myXML.item.length(); i++) {

// Get the item description
var tempString:String = myXML.item[i].desc


/*
* Check if the defined word does exist in the description, displaying:
* - Node title
* - Node ID
* - XML node index (from 0 to N)
* - The searched word
*/
if (tempString.search(stringToFind) != -1) {
// This trace displays:
// ---> Adobe Products ( ID - 102 ) contains this word: 'Flash Media' (XML item index: 1 )
// ---> Server Side Products ( ID - 103 ) contains this word: 'Flash Media' (XML item index: 2 )
trace("--->", myXML.item[i].title, "( ID -", myXML.item[i].@id, ") contains this word: '" + stringToFind + "' (XML item index:", i, ")")
}


}

How to set a global component style in Flash / AS3

Use StyleManager class and setComponentStyle method to set global styles
Following code sets color, size and textPadding properties to each Button Component used in your own Flash Application.
import fl.managers.StyleManager;
import fl.controls.Button

// Set a global textFormat for every Button Component
var tf:TextFormat= new TextFormat();
tf.color = 0x0000FF;
tf.size = 16;
StyleManager.setComponentStyle(Button, "textFormat", tf);

// Set a global style property for every Button Component
var styleProperty:String = "textPadding";
var value:Number = 30;
StyleManager.setComponentStyle(Button,styleProperty,value);

Google Search in Flex and ActionScript 3.0

How integrate a Google Search engine and display the result inside your Flex application?

Surfing the the web I found a cool AS3 library, developed by Boulevart, that provides a lot of classes to connect Flex (and Flash too) to Google services (Google Search, Translation, News, and so on) and require few code line to develop nice applications.
NOTE: to test this script you need to download the last API from Boulevart website
<?xml version="1.0" encoding="utf-8"?>
<!--
Use Google Search Bouleaver API
http://labs.boulevart.be/index.php/2008/12/15/google-as3-api/
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="600" height="500">

<mx:Script>
<![CDATA[
import be.boulevart.google.ajaxapi.translation.GoogleTranslation;
import com.adobe.utils.StringUtil;
import be.boulevart.google.ajaxapi.search.web.GoogleWebSearch;
import be.boulevart.google.ajaxapi.search.web.data.GoogleWebItem;
import be.boulevart.google.ajaxapi.search.GoogleSearchResult;
import be.boulevart.google.events.GoogleApiEvent;

private var start:int=0
private var max:int=0
private var lang:String=""
private var __results:Array

private function searchWeb():void{
var google:GoogleTranslation = new GoogleTranslation()

var googleWebSearch:GoogleWebSearch

// Only first time
if(max==0){

// Max result to get
max=nmsResults.value
__results=new Array()

// Trim() method removes whitespace from the front and the end of the specified
if(StringUtil.trim(txtInput.text).length){

// If italian radioButton is selected
if(optItalian.selected){
lang="it"
}

// Start a new Search and waiting for a response
googleWebSearch = new GoogleWebSearch()
googleWebSearch.search(txtInput.text,0,lang)
googleWebSearch.addEventListener(GoogleApiEvent.WEB_SEARCH_RESULT,onWebResults)
}
}else{
// Start a new Search and waiting for a response
googleWebSearch = new GoogleWebSearch()
googleWebSearch.search(txtInput.text,start,lang)
googleWebSearch.addEventListener(GoogleApiEvent.WEB_SEARCH_RESULT,onWebResults)
}
}

private function onWebResults(e:GoogleApiEvent):void{
var stop:Boolean=false
var resultObject:GoogleSearchResult=e.data as GoogleSearchResult

trace("Estimated Number of Results: "+resultObject.estimatedNumResults)
trace("Current page index: "+resultObject.currentPageIndex)
trace("Number of pages: "+resultObject.numPages)

// Loop over the result
for each (var result:GoogleWebItem in e.data.results as Array){
trace(result.title,result.url)
start++
if(start <= max){
__results.push(result)
}else{
stop=true
}
}

// make a new search if start < Max
if((start<=(max)) && !stop){
searchWeb()
}

if(stop){
// Populate dataProvider
webResultsView.dataProvider=__results
max=0
lang=""
start=0
}
}

]]>
</mx:Script>


<mx:HBox>
<mx:TextInput width="293" id="txtInput" text="ActionScript.it"/>
<mx:NumericStepper minimum="3" id="nmsResults" stepSize="1" value="15" maximum="30"/>
<mx:Button label="go" click="searchWeb()" />
</mx:HBox>

<mx:CheckBox label="search Italian sites only" id="optItalian"/>

<mx:TileList height="350" id="webResultsView" rowHeight="120" columnWidth="500"
columnCount="1" right="10" left="10" top="50" bottom="10"
itemRenderer="WebItem"></mx:TileList>


</mx:Application>