Flex Interview Questions
Flex Interview Questions
Flex Interview Questions
2. I need to load an image from flickr into my application. Do I need a crossdomain.xml file on flickr?
A: File is already there , we need to register our ip address to flicker’s crossdomain.xml
? : Since the images are located on a flickr server like farm1.static.flickr.com and there is no
crossdomain.xml file on that server (there is a crossdomain.xml for api.flickr.com so you can use the
api) that means you can’t get access to the bitmapData of the loaded images when you load them
from flickr. This is dumb, but that’s the way it is. So you can load images just fine, but the reflection
class copies the bitmapData of the image, so that doesn’t work if you load them straight from the
flickr server. I also wanted to set bitmap smoothing to true on the images so the thumbnails don’t
look as pixelated, and that also requires access to the bitmapData of the loaded image.
So the answer is to create a proxy that loads the flickr image so it appears to come from the same
domain.
4. How do you generate random numbers within a given limit with actionscript?
A: Math.round(Math.random() * (high - low)) + low
5. Have you built any components with actionscript? If so explain how you did it?
CountryComboBox.as
package components
{ import mx.controls.ComboBox;
public class CountryComboBox extends ComboBox
{ public function CountryComboBox()
12444940.doc 1 [email protected]
{ dataProvider = [ "United States", "United Kingdom" ];
}
}
}
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:custom="components.*"
width="220" height="115"
>
<custom:CountryComboBox />
</mx:Application>
7.I am going to add images into a tag. How will it resize itself?
A1: To let Flex resize the image as part of laying out your application, set the height or width
properties to a percentage value. Flex attempts to resize components with percentage values for these
properties to the specified percentage of their parent container.
A2 : By default, Flex does not resize the image. The scaleContent property has a default value of
true, therefore, Flex scales the image as it resizes it to fit the specified height and width. The aspect
ratio is maintained by default, so the image may not completely fill the designated space. Set the
scaleContent property to false to disable scaling. Set the maintainAspectRatio property to false to
allow an image to fill all available space regardless of its dimensions.
12444940.doc 2 [email protected]
preInitialize
Dispatched when a component has been created in a rough state, and no children have been created.
initialize
Dispatched when a component and all its children have been created, but before the component size
has been determined.
creationComplete
Dispatched when the component has been laid out and the component is visible (if appropriate).
13. How do you implement drag and drop on components that do not support ondrag and ondrop?
A:
14.Can you write to the file system from flex?
A: Yes .
import flash.filesystem.*;
private var stream:FileStream;
private function saveFile():void{
var file:File = File.desktopDirectory.resolvePath("HelloWorld.txt");
var stream:FileStream = new FileStream()
stream.open(file, FileMode.WRITE);
var str:String = "Congratulations on your 1st file, Rich Tretola - EverythingFlex.com";
stream.writeUTFBytes(str);
stream.close();
mx.controls.Alert.show("File has been saved to \n" + file.nativePath, "Notice");
12444940.doc 3 [email protected]
A : Skinning is the process of changing the appearance of a component by modifying or replacing its
visual elements. These elements can be made up of images, SWF files, or class files that contain
drawing API methods.
There are several ways that you can define skins: inline, by using the setStyle() method, and by using
Cascading Style Sheets (CSS).
Inline styles are defined in an MXML tag and can only be used in that tag. Inline styles are defined
as follows:
<mx:Button color="red"...>
<mx:TextInput fontFamily="Helvetica" fontSize="12"...>
20. What is the difference between sealed class and dynamic classes?
A : Classes are sealed by default, i.e. properties cannot be added dynamically at runtime.
* Dynamic classes can add additional dynamic properties at runtime; sealed classes cannot.
* Sealed classes conserve memory because no internal hash table is needed to store dynamic
properties, and the compiler can provide better error feedback.
12444940.doc 4 [email protected]
few components based on certain conditions.
* ViewStates are virtual state of an existing page apearing at an instance i.e. only one state can be
shown at a time
while viewStack are collection of different view containers which can be shown at a time
23.how does item renderer work? How do I add item renderer at runtime?
A : Each list control has a default mechanism for controlling the display of data, or view, and lets
you override that default. To override the default view, you create a custom item renderer.
Note: With reusable inline item renderers you use data binding to bind to the item renderer. When
you use a component as an item renderer, you do not use data binding but specify the name of the
custom component to use as an item renderer.
Add itemrendrer at run time: Create the basic item renderer. One of the things I needed to accomplish
with my item renderer was the ability to add it to different columns (ie the dataField was not always
the same). This meant I needed a way from within the renderer to determine what column it was
bound to so I could get and display the correct data. To do this the renderer needs to implement the
IDropInListItemRenderer. This interface allows the renderer to have access to information about the
list and column it is in via the BaseListData and DataGridListData classes. The DataGridListData
gives you everything you need to get the data required to make a flexible, reusable renderer.
To Modify itemrenderer at runtime we Need to use mx.core.ClassFactory. Basically, in order to
change a Flex itemRenderer at runtime, you need to cast it to a type ClassFactory.
class Employee {
internal var baseSalary:Number = 1000;
public function receivePayment():Number {
return this.baseSalary;
}
}
12444940.doc 5 [email protected]
27.what is dynamic keyword used for?
A: Dynamic classes, which allow you to programmatically add new properties and behavior to
classes during the run-time. Just add the magic keyword dynamic to the class definition:
dynamic class Person {
var name:String;
}
Now let’s add dynamically two variables name and age and the function printme() to the object of
type Person:
30.What is cairnghorm ? how do you use it?Have you worked with Cairnghorn?
A : Cairngorm is the lightweight micro-architecture for Rich Internet Applications built in Flex or
AIR. A collaboration of recognized design patterns, Cairngorm exemplifies and encourages best-
practices for RIA development advocated by Adobe Consulting, encourages best-practice leverage of
the underlying Flex framework, while making it easier for medium to large teams of software
engineers deliver medium to large scale, mission-critical Rich Internet Applications.
The benefits of the Cairngorm architecture are realized when developing complex RIA applications
with multiple use-cases and views, with a team of developers, and with a multi-disciplinary
development team that includes designers as well as creative and technical developers.
How is the MVC pattern carried out in a Flex + Cairngorm application?
- Model:???? Role of the ModelLocator & Model Objects
- View:???? Role of View Components & Event Objects
- Controller: Role of the FrontController & Command Objects
12444940.doc 6 [email protected]
32.What design patterns have you used? in Actionscript and java?
A:
1. Creational Pattern
* Factory Method Pattern
* Singleton Pattern
2. Structural Patterns
* Decorator Pattern
* Adapter Pattern
* Coposite Pattern
3. Behavioral Patterns
* Command Pattern
* Observer Pattern
* Template Metod Pattern
* State Pattern
* Strategy Pattern
4. Multiple Patterns
* MVC Pattern
* Symetric Proxy Pattern
33.What’s the difference between Java and AS3 getters and setters?
The best practice for defining components that return information back to the main application is to
design the component to dispatch an event that contains the return data. In that way, the main
application can define an event listener to handle the event and take the appropriate action. You also
use events in data binding. The following example uses the Bindable metadata tag to make
useShortNames a bindable property. The implicit setter for the useShortNames property dispatches
the change event that is used internally by the Flex framework to make data binding work.
12444940.doc 7 [email protected]
Works pretty much the same way as the watch, but instead of having to handle and event it allows
you to immediately bind two properties one-way.
The first two parameters are for the the target, the second parameters are the triggers.
BindingUtils.bindProperty( this, "va1", this, "var2");
Note : Make sure you add the flex framework.swc to your project Library Path to have access to the
mx.binding.util class.
36.Why would you want to keep a reference to a ChangeWatcher and call unwatch()?
A: So we can reattach the watcher again & We can change the source object (of changewatcher) by
reset method.
The ChangeWatcher class defines utility methods that you can use with bindable Flex properties.
These methods let you define an event handler that is executed whenever a bindable property is
updated.
unwatch () method:
Detaches this ChangeWatcher instance, and its handler function, from the current host. You can use
the reset() method to reattach the ChangeWatcher instance, or watch the same property or chain on a
different host object.
public function unwatch():void
37.How do you add event listeners in mxml components. Now AS3 components?
A:
* addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
* removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
* dispatchEvent(event:Event):Boolean
* hasEventListener(type:String):Boolean
* willTrigger(type:String):Boolean
38.What does calling preventDefault() on an event do? How is this enforced?
A: Cancels an event's default behavior if that behavior can be canceled.. For example, the
doubleClick event has an associated default behavior that highlights the word under the mouse
pointer at the time of the event. Your event listener can cancel this behavior by calling the
preventDefault() method.
You can use the Event.cancelable property to check whether you can prevent the default behavior
associated with a particular event. If the value of Event.cancelable is true, then preventDefault() can
be used to cancel the event; otherwise, preventDefault() has no effect.
39.Explain the lifecycle of a Cairngorm action.
A: Here’s a normal flow of operations and the Cairngorm classes that are exercised.
When the user takes some sort of action on the view, such as clicking a button, the view dispatches a
CairngormEvent. This event informs the FrontController, which instantiates a Command. The
command executes the business logic, and the event is responsible for passing data to the command
about the user interaction.
The command can either take some action on the Model, or instantiate and act on a Business
Delegate. The Business Delegate, or delegate for short, wraps the code required for a service call, so
it acts like the service API to the rest of the application. This is important because when the service
12444940.doc 8 [email protected]
changes, the changes to the application can be minimized and ideally only the delegate needs to
change. The delegate calls the service and then depending on the kind of service involved makes sure
that the command is informed when the service call has returned. Then the command changes the
state of the model, if necessary, and the model, through Flex’s binding, updates the view.
41.Explain the difference between creating an effect and setting the target as opposed to adding an
effectListener
A: To create a behavior, you define a specific effect with a unique ID and bind it to the trigger.
For example, the following code creates two zoom effects: one for shrinking the component slightly,
and one for reverting it to its original size. These effects are assigned, by using their unique IDs, to
the mouseDownEffect and mouseUpEffect triggers on the Button component.
<mx:Application ...>
<mx:Zoom id="shrink" duration="100" zoomHeightTo=".9" zoomWidthTo=".9" />
<mx:Zoom id="revert" duration="50" zoomHeightTo="1" zoomWidthTo="1" />
<mx:Panel title="Bouncy Button" paddingTop="10" paddingBottom="10"
paddingLeft="10" paddingRight="10" autoLayout="false" left="41" top="24" right="42">
<mx:Button id="bouncyButton" label="Click me!"
mouseDownEffect="{shrink}" mouseUpEffect="{revert}"/>
</mx:Panel>
</mx:Application>
How do you generate random numbers within a given limit with actionscript?
public function randRange(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNum;
}
What are the methods called when a UI component is intialized?
createChildren()
When the drag is complete, a dragComplete event is sent to the drag initiator.
12444940.doc 10 [email protected]
The ExternalInterface class is the External API, an application programming interface that enables
straightforward communication between ActionScript and the Flash Player container– for example,
an HTML page with JavaScript. Adobe recommends using ExternalInterface for all JavaScript-
ActionScript communication.
You can call an ActionScript function in Flash Player, using JavaScript in the HTML page. The
ActionScript function can return a value, and JavaScript receives it immediately as the return value
of the call.
This functionality replaces the fscommand() method.
The ExternalInterface class requires the user's web browser to support either ActiveX® or the
NPRuntime API that is exposed by some browsers for plug-in scripting. Even if a browser and
operating system combination are not listed above, they should support the ExternalInterface class if
they support the NPRuntime API. See http://www.mozilla.org/projects/plugins/npruntime.html.
Note: When embedding SWF files within an HTML page, make sure that the id and name attributes
of the object and embed tags do not include the following characters: . - + * / \
From ActionScript, you can do the following on the HTML page:
The BindingUtils class defines utility methods for performing data binding from ActionScript. You
can use the methods defined in this class to configure data bindings.
private function init():void {
BindingUtils.bindProperty(textInputDst, "text", textInputSrc,
"text");
}
An example of a behavior that is not cancelable is the default behavior associated with the
Event.REMOVED event, which is generated whenever Flash Player is about to remove a display object
from the display list. The default behavior (removing the element) cannot be canceled, so the
preventDefault() method has no effect on this default behavior.
You can use the Event.cancelable property to check whether you can prevent the default behavior
associated with a particular event. If the value of Event.cancelable is true, then
preventDefault() can be used to cancel the event; otherwise, preventDefault() has no effect.
<![CDATA[
private function textArea_textInput(evt:TextEvent):void {
if (evt.text == "\n") {
evt.preventDefault();
}
12444940.doc 12 [email protected]
}
]]>
</mx:Script>
<mx:TextArea id="textArea" verticalScrollPolicy="on" width="160"
height="120" textInput="textArea_textInput(event);">
<mx:text>The quick brown fox jumped over the lazy dog.</mx:text>
</mx:TextArea>
LifeCycle of Flex-application??
12444940.doc 13 [email protected]
initializedproperty
initialized:Boolean [read-write]
A flag that determines if an object has been through all three phases of layout: commitment,
measurement, and layout (provided that any were required).
Ex:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="349"
height="319" viewSourceURL="../files/LifeCycleEventsTutorial.mxml"
preinitialize="recordEvent(event)" initialize="recordEvent(event)"
creationComplete="recordEvent(event)" applicationComplete="recordEvent(event)">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
import flash.utils.getTimer;
[Bindable]
private var reportTxt:String = "";
private function recordEvent(event:FlexEvent):void
{
reportTxt += (event.type + " event occured at " + flash.utils.getTimer() + "ms" + "\n");
}
]]>
</mx:Script>
<mx:Panel x="0" y="0" width="349" height="319" layout="absolute" title="Life Cycle Events">
<mx:TextArea x="10" y="10" width="309" height="259" editable="false" id="txtReport"
text="{reportTxt}"/>
</mx:Panel>
</mx:Application>
Flex 1.5 does not support this. First declare the tags in MXML and then manipulate the URLs,
request objects, and so forth using ActionScript.
Dynamic loading of CSS files is not supported in Flex. CSS in Flex is processed on the server side
during MXML compilation rather than on the client side at runtime. There is a trick though: A CSS
file can be compiled into a separate SWF file and loaded dynamically into the application using the
Loader component.
Q. When I set visible="false", the component still takes up space and appears in the tab order. Why is
that?
You can often achieve the "display=none" effect by setting the height/width to zero when you set it
invisible, and then set it back to a fixed value or to undefined when you make it visible again.
Q. Why are my ValueObject member variables undefined in the results from my RemoteObject requests?
Flash Player deserializes objects in a special order that can confuse developers used to object
serialization from other RPC systems. When a strongly typed object is returned to the player, it first
creates an instance from the prototype of the registered class without calling the constructor. It then
12444940.doc 14 [email protected]
populates the object with the properties sent in the result. Finally, it calls the constructor without
arguments.
If your ValueObject constructor expects arguments to initialize an instance, be sure to check whether
arguments were actually sent to the constructor before overriding member variable values.
The NetConnection Debugger is an old utility from the early days of Flash Remoting that some
developers still find useful. It has an issue, however, displaying types that have been registered with
Object.registerClass(). If your Flex server is installed locally, we suggest enabling server-side
"debug" level logging in /WEB-INF/flex/gateway-config.xml to watch the raw trace information in
the Flex server console/logs from the AMF Gateway as it processes your RemoteObject requests.
Flex Builder also includes a Network Debugger that allows you to monitor AMF traffic.
The AMF Gateway provides access to the current HttpServletRequest instance in a thread local
variable. The session can be obtained from the request, as follows:
flashgateway.Gateway.getHttpRequest().getSession();
12. Can I resize the Internet Explorer browser window from Flex?
getURL('javascript:window.resizeTo(1050,900)');
13. Can Flex applications communicate with each other on the client?
Unfortunately, double-clicking is not supported by default. If you wish to add this functionality to,
say, a List or DataGrid component, you will have to add the following ActionScript 2.0 code to your
application:
var someTimestamp:Number;
public function doubleClickHandler( evt:Object ):Void {
var now = getTimer();
// we got a double-click
if( ( now - someTimestamp ) < 500 ) {
// do something here ...
}
someTimestamp = now;
}
15. Why are there errors with the macromedia.css.LocatorParser class and WebLogic?
WebLogic ships with its own version of the fop.jar, which in turn includes the batik.jar, which is
older and breaks Flex. To resolve this issue, remove the fop.jar from the CLASSPATH in the
startWebLogic.cmd file. This may apply to non-WebLogic servers as well, where batik.jar was
included.
12444940.doc 15 [email protected]
16. What does "The URL is not in the Proxy's whitelist" mean?
The whitelist is a security feature in Flex that requires you to define explicitly which URLs a data
service call can access.
You set this by editing the following file: ...\[flexroot]\WEB-INF\flex\flex-config.xml
There are three sections, one each for WebService, HTTPService, and RemoteObject. Be sure you
edit the correct section! Each has a subsection which contains nodes. To enable a URL for access by
a Flex dataService call, enter that URL between the tags.
For development phase only, you can allow global access with the wildcard rows. The flex-config
file is heavily commented. Open it up and you will see more detailed instructions there.
17. Sometimes, if I don't move the mouse, "click" and "mouseDown" don't work. Why is that?
This is a focus issue with Flash Player; usually when the UI changes "underneath" the mouse pointer,
as in a ViewStack navigation where the buttons are in the same screen location.
Make sure you use the TreeDataProvider methods to modify a node. Don't rely on the node being
XML. For example, the above should be myTreeNode.getProperty("label") instead.
20. When I add or modify an item in my dataProvider, why doesn't it show up in my DataGrid?
Low-level methods like Array.push() or myArray[0] = "whatever" do not cause the
dataProvider's modelChanged event to fire.
When you work with a dataProvider, it is always best to use the dataProvider API. In the above
example, you might code: myDataProvider.addItem(myItemObject) to add an item or use
editField() to modify a value programmatically.
Alternatively, you can call myDataProvider.modelChanged yourself or reassign dataProvider to
the control, as follows: myDataGrid.dataProvider = myDataProvider;
21. myTree appears just fine but why can't I access the node attributes?
Select a node in your myTree. In ActionScript, you can reference this node by using the following
code: myTree.selectedNode;
To access the attributes of the node, use the tree DataProvider API. These methods will work for
any format dataProvider item, which might be an object, array, or XML node.
The following example might work: myTree.selectedNode.attributes.myAttribute
But the following example is far more reliable:
myTree.selectedNode.getProperty("myAttribute");
It uses the initobj to pass in several built-in properties plus two user defined
properties.
One is a simple string, the other is a reference to the main application that can
be used for binding. Note the variable that holds the application reference is
typed to the name of the application. this is critical for binding to work
correctly.
Flex is not a server that you deploy and run. It is simply deployed as part of your web application. So
it will work, no matter which web container you are using: Tomcat, JRun 4, WebLogic, and so forth.
To learn how to deploy Tomcat, JRun 4, or any other Java server as a service, refer to the appropriate
documentation for the server you are using.
12444940.doc 16 [email protected]
29. How do I get Flex to query my database?
Flex does not have any native database integration functionality. You must have your own server-side
tier that provides the database-access tier and sends the data back to Flex through one of the
following protocols:
• RemoteObjects: This is the fastest. It communicates with server-side EJBs or POJOs using
AMF, a binary compressed format.
• HTTPService: This one uses the HTTP protocol. Sources can be JSP, ASPx, .NET, or any
URL that returns HTTP.
• WebService: This is the slowest. It uses the SOAP protocol. Sources can be .NET or any web
service.
30. I'm sending my request, and I see the data traffic in the command window, but why is the result always
empty?
You are probably trying to read the result immediately after the send(), right? You're expecting
synchronous behavior?
oRequestCall.MyQueryId = "WhateverIWanttoUseToIdentifyThisCall" ;
//Yes, you CAN set this AFTER you invoke send()
4. In the result handler, which will be called every time the data service call returns, identify
what the returned data contains, as follows:
var callResponse = oEvent.call; //get the call object
//gets the value of this property you set in the call
var sQueryId = callResponse.MyQueryId; //will be
"WhateverIWanttoUseToIdentifyThisCall";
trace(sQueryId);
You can use the sQueryId value in a switch to do the correct processing. Alternatively, you can pass
reference to a handler function directly.
12444940.doc 17 [email protected]
32. When I have only a single record, why doesn't it appear in my DataGrid?
This is a known issue that is caused by the inability of Flex to differentiate between an object and an
array with a single row. The solution is to always use toArray(), as in the following examples:
In MXML:
{mx.utils.ArrayUtil.toArray(modelAccidents1.accidents.accident)}
The inline format:
dataProvider={mx.utils.ArrayUtil.toArray(testSrv.result.result.error)}
In ActionScript:
myControl.dataProvider = mx.utils.ArrayUtil.toArray(testSrv.result.result.error)
The order is typically the reverse of the order in which they were added. If you need a specific order,
specify that and many other good things by using DataGridColumn tags.
Flex supports a limited subset of HTML in its TextArea and some other text-related classes.
There is also a new article by Christophe Coenraets on his blog discussing how to fake HTML with
an IFRAME: http://coenraets.com/viewarticle.jsp?articleId=95
• Cairngorm: http://www.iterationtwo.com/open_source_cairngorm.html
• FlexUnit: http://www.iterationtwo.com/open_source_flexunit.html
• SynergyFLEX: http://www.mossyblog.com/archives/473.cfm (this link is for 1.0.0a)
• ARP: http://www.osflash.org/projects/arp/about
• AsUnit: http://www.asunit.org
Yes, that is possible. You have to embed the font outlines and then use the _rotation property of the
control.
For example, you can use the Label _rotation property. But you would need to embed the font if
you want to rotate a Label, TextInput, or TextArea:
12444940.doc 18 [email protected]
Flex Component Life Cycle :
Initialization Stage :
12444940.doc 19 [email protected]