Tuesday, August 16, 2011

Calculator with Flex4

0 comments
Calculator is an example of event handling using Flex4. It can make some simple mathematical calculations like addition, subtraction, division and multiplication. the interface of that calculator is as follow


The functions used in the logic of that calculator are implemented and used to handle the click events for any button of that calculator buttons as the following:

<s:Button x="25" y="164" label="1" width="29" height="31" click="calculateResult(1)"/>
<s:Button x="187" y="67" label="*" fontFamily="Times New Roman" fontSize="23" height="27" width="67" fontWeight="normal" fontStyle="italic" textDecoration="none" lineThrough="false" focusColor="#345471" enabled="true" id="multiply" click="changeSign("*")"/>


<fx:Script>
private var calcResult:int = 0;
private var sign:String = "";
private function calculateResult( newNum:int):void
{
var firstNum: int = int(parseInt(result.text, 10));
if (sign == "*")
{
calcResult = firstNum*newNum;
sign = "";
}
else if (sign == "-")
{
calcResult = firstNum-newNum;
sign = "";
}
else if (sign == "+")
{
calcResult = firstNum+newNum;
sign = "";
}
else if (sign == "/")
{
calcResult = firstNum/newNum;
sign = "";
}
else
{
calcResult = newNum;
}
result.text = calcResult.toString();
}

private function changeSign(newSign : String):void
{
if (newSign == "clr")
{
calcResult = 0;
result.text = calcResult.toString();
sign = "";
}
else
sign = newSign;
}
</fx:Script>

To download the full source code click here

Monday, August 15, 2011

Event handling in Flex4

0 comments

What is Event Handling?

Event handling means that when an event is fired then a specific action should be taken as changing the choices in one drop-down menu after the user makes a selection in another menu and revealing a block of information when the user moves the cursor over an image.

Types of Events

The events are predefined the framework. but events has two main categories: system events and user events. The system events are not caused by user actions but they are fired in response to special events happened in the system such as the application being fully loaded, components being created or responses being received like receiving response from network connection. the user events are the direct result of a user action like moving the cursor, typing in a text input or clicking a button, and more.

Ways of Handling Events

There are two ways of telling the application what actions to take when an event is fired. instructions can be placed inline or can be placed in a function and calling that function occurred when the event is fired.

Inline Event Handling

Handling events inline can be performed by assigning some ActionScript code to the component event property that wanted to be handled as seen in the following example.
<s:Label id="myLabel"/>

<s:TextInput id="myText" change="myLabel text=myText text"/>

In the previous example when the text written in the TextInput component changed the label text also changed and the action performed is written inline with the event change.


Function Event Handling

Functions provide a better way to handle events. to use functions to handle events we should define the function script block at first and then assign the name of that function as the value of the components event property in the MXML file as shown in the following example.


<s:Label id="myLabel"/>
<s:TextInput id="myText" change="changeLabelText()"/>

protected function changeLabelText():void
{
myLabel text=myText text
}

This approach does a better job of separating the presentation part from the logic part, allows handling events in some sophisticated manner, and will also allow code reuse as same function can be used to handle all sort of events on all components.

Introduction to Adobe Flex4

0 comments


Adobe Flex 4


What is Flex4

Flex 4 is the next generation technology for Rich Internet Applications. It is proving as a magical tool for web developers as with the inception of Flash technology, the web development has reached to a new paradigm. As it is known that Adobe Flex uses Adobe Flash platform for running its applications, so in this perspective, the importance of Flex 4 increases because it offers the latest features of Flex.

Flex 4 with its added extraordinary features can revolutionize the web development technology by providing high-end features in the next generation web applications.
for more information about flex4 features and learning how to use it click here

Development Tools for Flex4 and Installation

When Adobe releases Flex 4, it also releases Flash Builder 4 tool that was formerly known as Flex Builder. This tool is available commercially but you can use its trial version for 60 days period. to install this software click here

File Upload in Flex4

0 comments

Example: Upload files to Rails server
  • User want to upload images to /upload folder on the server and saves the path of each image on the database.
  • Assume the database has table called images which has an attribute called path.

1- Upload Form
  • FileReference is a class which allows you to upload/download to/from a server.
  • Each FileReference object refers to a single file on the user's disk.
  • browse() method allows a user to select one or more files.
  • FileReferenceList can be used when the user need to select multiple files.
  • For more details click here.


<s:Button x="10" y="14" label="Upload" id="uploadButton" click="openUploadForm()"/>



private function openUploadForm():void

{
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var allTypes:Array = new Array(imageTypes);
fileRefList = new FileReferenceList();
fileRefList.addEventListener(Event.SELECT, selectHandler);
fileRefList.addEventListener(Event.COMPLETE, completeHandler);
fileRefList.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
try
{
var success:Boolean = fileRefList.browse(allTypes);
}
catch (error:Error)
{
trace("Unable to browse files.");
}
}




2- Form Request

	//called when file selection is done

public function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest("http://{Server URL}/images/upload");
request.method = URLRequestMethod.POST;

var list:Array = fileRefList.fileList;
var fileRef:FileReference;

for(var i:Number = 0; i < list.length; i++)
{
fileRef = list[i];
fileRef.addEventListener(Event.COMPLETE, completeHandler);
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
trace("name: " + fileRef.name);
try
{
fileRef.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
}

//called when upload is completed
private function completeHandler(event:Event):void
{
trace("uploaded !!!");
}




3-Handle Request from Rails

	def upload

name = params[:Filename]
directory = "public/uploads"
path = File.join(directory, name)
File.open(path, "wb") { |f| f.write(params[:Filedata].read) }
newPath = File.join("/uploads", name);
@image = Image.new(:path => newPath)
respond_to do |format|
if @image.save
format.xml #upload.rxml
else
format.xml { render :xml => @image.errors, :status => :unprocessable_entity }
end
end
end




Upload.rxml


		xml.instruct!

xml.images do
xml.image_path @image.path
end



4- Handle Response from Flex



	private function responseHandler(event:DataEvent) :void

{
var images:XML = XML(event.data); //parse response
var image:ImageClass = new ImageClass(images.image_path[0]);
//continue handling response ...



Possible Errors

"Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error."

it may happen when the response format doesn't handled,
in our example we are only handling html and xml responses, So this error my happen
if the response format specified in the request is anything except (html) or (xml)

it can be handled by specifying the format to be "xml"



var request:URLRequest = new URLRequest("http://{Server URL}/images/upload?format=xml");
request.method = URLRequestMethod.POST;

Connecting To Rails

0 comments
Why ?
Sometimes we need to connect to rails server to save/request new data to/from the database server.

How ?
  1. Form a request by specifying the parameters to be send
  2. Handle request from Rails.

Connecting to Rails from Flex 4
assume the user enters a text and presses a button to save the entered text to the database.

1- POST Request:

  • Specify the request service component


	<mx:HTTPService id="userSendData" method="POST">	

<mx:url>http://{Server URL}/cards/save</mx:url>
<mx:fault>Alert.show(event.toString(), event.type);</mx:fault>
</mx:HTTPService>


  • Send Request


 

<s:TextArea id="cardName_TA" x="149" y="10" width="118" height="27"/>
<s:Button id="listButton" x="342" y="176" label="List Cards" click="getData()"/>



private function sendData():void
{
var params:Object = {};
params["cardName"] = cardName_TA.text;
userSendData.send(params);
}




2- Handling Request from Rails
assuming we have a table named cards with attribute called name




def save
name = params[:cardName]
@card = Card.new(:name => name)
respond_to do |format|
if @card.save
format.html { redirect_to(@card) }
format.xml { render :xml => @card, :status => :created, :location => @card }
else
format.html { render :action => "new" }
format.xml { render :xml => @card.errors, :status => :unprocessable_entity }
end
end
end

Object Handles with Flex 4 - quick start guide

0 comments
Flex ObjectHandles is a library that gives your visual components the ability to be moved, sized and also rotated, in this guide, you'll be introduced to it by example explaining the use of ObjectHandles to Handle Images.

Usage
download ObjectHandles library from here, the swc library needed is found under /deploy directory
to Handle your visual components, you need:

an ObjectHandles instance

The main component, that provides to your Visual components the ability to move and resize , you have to register your Components to this object using

myObjectHandles.registerModel(myModel, myVisualComponent);


a Model

the Model class contains visual component Attributes, and implements required interfaces
package flex.images.client.objecthandles {

import com.roguedevelopment.objecthandles.IMoveable;
import com.roguedevelopment.objecthandles.IResizeable;

public class ImageModel implements IResizeable, IMoveable {
[Bindable] public var x:Number = 10;
[Bindable] public var y:Number = 10;
[Bindable] public var height:Number = 100;
[Bindable] public var width:Number = 100;
[Bindable] public var rotation:Number = 0;
[Bindable] public var isLocked:Boolean = false;
}
}


a Visual Component

the component you want to make it moveable, resizeable, and/or rotatable, it also contains the event listener for handling moves, scaling, and rotations
package flex.images.client.objecthandles {

import mx.controls.Image;
import mx.events.PropertyChangeEvent;

public class ImageShape extends Image {
protected var _imgmodel:ImageModel;

public function ImageShape() {
super();
this.maintainAspectRatio = false;
}

public function set model( model:ImageModel ) : void {
if( _imgmodel ) {
$_imgmodel.removeEventListener(
PropertyChangeEvent.PROPERTY_CHANGE,
onModelChange );
}
_imgmodel = model;
x = model.x;
y = model.y;
width = model.width;
height = model.height;

model.addEventListener(
PropertyChangeEvent.PROPERTY_CHANGE,
onModelChange );
}

protected function onModelChange( event:PropertyChangeEvent):void
{
switch( event.property ) {
case "x": x = event.newValue as Number; break;
case "y": y = event.newValue as Number; break;
case "rotation": rotation = event.newValue as Number; break;
case "width": width = event.newValue as Number; break;
case "height": height = event.newValue as Number; break;
default: return;
}
}
}
}


Example
Example showing the load of a dynamic Image and Handling It
  • Insert a canvas in mxml file
<mx:Canvas x="100" y="100" width="400" height="440"

id="objectHandlesContainer" ></mx:Canvas>
  • In ActionScript3 page/block, insert the following

[Bindable] protected var flexModel:ImageModel;

[Bindable] protected var imgShape:ImageShape;

private function myFunction():void {
/*can be called as an initializer function
to load image handles at page load or called as an event handler to
dynamicaly handle images*/
flexModel = new ImageModel();
imgShape = new ImageShape();
imgShape.model = flexModel;
objectHandlesContainer.addChild(imgShape);
imgShape.source = PATH_TO_IMAGE;
objectHandles.registerComponent( flexModel, imgShape );
}

Wednesday, July 20, 2011

RMagick installation problem

0 comments
Do you get this error when you are trying to install RMagick :
checking for Magick-config... no
Can't install RMagick 2.12.0. Can't find Magick-config in /usr/bin:/bin
  1. And you have installed ImageMagick with version > 6.3.5 from source.
  2. And when you search every where on the internet they tell you to install ImageMagick and ImageMagick-devel from yum.
  3. And when trying to understand why it is not working as Magick-config is available in /usr/local/bin , but RMagick is searching for it in /usr/bin and can't find it.
  4. The solution is to copy Magick-config from /usr/local/bin to /usr/bin , and try to install RMagick again.

Thursday, June 16, 2011

Database Localization in Rails

0 comments
A problem arises when you use I18N plugins (or your own code) to localize web sites; the data derived from your database is not localized. You have several options:
  1. You can give up on international users.
  2. You can use another plugin to 'Globalize' your database.
  3. You can do it yourself.
Here is a short and rather simple way to do it.

Wednesday, June 8, 2011

debugging in Aptana RadRails 2 steps

0 comments
the Steps needed to debug your Rails project under Aptana RadRails 2 IDE, (tested for Ruby 1.8.7, Rails 2.3.5)
  • Install DevKit, use the instructions at https://github.com/oneclick/rubyinstaller/wiki/Development-Kit
  • install ruby-debug-ide, it will install ruby-debug-base and linecache gems
  • in your Aptana RadRails IDE, select debug configuration (Run > Debug Configuration)
  • set your Application Root, Web Server, Action URL and Web Browser
  • Now you've completed your configurations, you should be able to start debugging

Thursday, June 2, 2011

Browser History with Ajax

0 comments
Hi Ajaxians,

In the last post we showed off a tiny tool that should make life easier writing Ajax for Rails apps using jQuery. The ideas was to separate (like everyone) the code from the design (which could be incrementally built with as little fuss as possible).

Of course, the back button of the browser reminds us all of the bad days on ugly browser refreshing. To Ajaxians it was a nightmare to support. Of course tons of libraries handle it for you so we thought we'd pitch in.