Archive for the 'Flex' Category

Dec 12 2008

Audiolife.com Flash Widget

Published by under Flex,Work Examples


Finally one of my big freelance projects has seen the light of the day. Audiolife.com has been launched as beta and the reviews are positive. There is a lot more work in the pipeline with this widget, have to make it customizable so that the user can change the look and feel of it as well as the size. Exciting times…. 

 

This is the widget i created for them, 

 

This Flex widget uses Cairngorm Framework to communicate with the webservices.

 

4 responses so far

Oct 16 2008

Using Flex Builder and Flash together…

Published by under AS 3.0,Flex

Anyone who has written code using Flex Builder Plugin for Eclipse or just the Flex Builder by itself will agree with me completely that writing code using Flash IDE is not fun anymore. 

 

So when i had to write something in pure AS3 i decided to use FB for writing all the classes and Flash only for compiling the FLA. It is a bit of hassle but the efficient provided by FB far exceeds that hassle. Also in my case the project is integration of Flex and Flash, the pure AS3 swf is going to be loaded into a Flex project so i have to launch the project through FB. 

 

Some tips/suggestions from my experience of using this methodology,

  • For debugging the code in FB you have to select permit debugging check box in the Fla options.
I always run my projects in debug mode, it helps me to see what exceptions are being thrown if any and i love to use break points to debug the code. It has made my life lot easier. So for that flash only swf to connect to flex debugger we need to check this option otherwise it won’t work.
  • Some of the advantage of using FB is lost because the child instances of movieclips have to be declared as movieclips even if they have some class attached to it.
Let me explain this further, lets say in your AS3 document class you have a movieclip with instance name sample which has a class Sample.as attached to it. 

 

 

public var sample:Movieclip; this is how you would declare it or this is another way 

public var sample:Sample; Flash doesn’t like this declaration and it freaked out on me. 

you won’t get any compile errors but when you run the movie it won’t be as you expected. So because of this it has to be a movieclip and therefore the FB autocompletion is not much of use there.

  • Major annoyance is that every time you change the code and have to test out the swf, you have to compile it and then copy paste is into the bin-debug folder of your flex project. Cleaning the project takes long time.
Because of the earlier problem, FB doesn’t compile any classes which are assigned to the movieclips and there any errors are discovered only when you compile the fla. After compilation of the swf, you have to copy it in the bin-debug folder so that the most recent changes are reflected when you run the project.
So far it has been the above things, if i encounter something new then i will add to this post.

No responses yet

Oct 01 2008

Using ChangeWatcher

Published by under Flex


Data binding is one of the best things about Flex, frameworks like Cairngorm rely heavily on data binding. But what if you want to detect a change in variable value and then also do something else. Changewatcher comes in handy during times like those.

 

import mx.binding.utils.ChangeWatcher;

 

This is the class i am talking about, it lets you listen for changes in a variable. Lets say we have a class variable totalItems and we need to detect changes to that variable. This is a simple class.

 

package {

    class Model {
        //i shall leave the constructor to you

        [Bindable]
        public var totalItems:Number;

    }
}

Now to detect changes to this variable, the code would look something like,

import mx.binding.utils.ChangeWatcher;

public var watcherInstance:ChangeWatcher;

[Bindable]
public var model:Model;

public function init():void{

//this is useful if you want to unwatch or stop detecting changes to this variable
//ofcourse init function has to be called
model = new Model();
watcherInstance = ChangeWatcher.watch(model,["totalItems"],itemsChanged);

}

public function itemsChanged(event:PropertyChangeEvent):void{
//this function is called as soon as value of totalItem changes.
//if you want to stop watching this variable.
watcherInstance.unwatch();
}

So you can see that this is very easy way of detecting changes, the only thing to keep in mind is that the variables being watched have to be Bindable. You can also detect changes within chain of classes.

 

For Eg. ChangeWatcher.watch(model,[“shoppingCart”,”totalItems”],itemsChanged); the variable totalItems is inside the class ShoppingCart which is initialized in Model. So your chain of variables can be as long as you want.

 

Other Important thing to note is that the line code after the variable will be executed only after your listener function is called. Its not asynchronous like URLLoader etc.

 

EDIT: 02/20/09 Imp Note:

If you are tracking changes to a number, your changewatcher function will fire only if the number changes. Lets say your variable totalItems is 1 and after performing some calculation its again 1, in this situation your changewatcher won’t fire because the value of variable hasn’t changed. It can cause crazy bugs in your application and i have been bitten by this couple of times now. 

 

The example below shows how you can watch a chain and also how every variable has to be bindable etc.

Click here for the source.

 

 

8 responses so far

Sep 05 2008

Using Mapping Services with Flex

Published by under AS 3.0,Flex

For a project i decided to try out the Flex libraries for both Yahoo maps and Google maps as well and they both seem to be pretty cool.

http://developer.yahoo.com/flash/maps/ and http://code.google.com/apis/maps/documentation/flash/

 

After working with examples of both the API’s it was not that difficult to find out which had better features.Lets consider the Visual Aspects first,

 

Speed

When you change the map types, Google emerges the clear winner. you can see it for yourself how fast the maps load. 

 

Zooming

When you zoom in and out, yahoo loads one tile at a time and its not pretty specially while zooming in. Google maps just scales the original image and then when the tiles load it fades out. It could have been better implemented by just waiting for all the tiles to load but they choose not to. Its not 100% clean but still better than yahoo.

 

Dragging

When you drag the map at any level, google maps keeps on repeating the images where as yahoo map just shows one image.It doesn’t matter much but i think its a nice feature to have. 

 

So visually Google is winner but for a Flash developer, Yahoo maps have a lot more to offer.

 

Geocoding

When you geocode something, both work well but the results returned by yahoo provide a lot more information. You can get the state and country information from the city name etc. It is awesome feature which google maps lack and hence for our application we are using yahoo maps.

 

Edit: If you look at the comments, I have been corrected that google does indeed have geocoding features, but i am sorry to say that as of 9th September 2008 the geocoding could use some work. See examples.

 

Search and Traffic

Yahoo maps allows you to get the traffic situation and also perform local search and then display the results on the map. Google map has no such features. 

 

Overlays

Google maps has polygon overlay which yahoo map lacks but then it seems easy to draw everything in yahoo maps using the Flash drawing API’s. 

 

I haven’t looked into changing the look and feel of the buttons etc but it seems to me that both the api’s allow the same. Samples and examples can be found for both, I will be putting one with yahoo maps soon.

 

Examples:

For our application I just wanted the map to move as the region were selected by the city, state and country data. you can check it out here, 

 

Yahoo Maps: Application Source

 

Google Maps: Application Source

 

Please Note: I am using amfphp to get the countries, states (US) and cities data. Also i have edited the keys in the source.

 

If you have both examples open, try to select the country yugoslavia and then see the results. At this point i stopped working on google maps example because it returned everything with yugoslavia. It can be a good thing or a bad thing depending on your application, for me it was bad thing. 

 

So Yahoo which returns me the country works for me, I am using standard city, state and country format to get the geocode results. Yahoo seems to be giving priority in that order.

 

2 responses so far

Aug 21 2008

Getting Shipping Rates from USPS

Published by under Flex

I have been working on a Flash/Flex shopping cart which uses AMFPHP to connect with OSCommerce and you can manage your cart using OScommerce. 

 

The client wanted to get shipping prices based on the weight and it had to be USPS. It turned out to be a really easy integration, I have used Flex but it would be the same using Flash as well. 

 

The only problem is when you hit the testing server of USPS they expect the xml to be exactly the same as they specify in the examples and also Rate3 API’s don’t work well. Shown below is the simple Flex code to get response from the testing server,

 

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”sendService()”>

    <mx:Script>

        <![CDATA[

            import mx.controls.Alert;

            private function errorMsg(info:Object):void{

                var data:Object = info;

            }

            private function gotBack(event:Object):void{

                var data:Object = event;

                mx.controls.Alert.show(event.result.Error.Description);

            }

            private function sendService():void{

                var xmlData:String = ‘<RateV2Request USERID=”xxxxxx”><Package                                                                         ID=”0″><Service>PRIORITY</Service>’ + 

                     ‘<ZipOrigination>10022</ZipOrigination><ZipDestination>20008</ZipDestination>’                                     + ‘<Pounds>10</Pounds><Ounces>5</Ounces><Container>Flat Rate Box</Container><Size>REGULAR</Size></Package></RateV2Request>’;

                var requestObj:Object = new Object();

                requestObj.XML = new XML(xmlData).toXMLString();

                requestObj.API = “RateV2”;

                upsService.request = requestObj;

                upsService.send();

            }

]]>

</mx:Script>

<mx:HTTPService id=”upsService” url=”http://testing.shippingapis.com/ShippingAPITest.dll” result=”gotBack(event)”

  fault=”errorMsg(event)” resultFormat=”e4x” />

</mx:Application>

 

As you can see there is not much to it, you just have to use a simple httpservice and the parameters required is the XML and the API. You can request upto 25 rates and the details can be found on the usps site out here.

 

USPS will return an XML even if there is an error and for production you have to move to a different server but the basic things still remain the same. Now only if they would have a crossdomain.xml on their servers, have put in a request for that but i doubt they would be willing to have it. *sigh*

One response so far

Aug 08 2008

Understanding Scale 9 grid for Flex

Published by under Flex

This article is for my reference as well because i always confused what co-ordinates i should use to specify the scale 9 grid i.e, upSkin: Embed(source=”../assets/graphics/combobox/ComboBox_upSkin.png”, scaleGridTop=”7″, scaleGridBottom=”10″, scaleGridLeft=”7″, scaleGridRight=”106″);

I use the above skinning method a lot and hence need to completely understand how to specify the co-ordinates to scale the graphic to any extent.

 

If this all doesn’t make sense then i would ask you to read this article, it is awesome article but i was totally confused on how to find the correct co-ordinates for scaling. 

 

Finally after lot of trials and errors i managed to get it right and understand it. I am going to show exactly how i calculate it. Take a look at the following picture,

 

I am selecting the same fancy_border.png from the Adobe site and i am trying to find a rectangular region in the center which if scaled is not going to affect my image. This region begins at 53,54 and is 215×82.

 

So now i need to assign my scaleGridTop, scaleGridBottom, scaleGridLeft and scaleGridRight from the above information,

 

scaleGridTop is the y position of this rectangle i.e. scaleGridTop=54

scaleGridBottom is the y position of this rectangle plus its height i.e scaleGridBottom=54+82

scaleGridLeft is the x position of this rectangle i.e scaleGridLeft=53 and finally

scaleGridRight is the x position of this rectangle plus its width i.e scaleGridRight=53+215

 

so for the above image embed tag would like,

  [Embed(source=”../assets/fancy_border.png”,
scaleGridTop=”54″, scaleGridBottom=”136″,
scaleGridLeft=”53″, scaleGridRight=”268″
)]

 

Flex scales this rectangular region when it scales the image, so your rectangle should be selected such that any distortion to this region won’t affect your original image. Also this rectangle will determine how much smaller your image can get without distortion, if you select a small rectangular region then you won’t be able to downsize your image.

 

Hope this article makes the scale nine implementation in Flex more clear. Here is a swf file for you all to play with it applies two different scale nine grids to the same image and you will see the difference how it affects the downsizing of the image. 

EDIT: 01/15/09

Using 0 in the scaleGridTop doesn’t work, you have to use 1. I don’t know but it seems to be the case.
 

Click here for the source.

 

 

10 responses so far

Jul 30 2008

Using Flex Builder 3 to compile Flex 4 applications

Published by under Flex

Flex 4 SDK is available for download now, even though it will be a lot buggy i suppose, nevertheless i decided to play with it and try it out. Flex 4 applications work with Flash Player 10 only and I didn’t want to install it since it can’t co-exist with other FP versions. Also i love FB eclipse plugin and wanted to write Flex 4 code using that. Here is how i achieved my goal, 

 

PS: I am assuming that you are fairly familiar with Flex Builder or the Eclipse FB Plugin

 

Downloading the Flex SDK:

They have started releasing nightly builds of Flex SDK and i downloaded the latest one. Get it.

It doesn’t matter where you save the file. Once you download the file, go to your Eclipse Preferences and then in Flex Settings, select add this SDK. I keep Flex 3 as my default SDK and then we will choose this SDK specifically for Flex 4 projects.

 

Setting up a Project:

Create a standard Flex project as you would normally do in FB. Lets not worry about the main application file for now, first we need to change some settings for our project.

 

Right Click the Project and then select its properties. Go to Flex Compiler option and Select use a specific SDK. 

Choose Flex 4. Also I select the wrapper to have required player version to 10.0.0 even though i will be running swf directly. For my browsers the FP version is still 9.0.115.

I use the following sample code, it is taken from Adobe site,

 

 

<?xml version=”1.0″ encoding=”utf-8″?>

<Application xmlns=”http://ns.adobe.com/mxml/2009

             xmlns:mx=”library:adobe/flex/halo

             layout=”flex.layout.VerticalLayout” backgroundColor=”white

             width=”800” height=”600” xmlns:ns=”library:adobe/flex/gumbo” xmlns:skin=”flex.skin.*>

    <Ellipse width=”10” height=”10” y=”3>

        <fill>

            <mx:RadialGradient>

                <mx:GradientEntry color=”0xAAAAAA/>

                <mx:GradientEntry color=”0x336699/>

            </mx:RadialGradient>

        </fill>

    </Ellipse>

    <mx:Button label=”halo button/>

    <Button label=”gumbo button/>

</Application>

 

 

Note: This is all you have to do if you already have FP 10 installed. 

 

Since i don’t have FP 10, I just have to do a minor modification. FP 10 also comes bundled with your Flex SDK, if you look into flex_sdk_4/runtimes/player/mac, there should be a zip file. I have associated all the swf files with this app. So whenever i click on swf, it opens up with this version of Flash Player. 

 

We can do that change in our project by selecting the Run/Debug Settings for the project and then clicking the edit button.

if everything goes well the next time when you run this project, it will run in FP 10 application and you are all set for writing Flex 4 applications.

No responses yet

Jul 23 2008

Reducing Main Application file size in Flex

Published by under AS 3.0,Flex

I know you might have come across the usual posts for reductions of file size of a Flex swf. Some of them are listed below incase if you don’t already know about it.

  • Use the optimize parameter for the compiler.
  • Don’t embed images, load them during runtime.
  • Use only classes which are required, import only single class instead of the complete package.
  • try using modules instead of developing one single application.
There is one more thing which is really useful if you are looking to  and i haven’t it being discussed that much.
 
Convert your CSS files into SWF files and then load during runtime.
 
When you use stylesheets to customize your Flex application, we usually import it in the mxml using the <style> tag. I would recommend using StyleManager class to load the styles swf file during pre initialization of your application.
 

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” width=”1024″ height=”768″ preinitialize=”applyCSS()”>
 

applyCSS would look something like this,

private function applyCSS():void{
StyleManager.loadStyleDeclarations("styles/mystyles.swf")
}

 

To convert your CSS into SWF in Flex Builder simply right click on it and then select convert to swf file. 

Overall ofcourse your will be still loading in that styles swf file, so the bandwidth usage will remain the same but the initial load time will be less. 

 

You might argue that it will be the same wait time for user to interact with the application but atleast the initial preloader will be on screen for less amount of time. 

 

Also depending on your application you can break it into multiple stylesheet documents and then load the required styles when a particular module loads thereby getting a lot of leverage from this technique. Hope this helps :)

One response so far

Jul 21 2008

References and how they work in Actionscript

Published by under Flash,Flex

This tutorial/article is mainly for newbies/intermediate programmers. Someone who is writing Actionscript code without coming from C or Java background will benefit from this. 

A quick test to find if this article is for you, without executing this piece of code can you predict what will be the trace statement will output,

function referenceTest():void {
var mainArray:Array = new Array("1","2","3","4");
var tempArray:Array = mainArray;

tempArray.pop();

trace(mainArray.length + " is the length ");
}

 

Be honest and if you think the answer will be 4 then you definitely need to read this article and understand it. Still confused???? now you can run this piece of code and then you will find that the answer is 3.

how is this possible? We are not modifying mainArray at all, yes we are not modifying the reference to the array but then we are creating another reference to this array and then using it to modify the array. confused still, i need to explain it in more simple terms.

Lets take a look at the picture below, forgive my drawing skills but i think it serves the purpose,

 Pointer example

var mainArray:Array = new Array(“1″,”2″,”3″,”4”);
this line of code actually creates a reference which we have called mainArray. This reference points to an array class.

 

var tempArray:Array = mainArray;
one would expect this to create a duplicate array but no, we are just creating a new reference to the
same memory block, this reference is called tempArray.

 

tempArray.pop();
now we are using this reference called tempArray to modify the block of memory its pointing at, and hence that block of memory changes and we have only 3 elements in this array now.

Since mainArray is a reference pointing to the same block of memory as tempArray is, whenever we use mainArray reference it has changed now and its length is no longer 4.

 

if we do something like this, var tempArray:Array = new Array(“1″,”2″,”3″,”4”);
then we are actually creating a new block of code in memory and any changes to tempArray won’t affect mainArray.

hope now your doubts have cleared.

Remember, In Actionscript all complex data types are passed by reference and not by value.

 

Another test to find out if you understood how this works, try the following code, I am not including the graphical elements and i shall leave upto you to fill out the code for that.

package {

package {
    public class SampleClass {

        public var value:String;

        public function SampleClass() {

        }
    }
}

A sample test class to be used in our example, I am copying this code from Flex so will include only the actionscript code, you need to do proper initialization etc.

public var dataArray:Array;

//initialization function with an array holding the sampleclass instances
private function init():void{
    dataArray = new Array();
    for (var i:Number= 0;i&lt; 6 ;i++){
        var tempSample:SampleClass = new SampleClass();
        tempSample.value = String(i);
        dataArray.push(tempSample);
    }
}

//this function is called on button click
private function findSample(event:MouseEvent):void{
   
    //call the getSample function
    var tempClass:SampleClass = getSample();

    //if we find a match then we will change its value
    if (tempClass){
        trace(" found something lets change value");
        tempClass.value = "found yay";
    }

    for (var i:Number = 0; i &lt; dataArray.length ;i++){
        //what do you this this trace statement will output
        //will it show the modified value or will output 0 through 5
        trace(dataArray[i].value);
    }
}


//this function is called from the findSample
private function getSample():SampleClass{

    var foundSample:SampleClass;

    //get the string on which matching is to be performed
    var findSample:String = sampleText.text;

    for (var i:Number = 0; i &lt; dataArray.length ;i++){
        if (dataArray[i].value == findSample){
            foundSample = dataArray[i];
            break;
        }
    }

    return foundSample;
}

Once you get run this modify the getSample function as shown below and compare the results. It should give you a better idea.

//this function is called from the findSample
private function getSample():SampleClass{

    var foundSample:SampleClass = new SampleClass();

    //get the string on which matching is to be performed
    var findSample:String = sampleText.text;

    for (var i:Number = 0; i &lt; dataArray.length ;i++){
        if (dataArray[i].value == findSample){
            foundSample.value = dataArray[i].value;
            break;
        }
    }

    return foundSample;
}

 

hope this article was useful, as usual questions, comments always welcome :) 

 

No responses yet

Jul 14 2008

Cairngorm and Remote Object

Published by under AS 3.0,Flex

I have had opportunity to use Cairngorm with Webservices, Httpservice and Remote Object as well. I had some difficulty passing variables to the amfphp backend but ultimately resolved it. here is how,

public function execute(event:CairngormEvent):void {
           
    product = event.data.product;
    responderObj = event.data.responderObj;
    productId = product.products_id;
    var service:RemoteObject = ServiceLocator.getInstance().getRemoteObject("getProducts");
           
    var operation:Operation = service.getOperation("get_colors") as Operation;     
   
    //this method of sending arguments wasn't working, it was sending undefined.       
    //var dataArray:Array = new Array({productId:"93"});
    //operation.argumentNames = dataArray;
   
    var token:AsyncToken = operation.send(productId);
    token.addResponder(this);
           
           
}

For some reason operation.argumentNames i thought would take the array and then send the objects in this array as variables, but it was sending undefined as the value for the variable.

I resolved the problem by sending the variables in send function and i am sure you can send more than one variable in the send function.

2 responses so far

« Prev - Next »