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.


Sunday, May 22, 2011

Yet another Ajax toolkit

0 comments
Here is a little dabbling we did at Accorpa to empower rapid development of ajax applications.

We needed a tiny library that uses jQuery to be used in Rails with two simple steps:

  1. Add a couple of custom attributes to some links/inputs/forms
  2. Include a javaScript file into the layout.

The solution had to allow developing the same site in Ajax and non-Ajax ways (in parallel) so we added a new custom MIME type 'text/ajax' and used it in our controllers whenever we needed it.

A full rails example will be coming soon. Here is the JavaScript file for starters:

Thursday, May 12, 2011

Helping You Choose

0 comments
A bit of news, just for the record.

We are nearing the first phase of developing a new and exciting project.

It's a Group Decision Support API that empowers team members to participate in decision making without the usual hassle and with a minimum of time and expense.

It can also be used for e-Voting as it includes robust ballot-checking and verification tools to make sure the results are not open to fraud.

It can be used to develop web sites using Rails (or included into existing web sites via Ajax). It can also be used directly from JavaScript Web Page (returning meaningful JSON) or from a Flash/AIR application (returning meaningful XML). Indeed, we tried it from Delphi and it's OK.

The highlight is yet to come. From the ground up the model and libraries have been built to provide tons of statistics and staggering reports. These will be open as well for use as HTML, JSON, or XML.

We hope to release sneak peaks by the end of the month (i.e. April 2011) with the reporting API a couple of months later. We expect to go live before the end of the year.

Hope you like it. Fingers crossed.

Monday, May 9, 2011

Saving user settings in ios

0 comments
1- Saving user settings and loading them is very simple in ios development,

NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
[prefs setValue:@"10" forKey:@"timer"];
[prefs setValue:@"NO" forKey:@"showTip"];
[prefs synchronize];

don't forget to syncronize at the end so settings will be saved.

2- Loading user settings,

NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
NSString* s = [prefs valueForKey:@"timer"];
combines = [(NSString*)[prefs valueForKey:@"showTip"] boolValue];
start = [NSDate timeIntervalSinceReferenceDate];

Sunday, May 8, 2011

The Right way to do an Update statement in ios

0 comments
Yesterday i spent a whole hour trying to figure out why Update statement don't work, and then i found the solution,

1-Remember always to finalize your statement after using it (sqlite3_finalize), and closing the database (sqlite3_close), so you won't get this error "database is locked".

2- prepare statement don't execute the statement (sqlite3_prepare_v2), you have to run (sqlite3_step) to actually execute the statement.

3- use update statement as follows :
i want to do something like that
UPDATE users set language = 'en' , rank = 1 WHERE id = 4

and language, rank and id is captured from variables.


sqlite3* database;

if(sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK)
{
NSLog(@"connected to db");
NSString* format =
[NSString stringWithFormat:@"UPDATE Users set language = %@,rank = %d WHERE id = ?", language, rank];

const char* select = [format UTF8String];
sqlite3_stmt* stmt;

int result = sqlite3_prepare_v2(database, select, -1, &stmt,NULL );

if(result == SQLITE_OK)
{
sqlite3_bind_int(stmt, 1, cid);
if(SQLITE_DONE != sqlite3_step(stmt))
{
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(database));
}
sqlite3_finalize(stmt);
}
else
{
NSLog(@"error in statment: %s",sqlite3_errmsg(database));
}
}

sqlite3_close(database);

Wednesday, May 4, 2011

Juggling Ruby Class Names

0 comments

In a recent task, we had generated several models that share some common behavior. However, inheritance was not an option as the names of attributes were different for each class.

In such a case, you need to provide functionality for each class separately. Much of the code will be duplicated in methods pertaining to each class, which runs against the DRY principle.

In Ruby, a class called "Object" comes to the rescue. Using this class, we can retrieve a class (to be used exactly as a class) given its name (as a string):

@klass = Object.const_get("class_name")

You can create a new instance of the class:

@instance = @klass.send "new"

You can then assign values to attributes by their  name (string):

@instance.attributes={attribute_symbol => attribute_value}

You can also invoke a method directly on the class such as "find" or "all":

@klass.send "find", parameter_1, parameter_2, ...

In the following snippet, we call a method from a module to create a link between any object and a tagging object. We can use this in our controllers several times, passing relevant parameters to each:

tag_object( 'SubjectTag', :subject_id, :tag_id, 312, 105)

The code implementing this function can be understood knowing the above hints:

def tag_object(tag_class, id_symbol, tag_symbol, id, tag)
      
    @klass = Object.const_get(tag_class)
      
    if (@klass.send "find", :all, :conditions => {id_symbol => id, tag_symbol => tag}).length > 0 then
        return false   
    end   # if
    new_tag = @klass.send "new"
    new_tag.attributes={id_symbol => id, tag_symbol => tag}
    return new_tag.save
end

Hoping this is useful.

Tuesday, May 3, 2011

Custom Mime types in Rails

0 comments
To create a custom Mime type, you need to give it a name to be used in Rails under the format section in any controller.

You also need to provide a 'class/type' string to be recognized by the request/response protocol (i.e. in http headers).

To do this, open the folder "config/initializers" in your project, you'll find a file called "mime_types.rb".

Inside that file, add the following line:
Mime::Type.register "class/type", :name
For example, we use "text/ajax" and :ajax to provide a way of telling the controller that I'm requesting an ajax page, so no layout is rendered. More on this scenario later.

Please comment if you find any better solution or find a new use case for this tip.

Hi Folks

0 comments
Hello everyone

This is an open invitation to members of the Accorpa team to devote a few minutes of every day to reading and updating this blog.

It might be the best thing we ever do to start a Knowledge Management trend in Accorpa.

So, happy posting. Don't forget to comment!