Archive for the 'Tips & Tricks' Category

01
Sep

Convert ByteArray into an image and NetStream limitation

Flash Player 10 and AIR allow loading files from your local system as well as saving files. Once the files are loaded you have access to the ByteArray.

Convert ByteArray into an image

You can easily convert the ByteArray into an image:


var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void
{
      event.currentTarget.removeEventListener(event.type, arguments.callee);
      image.source=loader.content;
});

loader.loadBytes(event.file.fileContent);

Play ByteArray

Unfortunately, you cannot set the bytes of a video stream through the NetStream Object. What you can do is write the URLStream’s bytes to a local file, and then pass that file to the NetStream object. You can do a workaround such as writing out the URLStream’s bytes as they come in with the help of the “append” method.

What it means is that you cannot play ByteArray in AIR or Flex Application. I know that that feature is on the Adobe’s team list but until they adjust the code you will have to find a workaround.

01
Sep

Tips & Tricks: Mixing Halo and Spark components

Mixing Halo and Spark components is still not working perfectly and causing all sort of problems, but in case you need to do inline rendering using Halo component, it’s possible. This is how you would do it for a Spark list component:


	<s:List id="output">
		<s:itemRenderer>
			<fx:Component>
				<mx:HBox>
					<mx:Image source="{data.thumbnail}" height="50" width="50" />
					<mx:Label text="{data.label}" width="300" height="20" />
				</mx:HBox>
			</fx:Component>
		</s:itemRenderer>
	</s:List>
20
Jul

Under the hood Flex data model using the fx:Model and fx:XML tags

When creating data model there are two popular ways to create data model in addition to VO / DTO. You can use the fx:Model and the fx:XML tags. These tags are mxmlc compiler tag. What it means is that the compiler handles these tags differently than the regular tags in MXML. In case you are like me and like to dig deep into how the mxmlc works than keep reading… In the Model or XML tags the source property can be set to an external source, however the compiler retrieve the information and set it as an ObjectProxy, which allow the object to be bindable, additionally it does direct assignment so there is no service call to retrieve the data as you may expect from an MXML tag. Consider the code below:


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/halo"
			   minWidth="1024" minHeight="768"
                           creationComplete="creationCompleteHandler(event)">
	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;

			protected function creationCompleteHandler(event:FlexEvent):void
			{
				trace("infoVO full name property: "+this.infoVO.fullName);
				trace("info2VO full name property: "+this.info2VO.fullName);
			}

		]]>
	</fx:Script>

	<fx:Declarations>

		<fx:Model id="infoVO">
			<root>
				<fullName>John Doe</fullName>
				<email>john@gmail.com</email>
				<phone>212-222-2222</phone>
				<zip>10001</zip>
			</root>
		</fx:Model>

		<fx:Model id="info2VO" source="Info.xml" />

	</fx:Declarations>

</s:Application>

We have two Model tags in the code and although one tag calls an xml using the source property and another one does direct assignment the mxmlc compile will generate the same code for both of these tags.

Take a look at what the compiler does when you use set infoVO and info2VO with the source property:


private function _DataModel_ObjectProxy2_i() : mx.utils.ObjectProxy
{
	var temp : mx.utils.ObjectProxy = new mx.utils.ObjectProxy();
	temp.fullName = "John Doe";
	temp.email = "john@gmail.com";
	temp.phone = "212-222-2222";
	temp.zip = 10001;
	info2VO = temp;
	return temp;
}

private function _DataModel_ObjectProxy1_i() : mx.utils.ObjectProxy
{
	var temp : mx.utils.ObjectProxy = new mx.utils.ObjectProxy();
	temp.fullName = "John Doe";
	temp.email = "john@gmail.com";
	temp.phone = "212-222-2222";
	temp.zip = 10001;
	infoVO = temp;
	return temp;
}

And here’s what the mxmlc code generated to create the binding tag:


    [Bindable(event="propertyChange")]
    public function get info2VO():mx.utils.ObjectProxy
    {
        return this._1945369341info2VO;
    }

    public function set info2VO(value:mx.utils.ObjectProxy):void
    {
    	var oldValue:Object = this._1945369341info2VO;
        if (oldValue !== value)
        {
            this._1945369341info2VO = value;
            this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "info2VO", oldValue, value));
        }
    }

	/**
	 * generated bindable wrapper for property infoVO (public)
	 * - generated setter
	 * - generated getter
	 * - original public var 'infoVO' moved to '_1184171033infoVO'
	 */

    [Bindable(event="propertyChange")]
    public function get infoVO():mx.utils.ObjectProxy
    {
        return this._1184171033infoVO;
    }

    public function set infoVO(value:mx.utils.ObjectProxy):void
    {
    	var oldValue:Object = this._1184171033infoVO;
        if (oldValue !== value)
        {
            this._1184171033infoVO = value;
            this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "infoVO", oldValue, value));
        }
    }

Since the mxmlc compiler create an ObjectProxy component it allows us to bind these properties as in the example below:


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/halo"
			   minWidth="1024" minHeight="768">

	<s:layout>
		<s:BasicLayout/>
	</s:layout>

	<fx:Declarations>
		<fx:Model id="infoVO">
			<root>
				<fullName>{fullNameTextInput.text}</fullName>
				<email>{emailTextInput.text}</email>
				<phone>{phoneTextInput.text}</phone>
				<zip>{zipTextInput.text}</zip>
			</root>
		</fx:Model>
	</fx:Declarations>	

	<mx:DataGrid x="11" y="164" id="dataGrid"
				 dataProvider="{infoVO}">
		<mx:columns>
			<mx:DataGridColumn
				headerText="fullName"
				dataField="fullName"/>
			<mx:DataGridColumn
				headerText="email"
				dataField="email"/>
			<mx:DataGridColumn
				headerText="phone"
				dataField="phone"/>
			<mx:DataGridColumn
				headerText="zip"
				dataField="zip"/>
		</mx:columns>
	</mx:DataGrid>

	<mx:Form>
		<mx:FormItem label="FullName">
			<s:TextInput
				id="fullNameTextInput"/>
		</mx:FormItem>
		<mx:FormItem label="Email">
			<s:TextInput
				id="emailTextInput"/>
		</mx:FormItem>
		<mx:FormItem label="Phone">
			<s:TextInput
				id="phoneTextInput"/>
		</mx:FormItem>
		<mx:FormItem label="Zip">
			<s:TextInput
				id="zipTextInput"/>
		</mx:FormItem>
	</mx:Form>
</s:Application>

Here’s a screen shot of the application:
Flex Data Model

It valuable to understand how the mxmlc works and use these tags when needed.

26
Jun

CSS Tip: align FormItem label property to the left

Here’s a quick little tip. In case you are trying to align a form label to the left and can’t get it to align, you will find that textAlign left which should work according to the LiveDoc doesn’t work on all Flex SDK versions. Apparently this is a known bug in Adobe’s JIRA system:
http://bugs.adobe.com/jira/browse/SDK-12776.

Adobe SDK team added a new property to the FormItem component called: labelStyleName.

Here’s the solution. Create a style sheet and use text-align: left.


	<fx:Style>
        .formItemLabelLeft {
            text-align: left;
        }
	</fx:Style>

Next, attach the CSS to the labelStyleName property.


	<mx:Form>
		<mx:FormItem label="Label Name:" width="148" labelStyleName="formItemLabelLeft">
		<mx:ComboBox editable="true" width="79"></mx:ComboBox>
	</mx:FormItem>

This was tested in Flex 4 beta SDK.

28
Mar

Finally… Flex Builder shortcut cheat sheet for Mac OS

I was looking for a quick reference or cheat sheet card to print that includes all the shortcuts that are available for Mac OS and although I found many for PC there is nothing for Mac, so I created one myself.

All the available shortcuts are split into different categories and include the most useful shortcuts that exist. The complete list of the entire shortcut list is available using the key assist (Command+Shift+L).

You can download a one page PDF version from here and print to place it next to your desk or keep this page on your bookmark for future reference. In case I forget any important ones please feel free to drop a line.

Category

Type

Shortcut

Comments

Add Comments

Shift+Command+D

 

Comment Selected Code

Command+/

History

Backward History

Command+[

 

Forward History

Command+]

File

Build All

Command+B

 

Save

Command + S

 

Close

Command+W

 

Close All

Command+Shift+W

 

New Menu

Option + Command + N

 

New File

Command + N

 

Compile and Run

Shift + Command + F11

Edit text

Copy

Command+C

 

Copy Selected Lines Above

Option+Command+ Up Arrow

 

Copy Selected Lines Below

Option+Command+ Down Arrow

 

Paste

Command + V

 

Cut

Command+X

 

Delete

Delete

 

Delete Line

Command+Delete

 

Delete Next Word

Option+Small Delete

 

Delete Previous Word

Option+Large Delete

 

Delete to the end of the line

Shift+Command+Small delete

 

Redo

Command + Y

 

Insert line above

Command + Shift + Enter

 

Move selected lines Up

Option + Up Arrow

 

Move selected lines down

Option + Down Arrow

 

Duplicate lines

Command + Option + Arrow down

 

Optimize imports

Command + Shift + O

 

Select all

Command + A

 

Select Line end

Shift + Command + right arrow

 

Select Next word

Shift + Command + right arrow

 

Select Previous word

Shift + Command + left arrow

 

Select Text End

Shift + Page down

 

Select Text Start

Shift + Page up

 

Select everything to the left

Command + Shift + left arrow

 

Select everything to the right

Command + Shift + right arrow

 

Last edit location

Control + Q

 

To Lower case

Shift + Command + Y

 

To Upper case

Shift + Command + X

 

Toggle block comment

Shift + Command + C

 

Toggle breakpoint

Shift + Command + B

 

Word completion

Control + Space

 

Undo

Control + Z

Search/Find

Find all declaration – select expression first.

Command + G

 

Find all References in Workspace – select expression first.

Shift + Command + G

 

Find next – select expression first

Command + K

 

Find Previous

Shift + Command + K

 

Find Text in Workspace

Option + Command + G

 

Find and Replace

Command + F

 

File Search

Command + Shift + F

 

Goto definition – Step into

F3 or Command + Enter

 

Go to Line number

Command + L

 

Go to matching bracket

Command + Shift + P

 

Line end

Command + Right arrow

 

Line start

Command + Left arrow

 

Open resource

Command + Shift + R

 

Open class types window

Command + Shift + T

 

Previous/Next word

Option + right arrow/left arrow

Views/Editors

Maximize view

Command + M

 

Next Editor

Command + F6

 

Previous Editor

Shift + Command + F6

 

Next Prospective

Command + F8

 

Previous Prospective

Shift + Command + F8

 

Previous View

Shift + Command + F7

 

Next View

Command + F7

 

Dynamic Help

Command + Shift + ?

 

Properties

Option + Enter

 

Quick access

Command + 3

 

Quick Switch Editor

Command + E

 

Refresh

F5

 

Show Key assist

Command + Shift + L

 

Ruler Context Menu

Command + F10

 

Show system menu

Shift + Command + F10

 

Switch to Editor

Shift + Command + E

28
Feb

Flash Catalyst DesignLayer tag pitfall tip

I am using Flash Catalyst for few projects now and I have to say that Flash Catalyst rocks!

I am able to convert vector images right into Flex Gumbo and no need to chop designers images any more. Keep in mind that Flash Catalyst is still in Alpha version so I don’t have the luxury to use it on all projects since it requires Flash 10.

Flash Catalyst allows you to import your art work from Adobe Illustrator and the graphic get converted to FXG, however if you try to compile and run your project you sometimes get a blank screen.. don’t get alarmed..

Flash Catalyst bring back all your layers from Flash Illustrator CS4, however it creates a tag around your layer, which cause Flex to ignore the entire block of code. The solution is simple. Remove the tags and you are all set.

Here’s an example of tags generated for a layer imported from Illustrator:


<DesignLayer d:id="2" userLabel="Layer1">
    // FXG code
</DesignLayer>

This little tip can save you about 15-30 valuable development time.

21
Feb

Ant task to generate SWC and ASDOC

Ant task to generate SWC and ASDOC for a library.

First create a property file to store location of your sdk and other information regarding your application: asdoc.properties - set properties file;


###################################################################
# Author: Elad Elrom - creates ASDOC and SWC
###################################################################
# Location of sdks directories
sdk.home 	 = /Users/user/Applications/Adobe\ Flex\ Builder\ 3\ Plug-in/sdks
# Location of sdk version
sdk.dir      = ${sdk.home}/3.2.0
# Location of asdoc.exe
asdoc.exe    = ${sdk.dir}/bin/asdoc
# ASDOC information
src.dir      = /Users/user/Documents/workspace/Library
doc.dir		 = /Users/user/Documents/workspace/Library
doc.src		 = ${doc.dir}/src/com/elad/API
output.dir   = ${doc.dir}/asdoc
# Libpath location to be included
libpath		 = ${doc.dir}/libs
# file name and folder
swc.dir		 = /Users/user/Documents/workspace/Library/swc
swcfilename	 = library.swc
FLEX_HOME	 = ${sdk.dir}
# ASDOC title for html pages
main.title   = ASDOC Title
window.title = ASDOC Title
</p>

Next, create the ant task to generate the asdoc and SWC file. Notice that I placed the flexTasks.jar in my local library, but feel free to point to it directly.


<project name="ASDoc build" default="main" >
	<!-- make sure that flexTasks.jar which is located in skd/ant/lib/flexTasks.jar otherwise you'll get an error message -->
	<taskdef resource="flexTasks.tasks" classpath="libs/flexTasks.jar" />
	<!-- defines all values for the ASDoc compiler -->
<property file="asdoc.properties" />
    <!-- main target: cleans and compiles ASDocs -->
    <target name="main" depends="clean-asdoc-directory, create-docs, clean-swc-directory, swc-generator" />
    <!-- deletes and recreates the asdoc directory -->
    <target name="clean-asdoc-directory" >
       <delete dir="${output.dir}" />
       <mkdir  dir="${output.dir}" />
    </target>
    <!-- deletes and recreates the swc directory -->
    <target name="clean-swc-directory" >
       <delete dir="${swc.dir}" />
       <mkdir  dir="${swc.dir}" />
    </target>
    <!-- runs the asdoc.exe compiler on the source -->
    <target name="create-docs" >
        <exec executable="${asdoc.exe}" failonerror="true" >
        	<arg line="-external-library-path='${libpath}/'" />
            <arg line="-doc-sources ${doc.src}" />
            <arg line="-output ${output.dir}" />
        </exec>
    	<echo>ASDOC created successfully</echo>
    </target>
	 <!-- generate the swc -->
	<target name="swc-generator" description="Compile the SWC file">
		<compc output="${swc.dir}/${swcfilename}">
			<include-libraries file="${libpath}/" />
			<!-- include our Class packages into the build (com folder) -->
			<include-sources dir="${doc.dir}/src/com" includes="*" />
		</compc>
		<echo>SWC created successfully</echo>
	</target>
</project>
</p>
17
Feb

Passing FlashVars using Flex template html

Adobe Livedoc (see here) indicates that you can pass flashvars in different ways through the URL or the flashvar object. I am using Flash Player 10 on Mozilla browser and it seems that the current player doesn’t work as explained.

It seems that there is only one way to pass the flash vars when using the template page that Flex builder 3.0 generates. You need to set it in the src under the javascript tag:


AC_FL_RunContent(
			"src", "${swf}?myName=Elad",
			"width", "${width}",
			"height", "${height}",
			"align", "middle",
			"id", "${application}",
			"quality", "high",
			"bgcolor", "${bgcolor}",
			"name", "${application}",
			"allowScriptAccess","sameDomain",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
	);

You can then easily read it in your Flex application:


var myName:String = mx.core.Application.application.parameters.myName;

I tested all the other options and nothing else seems to work. I also notices some other posts talking about the same issue, such as here:
http://flexblog.faratasystems.com/?m=200610

This issue may be related to the way the swf is deployed, in any case, I couldn’t get the examples from the livedoc to work. Remember to make the changes in the html-template folder so it will generate your template automatically every time you clean your project.

If anyone have more information, feel free to post it here.

16
Feb

Declaration tag in Flex Gumbo

Flex Gumbo have added a new tag called declaration. The new tag has to be used in cases where you want to reference a component that is not part of the mx.core or classes that are not display objects.

For instance, when creating Cairngorm projects you need to set references in the entry point to your controller, services and view such as the following code:


	<view:MainApp />
	<control:Controller />
	<business:Services />

However, in Flex Gumbo classes that are not display objects needs to be placed in a a declarations tag. Change your code easily by placing your classes to the declaration tag as follow;


	<view:MainApp />
	<Declarations>
		<control:Controller />
		<business:Services />
	</Declarations>

Otherwise you will get the following runtime error message.


TypeError: Error #1034: Type Coercion failed: cannot convert com.domain.project.control::Controller@21cf9d61 to flash.display.DisplayObject.
	at mx.components::Group/itemAdded()[E:\dev\gumbo_alpha\frameworks\projects\flex4\src\mx\components\Group.as:752]
	at mx.components::Group/initializeChildrenArray()[E:\dev\gumbo_alpha\frameworks\projects\flex4\src\mx\components\Group.as:251]
	at mx.components::Group/commitProperties()[E:\dev\gumbo_alpha\frameworks\projects\flex4\src\mx\components\Group.as:267]
	at mx.core::UIComponent/validateProperties()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\core\UIComponent.as:6130]
	at mx.managers::LayoutManager/validateProperties()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\managers\LayoutManager.as:539]
	at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\managers\LayoutManager.as:659]
	at Function/http://adobe.com/AS3/2006/builtin::apply()
	at mx.core::UIComponent/callLaterDispatcher2()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\core\UIComponent.as:8849]
	at mx.core::UIComponent/callLaterDispatcher()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\core\UIComponent.as:8789]

Notice that I haven’t placed my view in the declaration tag, since my view is a Canvas component, which extends Container. So what?

Component that doesn’t implements the mx.core namespace has to go into the declaration tag, including all the Fx components, however Canvas extends Container which is part of mx.core so no need to place it in the declaration tag.

By the way, you may have the same issue with PureMVC projects. The view reference in your entry point may need to be placed in the declaration tag, as explained above.

27
Jan

Tips - Debugging Flex applications with flashlog.txt on a Mac

Debugging Flex applications with mm.cfg and flashlog.txt let us track trace statements and error messages for projects running in the browser using the debug mode. Since I haven’t done it since 2001 I completely forget what to do and came across couple of issues, so I figured I’ll throw a post for other people that may have the same issue.

You first need to create the txt file and directories here:
/Users/YourUserName/Library/Preferences/Macromedia/Flash\ Player/Logs/flashlog.txt

Then you need to create the mm.cfg file in both location:
/Library/Application Support/Macromedia/mm.cfg
/Users/YourUserName/mm.cfg

Then paste the follwing code in the mm.cfg:
ErrorReportingEnable=1
TraceOutputFileEnable=1
MaxWarnings=0

Initially, I pasted the code only in the first directory and couldn’t get it to work, not sure why, so place the file in both directories to play it safe.
I am running the Flash Debug Player 10, on Mac OS X.

To see the messages as they come on Terminal, navigate to the flashlog directory and type in:
tail -f flashlog.txt

I Hope you find this tip handy.