Wednesday, September 12, 2007

Normal -> AJAX -> AJAJ -> AJAJS

The internet world is moving towards a rich and fast user experience at a very rapid speed. AJAX is contributing majorly in this direction.
AJAX [Asynchronous Javascript And XML] is not a technology, it is a concept built on the existing technology provided by major webbrowsers.
The native XMLHttpRequest object or the Microsoft.XMLHTTP ActiveXObject enables the use of AJAX. Using one of these [as the case may be] objects, the javascript code in a webpage can asynchronously send the HTTP's GET/POST request to a webserver. Javascript can be further used to display the responseText/responseXML anywhere on the existing webpage. This way some text [or image or any other HTML object for that matter] can be changed on the existing webpage without reloading the whole page.
Gmail, Orkut, Google Suggest and many other existing and upcoming sites use this concept extensively.
You can find a detailed explanation and examples of how to implement AJAX in your applications here.

AJAX requires the response from the webserver to be in XML format. To further improve the performance of the application, XML can be replaced by something light in weight. JSON (JavaScript Object Notation) provides a fat free notation of JavaScript objects. AJAJ (Asynchronous Javascript And JSON) does exactly this. By the use of AJAJ you may not have to fetch/parse the responseXML of the HTTP object to extrace the relevant info. The responseText can be directly loaded in the JavaScript variables. The official JSON website demonstrates this with beautiful examples.
There are 2 benifits of using AJAJ over AJAX:
1. JSON is lighter that XML.
2. You do not have to parse JSON on the client side to initialize JS variables, unlike XML.

Going a step further, we may even replace the JSON of AJAJ with JavaScript. I call it AJAJS [Asynchronous JavaScript And JavaScript]. Insead of responding with the responseXML or a JSON in the responseText, the server might respond with a javascript code in the responseText.
And on the client side, you may use the JavaScript eval() function to execute the responseText. So now the responseText can even be a function call.
Eq:
suppose http.responseText = "showMessage('From: chhabra.kapil@naukri.com', 'Subject: Hey!', 'Body: How do you do, buddy! ...')";
Now suppose that showMessage is a function in your javascript that accepts 3 parameters to display an email mesage on the page, you may just
eval(http.responseText)
in your client side JS code.

Monday, September 10, 2007

Working With Data in Flex-2

When retrieving data, one needs to know the structure of XML being fetched. In order to form a collection out of the same on needs to point to the repeating structure. For eg. in the following XML:
<parent>
<child>
<name>child1</name>
<id>0</id>
</child>
<child>
<name>child2</name>
<id>1</id>
</child>
<child>
<name>child3</name>
<id>2</id>
</child>
<child>
<name>child4</name>
<id>3</id>
</child>
</parent>
we would have some function:

[Bindable]
private var resultList:ArrayCollection=new ArrayCollection();

public function getResult(event:ResultEvent):void{
resultList = event.result.parent.child;
}

In this case child is the repeating unit.
When using a list-based control we could directly specify the data from this xml as follows:
<mx:List id="id" rowCount="3" dataProvider="{resultList}" labelField="name"/>
Note that for labelField we have directly specified the name of the node to be used.

The actual call will happen only when the send method is invoked using the id given to HTTPService class. It is prudent to call it on creationComplete event of application if data is to be used application wide. Else on creationComplete of the specific ui objects.

Always use collections instead of arrays for data-binding. Much more useful. By default complex data-structure is returned as an ArrayCollection. Multiple control enable display datastructures using the dataProvider property. List-based controls (List,Tree,DataGrid,TileList,ComboBox) use this property for sure. dataProvider control have a lot of advantage in the sense they are dynamic and can be used to populate multiple controls. UI control data-binding does not happen with AS2.0 Array. You can pass the array to creation constructor of a collection to form a collection with the array elements.

Questions:
  1. What is the advantage of using collections instead of arrays for data-binding?
  2. Explain usage of HTTPService with an example.
  3. When does the call to the URL mentioned in HTTPService happen?

Friday, September 7, 2007

Working With Data in Flex : Using HTTPService

<mx:Model> tag allows you to build a client-side data-model. AS can access it in id.tagName format. When using databinding in MXML, it is indicated by {}. You can either type the tags or specify an external file. Useful to embed data that will not change (like options in option box/label text). Also useful for applications that need data offline. However this data is not typed: can result in poor performance and severly limit error trapping. It is just a simple substitute for server-side data. Can be addressed by using AS class for client side data-structure. Another reason that it is a bad idea is because it embeds XML into the swf. Besides increasing the size it also means that we need to recompile the swf every time we change the XML. A better option will be to pick the XML at runtime using the HTTPService class. It will retrieve XML using HTTP/HTTPS protocol by making a GET or POST request.

HTTPService class can be used to make asychronous calls. send() method of the object is used to send the request. After data has been received, result event (ResultEvent) is broadcast. The result is stored in lastResult property. A resultFormat can be specified or Flex will parse it approproately. Format can be array, e4x, flashvars, object, text or xml.

Flex gives the flexibility to convert to native XML object (E4X) or to directly convert into a object(like ArrayCollection, XMLListCollection).

For automatic conversion, we will have a tag similar to this in the MXML:
<mx:HTTPService id="serviceId" url="http://www.myUrl.com/myXml.xml" result="handlingFunc(event)" fault="handleFault(event)"/>

Use fault event to handle errors. The event in this case will be FaultEvent and not ResultEvent

Questions:
  1. What are the advantages and disadvantages of using a Model tag in flex?
  2. How can you avoid using a Model tag?
  3. Describe in brief how HTTPService class works.
  4. What are possible result formats for HTTPService?
  5. What are the advantages of using HTTPService?
Sample MXML would make sense after a few more writings in this series. This is a very important feature in flex and well worth the time spent on it :) !

Thursday, September 6, 2007

Road To Flex-4

  • All tags added to MXML represent an object
  • creationComplete is a system event, dispatched by flex components after being screen rendered. Application dispatches it after all components drawn and individual components dispatch too.
  • [Bindable] metadata tag, when specified in front of the class keyword, means that every property in the class can be bound to controls or other datastructures. We can also specify individual properties as bindable. Allows changes to be reflected from source to destination.
  • A class constructor is defined using function keyword followed by the name of the class
  • Event class holds a lot of useful information about the event generated. currentTarget property refers to the element which generated the event. type property tells about the event type.

Questions that can be asked:
  1. How can we find out if a ui component has been rendered completely or not in flex?
  2. What is the use of Bindable tag?
  3. How do you define a class constructor in AS?

Tuesday, September 4, 2007

Road To Flex-3

  • To control focus in a form use FocusManager class.
  • <mx:CheckBox> is a regular ui component. selected property determines if checked.
  • <mx:Script> tag to write AS. functions defined can be called by name in control actions (like click for Button). Script written as is between <![CDATA[]]>
  • To display an image we use an Image control. ID property can be used by actionscript to reference the Image class. Scale content property if set to true scales image to container size. Embed directive embeds the image into the swf. eg: source="@Embed('assets/myPic.jpg')". mouseOver/ mouseOut property can be used to change current state.
  • Label control allows you to display a single line of text
  • Text control allows you to display multiple lines of text
  • <mx:Spacer> tag to add space between two controls. Specify width.
  • <mx:DateField> for date based input
  • All radio buttons must belong to a group. data property helps determine which btn selected in a group.
Questions:
  1. Name some common UI controls in flex.
  2. What can you do to control focus in a form?
  3. How can you ensure that a checkbox componenet is selected on creation?
  4. How can you write an actionscript in an MXML?
  5. How can you prevent an image in an image component from scaling?
  6. What effect will an Embed command have on an Image component?
  7. Which component will you use for a date-based input?
Sample MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

private var categories:ArrayCollection = new ArrayCollection();

private function myFunction():void{
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:LinkButton label="Default State" click="this.currentState=''"/>
<mx:LinkButton label="Change State" click="this.currentState='state1'"/>
<mx:Spacer width="100%"/>
<mx:Label text="Date Field"/>
<mx:DateField id="myDate"/>
<mx:RadioButtonGroup id="radioGrp"/>
<mx:RadioButton id="r1"
groupName="radioGrp"
label="Option 1"
data="1"
selected="true"/>
<mx:RadioButton id="r2"
groupName="radioGrp"
label="Option 2"
data="2"/>
</mx:ApplicationControlBar>
<mx:states>
<mx:State name="state1">
<mx:SetProperty target="{mainPanel}" name="width" value="0"/>
<mx:SetProperty target="{mainPanel}" name="height" value="0"/>
</mx:State>
</mx:states>
<mx:Panel id="mainPanel" title="My Panel" height="100%" width="100%">
</mx:Panel>
</mx:Application>

Flex Problems September 2007

Just archiving the flex problems I faced and the solutions that helped me. Will have one of these per month depending on whether I find a problem or not :p.

Problem: This message comes in debug mode: "Installed Flash Player is Not a Debugger. Flex Builder cannot locate the required debug version of the Flash Player. You may need to install the debug version of the Flash Player 9.0 or reinstall Flex Builder. Do you want to try to debug with the current version?"


Solution: Visit this link

The Road to Flex-2

  • All constraints are set relative to edges of a Canvas container (or those that can act as a canvas container like Application, Panel). They cannot be set relative to other controls or containers
  • Constraints help in controlling the view when window size changes
  • View state is one of the several views that you define for an application or a custom component. Every MXML page has at least one state, referred to as the base view state.
  • Each MXML page has a property called currentState that can be used to control which state of application to show to the user at any given time.
  • Setting currentState to blank string resets app to initial state
  • Forms are needed to collect info from users. In flex form containers can designate fields as optional or required, handle error messages and do validations. Form container uses <mx:Form>, <mx:FormHeading>, <mx:FormItem>. <mx:Form> is outermost tag and always arranges children in vertical fashion and left aligns them. We can have multiple heads. Form heading enable to specify label for a group of form items. Form item will automatically supply one label control. Other controls are added within tags and follow the label. By default all controls laid vertically right to the label. To change one needs to specify 'direction' property.
Questions:
  1. How are view constraints set in Flex?
  2. What is the use of having such constraints?
  3. What is the use of view states?
  4. What is the use of the property currentState?
  5. What will happen if the property currentState is set to a blank string?
  6. What is the use of forms in flex?
  7. How many heads/headings can a form have?
  8. What is the default layout for controls in a form? How can that be changed?
A sample MXML showing use of forms:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Form>
<mx:FormHeading label="Form Heading"/>
<mx:FormItem label="Item1 Name">
<mx:TextInput id="item1Txt" text=""/>
</mx:FormItem>
<mx:FormItem label="Item2 Name">
<mx:TextInput id="item2Txt" text=""/>
</mx:FormItem>
<mx:FormItem label="Item3 CB">
<mx:CheckBox id="cb1" selected="true"/>
</mx:FormItem>
<mx:FormItem>
<mx:HBox>
<mx:Button label="Save"/>
<mx:Button label="Cancel"/>
</mx:HBox>
</mx:FormItem>
</mx:Form>
</mx:Application>