[Tip] Fix AS3-Flex Error #2032 Stream Error

Recently I encountered an error #2032 within a two year project in Flex, for three days I struggled with it and tried almost everything, this is why I’m posting this here so that it might save someone else time.

This error occurred when I tried to do an HTTPService call to the Back-End and send some really heavy file. The file would require Back-End parsing and when that was over it would return a result. However mid-way the POST call would be interupted and I was presented with a #2032 Stream Error fault.

The solution was both simple and extremely hidden and in my opinion stupid. In the HTTPService I had set the property:


this.requestTimeout = 3800;

However as shown in this post: http://stackoverflow.com/questions/8820715/flex-httpservice-times-out-anyway

This property is NOT taken into consideration by the HTTPService.

It needs:


import flash.net.URLRequestDefaults;
URLRequestDefaults.idleTimeout = 1200000; // or any amount of time in ms

This way we override the default timeout of EVERY call and thus the request no longer fails…

I truly hope this helps someone as the above post helped me.

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex / Air post apocalyptic battleship game [Post-Grid]

Hello, I have just released a new Flex/Air game on ActiveDen. Check it out!

large-banner

– It features smart A.I to play against.
– Source files include cross-platform Air application AND Flex Web-application.
– High customization available.
– Based on latest Official Adobe Flex SDK (4.6)

You can find it here: LINK

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

AS3 send BitmapData to backend efficiently

I was recently asked to send a medium/large file to a backend server running with php. At first I tried sending byteArray but that got messed up from JSON.strigify then I thought to convert the byteArray to base64 format. Although it worked an image of 500×700 occupied ~500kb on the database so it was unacceptable.
The solution was to compess the byteArray and send it, and then decompress it when I received it again. And here is how I did it:


public static function deconstructBitmap(bmp:BitmapData):Object
    {
      // converting the bitmapdata into a byteArray
      var byteArray:ByteArray = bmp.getPixels(bmp.rect);
      // compressing using the default algorithm 'zlib'
      byteArray.compress();
      var enc:Base64Encoder = new Base64Encoder();  
      var b64;
      enc.encodeBytes(byteArray);
      // joining all in one line
      b64 = enc.drain().split("\n").join("");
      // the rectangle is needed for re-contstruction
      return {'bmpData':b64,'rect':bmp.rect};
    }

And now we have a compressed byteArray with our bitmapData the 500×700 bitmap data now occupies ~13kb on the database!

And here is the re-construction of the byteArray into bitmapData ready to be inserted to <s:Image/> or any other component.


public static function constructBitmap(obj:Object):BitmapData
    {
      // to avoid errors
      if(obj!==''&&obj!==undefined&&obj!==null&&obj.bmpData!=='ByteArray'){
        var dec:Base64Decoder = new Base64Decoder();
        dec.decode(obj.bmpData); // decoding using the same algorithm
        var newByteArr:ByteArray=dec.toByteArray();
        newByteArr.uncompress();
        // end of decoding //
        
        var bitmapData:BitmapData = new BitmapData(obj.rect.width, obj.rect.height);
        bitmapData.setPixels(bitmapData.rect, newByteArr);
        return bitmapData;
      }
      else
      {
        return null;
      }
    }

And thats it, two simple functions to make you and your database happy!

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Re-arrange objects in a VGroup by Drag&Drop (Flex Spark)

Adding drag and drop support for Group components, as well as swapping of children or reorder.
This might seem like a straightforward issue and an easy solution, but as I found out… only list based views have the ability to re-arrange their children via dragging and droping. But there is one hidden gem, all the Group based components have build-in support for drag and drop operations, and whilst the user cannot enable directly the dropEnabled option (which allows the re-arrange like operation), it is fairly easy to create a custom functionality to imitate it.
Continue reading

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex audio player with Flowplayer core

I’ll present a simple task that allows to implement the power of the flex framework and flash graphics to a equally powerful core player such as the Flowplayer, bridged with JQuery.

First of all let’s create the graphics for the player, lets assume you have some basic images for the buttons and the background:

<s:Group width=”338″ height=”39″>
<s:Image source=”assets/playerBack.png” smooth=”true” width=”338″ height=”39″/>
<s:Image source=”assets/play.png” smooth=”true” left=”20″ top=”10″ click=”goPlay()” useHandCursor=”true” buttonMode=”true”/>
<s:Image source=”assets/pause.png” smooth=”true” left=”50″ top=”10″ click=”goStop();” useHandCursor=”true” buttonMode=”true”/>

<s:HSlider horizontalCenter=”20″ top=”10″ width=”178″ maximum=”1″ minimum=”0″ showDataTip=”false” stepSize=”0.1″ skinClass=”Skinz.VolumeSkinClass”/>
</s:Group>

!Note: make the <s:Application/> slightly bigger and opaque (height=”45″ width=”360″ backgroundAlpha=”0.0″)

!Note:make sure to include Jquery to your HTML file, I created this with JQuery.1.5.min.js

now a little bit of AS3 script to trigger the Javascript

private function goPlay()
{
ExternalInterface.call(“goPlay”);
}

private function goStop()
{
ExternalInterface.call(“goStop”);
}

Now export a release build and copy the .swf file in your HTML Project folder.

Our Flowplayer lives on a <div/>

<div id=”audiosecure” style=”display:block;” href=”http://releases.flowplayer.org/data/fake_empire.mp3″></div>

!Note: placing it on a div without size makes it invisible but still functional. cool huh!?

Create the flowplayer:

// install flowplayer into container
$f(“audiosecure”, “flowplayer/flowplayer.commercial-3.2.5.swf”, {

// fullscreen button not needed here
plugins: {
controls: {
fullscreen: false,
height: 30,
autoHide: false
}
},
clip: {
autoPlay: false,

// optional: when playback starts close the first audio playback
onBeforeBegin: function() {
$f(“audiosecure”).close();
}
}
});

Our SexyPlayer :

<div id=”sexyPlayer”>
<object width=”360″ height=”45″ wmode=”transparent”>
<param name=”movie” value=”css/assets/player/Action24Player.swf”>
<embed src=”css/assets/player/Action24Player.swf” wmode=”transparent” width=”360″ height=”45″>
</embed>
</object>
</div>

Some CSS:

#audiosecure
{
position:absolute;
left:150px;
top:100px;
}

#sexyPlayer
{
position:absolute;
left:150px;
top:10px;
z-index:9999;
}

!Note: make sure to place the Flowplayer lower than sexyPlayer

Throw in a couple of JS functions and you’re good to go:

function goPlay(){
$f(1).stop();
$f(0).play();
}

function goStop(){
$f(1).stop();
$f(0).stop();
}

Enjoy!

feel free to comment if you found this helpful.

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Simple Draggable Panel Flex 3.5

So I thought to post a simple way to make a draggable panel, actually this can be implemented in every container component. You just create a custom component of the container of your choise and place the following code, then you can simply reference your component (named MovingPanel for example) as:
<local:MovingPanel width=”400″ height=”200″/>

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Panel xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” width=”400″ height=”300″ creationComplete=”initDrag(event)” dropShadowEnabled=”false” alpha=”1.0″ backgroundAlpha=”1.0″ backgroundColor=”#FFFFFF” borderAlpha=”1.0″>
<mx:Script>
<![CDATA[

import flash.events.*;
import flash.filters.*;

var clickX, clickY;
public var f:DropShadowFilter = new DropShadowFilter(5,90,0×000000,.70,9,9);
public var myFilters:Array = new Array();
var dragger;

public function initDrag(e)
{
dragger = this.titleBar;
dragger.addEventListener(MouseEvent.MOUSE_DOWN,beginDraging);
}
public function beginDrag(e)
{
clickX = e.localX;
clickY = e.localY;
myFilters.push(f);
dragger.removeEventListener(MouseEvent.MOUSE_DOWN,beginDraging)
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragIt);
stage.addEventListener(MouseEvent.MOUSE_UP, endDraging);
this.filters = myFilters;

moveToTop();
}

public function dragIt(e)
{
this.x = e.stageX-clickX;
this.y = e.stageY-clickY;
}

public function endDraging(e)
{
this.filters.pop();
this.filters = null;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragIt);
stage.removeEventListener(MouseEvent.MOUSE_UP, endDrag);
dragger.addEventListener(MouseEvent.MOUSE_DOWN,beginDraging);

// super.shadowDistance = 0;
}

function moveToTop(e=null)
{
parentDocument.setChildIndex(this, stage.numChildren);
}

]]>
</mx:Script>

</mx:Panel>

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex Simple Media Player

Creating a simple media player with Flex is not as hard as it sounds. In this tutorial I’ll go over the MXML code and some simple Action Script. In the next part I’ll describe more advanced functions such as repeat and playlist.

//First off with the MXML code:

<mx:Panel id=”mediaPanel” backgroundColor=”#2e2e2e” borderStyle=”solid” borderColor=”#4193DF” borderThickness=”2″
height=”80″ width=”280″ layout=”horizontal” alpha=”1.0″ headerHeight=”0.0″
roundedBottomCorners=”true” doubleClickEnabled=”true”
paddingTop=”10″ paddingBottom=”10″ paddingLeft=”10″ paddingRight=”10″ verticalScrollPolicy=”off” horizontalAlign=”center” top=”180″ x=”10″ dropShadowEnabled=”true”&gt

<mx:Canvas height=”100%” width=”100%” includeInLayout=”true” autoLayout=”true” borderStyle=”none” verticalScrollPolicy=”off”&gt

//some skining here would be usefull and better looking…
<mx:Button id=”stopButton” y=”10″ click=”stopPlaying();” styleName=”Button” x=”150″/&gt

<mx:Button id=”pauseButton” y=”10″ click=”pausePlaying();” styleName=”Button” x=”100″/&gt

<mx:Button id=”playButton” styleName=”Button” enabled=”true” click=”mediaPlay();” x=”50″ y=”10″/&gt

</mx:Canvas&gt

</mx:Panel&gt
//——————————————————

//Now some simple AS code, for the Play-Pause-Stop

import mx.core.SoundAsset;
import flash.media.*;

public var snd:SoundChannel = new SoundChannel();
public var pauseFlag:int=0;
public var pausePosition:int;
public var Sounds:Sound;
public var repSound:Sound;

//If we started playing from the beginning it simply plays the song, or if we paused first it resumes.
private function mediaPlay():void
{
if(pauseFlag==1)
{
resume();
}
else
{
snd.stop();
var mySound:Sound = new Sound(new URLRequest(/assets/mySong.mp3));
Sounds=mySound;
snd = mySound.play();
snd.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler1)
}
}

//To Pause the sound channel we stop it and keep track of the timeline the stopping occured. Then we invoke Play from the exact spot we left off.
private function pausePlaying():void
{
pausePosition = snd.position;
snd.stop();
pauseFlag=1;
snd.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler1)
}

public function resume():void
{
pauseFlag=0;
snd = Sounds.play(pausePosition);
}

//We invoke the sound channel to stop transmitting
private function stopPlaying():void
{
snd.stop();
}

//I’ll get a working example up and running soon, until then Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Create/Edit XML with Flex and PHP (part 1/2)

This project of creating and editing an XML through Flex and PHP took me several days to figure out and gather all the info I wanted, and because there isn’t anything really helpfull out there I decided to make this post so that there is at least one viable piece of code for people to learn on.
So on to the code:

//in this example the structure that we will create is like this and stored in a file named “music.xml”:
//<music&gt
//<newFile&gt
//<id>…</id&gt
//<title>…</title&gt
//<urlID>…</urlID&gt
//<descriptionID>…</descriptionID&gt
//<dateID>…</dateID&gt
//</newFile&gt
//…
//
// have in mind that the initial tag has already been created and we
// add the nodes in there
//we create the http request that will transfer the data to the php file upon call

<mx:HTTPService id=”filePush” showBusyCursor=”true” url=”assets/xmlWriter.php” headers=”null” requestTimeout=”18″ resultFormat=”e4x”
contentType=”application/x-www-form-urlencoded” method=”GET”&gt
<mx:request&gt
<id>{getID()}</id&gt
<title>{titlePush.text}</title&gt
<url>{urlString+titlePush.text}</url&gt
<date>{date_str}</date&gt
<desc>{desc.text}</desc&gt
</mx:request&gt
</mx:HTTPService&gt

//now we throw in some Action script
//to create a unique id for all entries

public function getID():Number
{

var start:Number=Math.round(Math.random()*today_date.getFullYear());
start=(start+(today_date.getMonth()+1)+today_date.getDay())*today_date.getSeconds();
return start;
}

//and for the Date

[Bindable]
public var today_date:Date = new Date();
public var date_str:String = (today_date.getDate()+”/”+(today_date.getMonth()+1)+”/”+today_date.getFullYear());

//==========================================
//and finaly the PHP code, pretty straightforward using SimpleXML:

<?php
$file=”music.xml”;
$xml=simplexml_load_file($file) or die (“Unable to load XML”);
$vitals = $xml->addChild(‘newItemID’);
$vitals->addAttribute(‘id’, $_GET[‘id’]);
$vitals->addChild(‘titleID’, stripcslashes($_GET[‘title’]));
$vitals->addChild(‘urlID’, $_GET[‘urlID’]);
$vitals->addChild(‘dateID’, $_GET[‘date’]);
$vitals->addChild(‘descriptionID’, stripcslashes($_GET[‘desc’]));

$doc = new DOMDocument(‘1.0’);

$doc->preserveWhiteSpace = false;
$doc->loadXML( $xml->asXML());
$doc->formatOutput = true;

file_put_contents( $file, $doc->saveXML());

?&gt

for the editing part wait for my next post which won’t be too late!
Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Communicate with JavaScript, send-receive

Actually its quite simple to communicate with Javascript from Flash, simply by importing the externalInterface library. The following code displays a simple use, from which the Javascript “reads” the available space within the browser window and sends it to the flex application, which draws a panel to match this space, so you can have a full screen application no matter the screen resolution and/or browser…

&lt?xml version=”1.0″ encoding=”utf-8″?&gt

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” viewSourceURL=”srcview/index.html”&gt

<mx:Script&gt
&lt![CDATA[
import mx.controls.Alert;
import mx.events.*;
import mx.controls.*;
import flash.external.*;

public var w:uint;
public var h:uint;
public function callWrapper(event:MouseEvent):void
{

var jsWidth:String = “getWidth”;
var jsHeight:String = “getHeight”;
w = ExternalInterface.call(jsWidth);
h = ExternalInterface.call(jsHeight);
//testPanel.width=w/2;
//testPanel.height=h/2;
Alert.show(w.toString()+”*”+h.toString());
resizeMe.widthTo=w;
resizeMe.heightTo=h;
resizeMe.play();
}

public function original():void
{
resizeMe.widthTo=200;
resizeMe.heightTo=300;
resizeMe.play();
}
]]>
&lt/mx:Script&gt

<mx:Resize id=”resizeMe” target=”{testPanel}”/&gt

<mx:Canvas height=”100%” width=”100%”&gt

<mx:Button label=”Expand!” click=”callWrapper(event);” horizontalCenter=”0″/&gt

<mx:Panel id=”testPanel” width=”200″ height=”300″ backgroundColor=”#BDE018″ y=”0″ x=”0″ borderStyle=”none”&gt
<mx:Button label=”Return” click=”original();”/&gt
&lt/mx:Panel&gt

&lt/mx:Canvas&gt

&lt/mx:Application&gt

add this 2 functions to your html that contains the produced .swf

<script language=”JavaScript” type=”text/javascript”&gt

function getWidth() { return document.body.clientWidth; }
function getHeight() { return document.body.clientHeight; }

View working example here

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Applying an effect to a popup in Flex (open,close)

This is an effect I made to make popups appear and disappear in a cooler way…

u can view an example here right click for source code…

also posting the code here just in case…

the mxml code for the main application:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” viewSourceURL=”srcview/index.html” backgroundColor=”0xffffff”>

<mx:Script>
<![CDATA[
import mx.effects.easing.*;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

private function launchDiag1():void
{
var win:diagBox = PopUpManager.createPopUp(this, diagBox, true) as diagBox;
PopUpManager.centerPopUp(win);
}
]]>
</mx:Script>

<mx:Canvas height=”100%” width=”100%”>

<mx:Button click=”launchDiag1()” label=”Play!” verticalCenter=”0″ left=”50″ height=”80″ width=”100″/>

</mx:Canvas>
</mx:Application>

//=================================================

Now the popup code: ( create a new mxml component first, and name it diagBox)

<?xml version=”1.0″ encoding=”utf-8″?>
<!– diagBox.mxml –>

<mx:TitleWindow xmlns:mx=”http://www.adobe.com/2006/mxml”
layout=”vertical”
showCloseButton=”true”
width=”550″
height=”500″
close=”titleWindow_close();” backgroundAlpha=”0.0″ borderAlpha=”0.0″ creationComplete=”openingEffect.play();”
shadowDirection=”center” shadowDistance=”0″ borderStyle=”none”>

<mx:Script>
<![CDATA[
import mx.events.EffectEvent;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
import mx.effects.easing.*;

private function titleWindow_close():void {
shutdownEffect.play();

}

public function endDiag():void
{
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>

<mx:Style>
.header
{
color:#ffffff;
}
</mx:Style>

<mx:Sequence id=”openingEffect” target=”{panel}” effectStart=”panel.visible=true”>
<mx:Pause duration=”400″/>
<mx:Resize id=”expand” widthTo=”500″ duration=”300″ easingFunction=”Circular.easeOut”/>
<mx:Pause duration=”300″/>
<mx:Resize id=”expand2″ heightTo=”450″ duration=”300″ easingFunction=”Circular.easeInOut”/>
</mx:Sequence>

<mx:Sequence effectEnd=”endDiag();” id=”shutdownEffect” target=”{panel}” suspendBackgroundProcessing=”true”>
<mx:Pause duration=”400″/>
<mx:Resize id=”contract2″ heightTo=”1″ duration=”300″ easingFunction=”Circular.easeInOut” suspendBackgroundProcessing=”true”/>
<mx:Pause duration=”300″ suspendBackgroundProcessing=”true”/>
<mx:Resize id=”contract” widthTo=”1″ duration=”300″ suspendBackgroundProcessing=”true” easingFunction=”Circular.easeOut”/>
</mx:Sequence>

<mx:Canvas height=”100%” width=”100%”>

<mx:Panel id=”panel” visible=”false” height=”1″ width=”1″ borderColor=”#000000″ horizontalCenter=”0″ verticalCenter=”0″
title=”Early Years…” themeColor=”#ffffff” autoLayout=”true” titleStyleName=”header”>

<mx:Text id=”info” text=”Sample Text containing the phrase: Hello World! “/>

</mx:Panel>
</mx:Canvas>

</mx:TitleWindow>

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin