Wednesday, July 29, 2009

Working with AMFPHP for Flex

Flex with PHP using AMFPHP for framework.
Install framework AMFPHP in your computer.
- Download amfphp-1.9.beta.20080120.zip under amfphp_1.9_beta2 from this URL http://sourceforge.net/project/showfiles.php?group_id=72483#files
- Create folder amfphp in your webserver
ex => D:\xampp\htdocs\amfphp
extract your amfphp-1.9.beta.20080120.zip in D:\xampp\htdocs\amfphp
- Try invoking gateway.php and see if it is set up properly.
http://localhost/amfphp/gateway.php

Create your file PHP, under directory ../amfphp/services/myservice/
This connection using Microsoft SQL Server with ADODB
- connection.php
<?php
include('adodb/adodb.inc.php'); # load code common to ADOdb

class connection
{
public $rrgpl;
public function connection(){}
public function getConnection()
{
$rrgpl = ADONewConnection('mssql');
$rrgpl -> Connect("SERVER_NAME","USERNAME","PASSWORD",'DB_NAME');
return $rrgpl;
}
}
?>


databrg.php
<?
include "connection.php";
class databrg
{
function databrg(){}
public function getAllData()
{
$result = array();
$conn = new connection();
$rrgpl = $conn->getConnection();
$i=0;
$databrg = $rrgpl->Execute("SELECT KDBRG,NMBRG,UNIT,GAMBAR FROM TABLE_NAME");

while(!$databrg->EOF)
{
$result[$i]["kode"]=trim($databrg->fields[0]);
$result[$i]["nama"]=trim(str_replace('&','&',$databrg->fields[1]));
$result[$i]["unit"]=trim($databrg->fields[2]);
$result[$i]["gambar"]=trim($databrg->fields[3]);
$i++;
$databrg->MoveNext();
}
return $result;
}
}
?>

After you create file PHP for getting data in database, now you create Flex file ( MXML & Action Script 3.0 ) , you can use Flex Builder for create this file:
Code :
SrvHTTP.as
import mx.controls.Alert;
import mx.managers.CursorManager;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.rpc.events.FaultEvent;

private var cs:ChannelSet;
private var channel:AMFChannel

private function getNewChannelSet():ChannelSet
{
cs = new ChannelSet();
channel = new AMFChannel("amfphp","http://localhost/amfphp/gateway.php");
cs.addChannel(channel);
return cs;
}
private function faultHandler(fault:FaultEvent):void
{
CursorManager.removeBusyCursor();
Alert.show("code:\n" + fault.fault.faultCode + "\n\nMessage:\n"
+ fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail);
}

Code:
listbrg.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="666" height="514" alpha="0.8" title="List Data Barang" backgroundAlpha="1.0" showCloseButton="true" close="closing()" creationComplete="init()">
<mx:ArrayCollection id="array_jmlh"/>
<mx:RemoteObject id="getListDataBrg" source="srv-kunci.databrg" destination="amfphp" fault="faultHandler(event)" showBusyCursor="true">
<mx:method name="getAllData" result="resDataBrg(event)" fault="faultHandler(event)" />
</mx:RemoteObject>
<mx:Script source="SrvHTTP.as"/>
<mx:Script>
<![CDATA[
import mx.utils.ArrayUtil;
import mx.collections.IViewCursor;
import mx.controls.CheckBox;
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.managers.PopUpManager;

public var kode:String='';
public var nama:String='';
public var unit:String='';
public var gambar:String='';
public var statusClose:Boolean=false;

private function init():void
{
getListDataBrg.channelSet=this.getNewChannelSet();
getListDataBrg.getAllData();
}
private function closing():void
{
statusClose=true;
PopUpManager.removePopUp(this);
}
private function resDataBrg(evt:ResultEvent):void
{
this.array_jmlh = new ArrayCollection( ArrayUtil.toArray(evt.result) );
}

private function selectListBrg():void
{
kode=dgListBrg.selectedItem.kode;
nama=dgListBrg.selectedItem.nama;
unit=dgListBrg.selectedItem.unit;
gambar=dgListBrg.selectedItem.gambar;
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<mx:DataGrid dataProvider="{array_jmlh}" id="dgListBrg" doubleClickEnabled="true" doubleClick="selectListBrg()" left="10" right="10" top="10" bottom="40">
<mx:columns>
<mx:DataGridColumn headerText="Item Code" dataField="kode" width="130"/>
<mx:DataGridColumn headerText="Item Name" dataField="nama"/>
<mx:DataGridColumn headerText="Item Unit" dataField="unit" visible="false"/>
<mx:DataGridColumn headerText="Item Gambar" dataField="gambar" visible="false"/>
</mx:columns>
</mx:DataGrid>
</mx:TitleWindow>

That's it sample simple for Remote using Flex and AMFPHP framework with PHP file.

Sunday, July 26, 2009

Building Run Time Shared Libraries For Flex Application

  1. Open your project Flex
  2. Right-click on the project name and select Properties.
  3. Select Flex Build Path from the left hand menu.
  4. Select the Library path tab and notice the Flex 3.x as one of the libraries in the project.
  5. Expand the Flex 3.x library.
  6. Expand framework.swc.
  7. Select the Link Type and click on the Edit tab.
  8. Uncheck Use same linkage as framework.
  9. Change the Link Type menu drop down to Run time shared library (RSL).
  10. Click OK.
  11. Bulid your project.
  12. Now, select your file .swf file and right-click on it. Select the Properties and look at the Size of the file. which is a further reduced from before. ^,^v Wow....look your SWF file siz
  13. By default, Flex Builder created the swf files for the projects under the bin-debug folder. All files under this folder have some additional debug information which is not required when publishing a project. We will create a release version of this application next.
  14. Right-click on the project name and select Export.
  15. Expand the Flex Builder folder.
  16. Select Release Build
  17. Click Next.
    Alternatively, you can select from the main menu Project > Export Release Build.
  18. In the dialog window that comes up, notice the Export to folder option is listed as bin-release.
  19. Click on Finish to create the release files.
  20. Now, look your SWF file size in folder bin-release....^,^v

Saturday, July 18, 2009

Modify cell color in Datagrid component

The DataGrid control is a list that can display more than one column of data. It is a formatted table of data that lets you set editable table cells, and is the foundation of many data-driven applications.

For information on the following topics, which are often important for creating advanced data grid controls, see:

  • How to format the information in each DataGrid cell and control how users enter data in the cells.
  • How to drag objects to and from the data grid

For complete reference information, see the Adobe Flex Language Reference.

About the DataGrid control

The DataGrid control provides the following features:

  • Resizable, sortable, and customizable column layouts, including hidable columns
  • Optional customizable column and row headers, including optionally wrapping header text
  • Columns that the user can resize and reorder at run time
  • Selection events
  • Ability to use a custom item renderer for any column
  • Support for paging through data
  • Locked rows and columns that do not scroll
This sample for modify color cell in datagrid and using action script,

The flex code for datagrid component :
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="getListDataBrg.send()">
<mx:HTTPService id="getListDataBrg" method="POST" showBusyCursor="true"
useProxy="false" url="http://localhost/projectDir/srv/myPHP.php"/>
<mx:DataGrid x="312" y="57" dataProvider="{getListDataBrg.lastResult.data.detail}">
<mx:columns>
<mx:DataGridColumn headerText="Item Code" dataField="kode" width="130"
itemRenderer="TextOrHTMLRenderer"/>
<mx:DataGridColumn headerText="Item Name" dataField="nama"/>
<mx:DataGridColumn headerText="Item Unit" dataField="unit"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>


This ActionScript for coloring cell in datagrid, TextOrHTMLRenderer.as :
package
{
import mx.controls.DataGrid;
import mx.controls.dataGridClasses.DataGridItemRenderer;
import mx.controls.dataGridClasses.DataGridColumn;

public class TextOrHTMLRenderer extends DataGridItemRenderer
{

public function TextOrHTMLRenderer()
{
super();
}

override public function validateProperties():void
{
super.validateProperties();
if (listData)
{
var dg:DataGrid = DataGrid(listData.owner);

var column:DataGridColumn = dg.columns[listData.columnIndex];
htmlText = data[column.dataField];

if (getStyle("plainText"))
{
text = text;
}
}
}

}

}

This PHP code for myPHP.php, this code used to setting color properties in HTML code :
<?
header('Content-Type: text/xml');
include('adodb/adodb.inc.php'); # load code common to ADOdb
$connectX = ADONewConnection('mssql'); # create a connection
$connectX -> Connect("yodi-it","USERNAME","PASSWORD",'DATABASENAME');

$databrg = $connectX->Execute("SELECT KDBRG,NMBRG,UNIT FROM TABLE_NAME");
$xml="<data>";
$xml.="<count>".$databrg->RecordCount()."</count>";
while(!$databrg->EOF)
{
if(trim($databrg->fields[0])=="A001")
{
$colorx="color='#000000'";
}
else
{
$colorx="color='#CFB004'";
}
$xml.="<detail>";
$xml.="<kode> <FONT $colorx >".trim($databrg->fields[0])."</FONT>
</kode>";

$xml.="<nama>".trim(str_replace('&','&',$databrg->fields[1]))."</nama>";
$xml.="<unit>".trim($databrg->fields[2])."</unit>";
$xml.="</detail>";
$databrg->MoveNext();
}
$xml.="</data>";
print($xml);
?>

Create simple external Action Script for HTTP Service

Flex developers can use ActionScript to extend the functionality of their Adobe® Flex™ applications. ActionScript provides flow control and object manipulation features that are not available in MXML. For a complete introduction to ActionScript and a reference for using the language, see Programming ActionScript 3.0 and ActionScript 3.0 Language Reference.

Flex developers can use ActionScript to implement custom behavior within their Flex applications. You first use MXML tags to declare things like the containers, controls, effects, formatters, validators, and web services that your application requires, and to lay out its user interface. Each of these components provides the standard behavior you'd expect. For example, a button automatically highlights when you roll over it, without requiring you to write any ActionScript. But a declarative language like MXML is not appropriate for coding what you want to happen when the user clicks a button. For that, you need to use a procedural language like ActionScript, which offers executable methods, various types of storage variables, and flow control such as conditionals and loops. In a general sense, MXML implements the static aspects of your application, and ActionScript implements its dynamic aspects.

ActionScript is an object-oriented procedural programming language, based on the ECMAScript (ECMA-262) edition 4 draft language specification. You can use a variety of methods to mix ActionScript and MXML, including the following:

  • Use ActionScript to define event listeners inside MXML event attributes.
  • Add script blocks using the tag.
  • Include external ActionScript files.
  • Import ActionScript classes.
  • Create ActionScript components.
This is simple code for create external Action Script for HTTP Service.

Code Action Script SrvHTTP.as


Flex Code for call the SrvHTTP.as like this :
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script source="SrvHTTP.as"/>
<mx:HTTPService id="validationLogin" method="POST" showBusyCursor="true" useProxy="false" url="{SrvHttp}/filePHP.php"/>
</mx:Application>

Friday, July 17, 2009

Simple Flex Effect Example

Open Flex Builder and go to File > New Project > Flex Project and name your project as MyEffects. In Design view take new Panel to the stage, set ID - mPanel , title – My Effects, Horizontal align – center, Vertical align – middle. Now inside this new panel, drag Image component. Set ID – mImage, scale content – true. Move to Category View for Image component, within Style choose center horizontalAlign and middle verticalAlign. Create assets folder inside your project, insert any image and for Image component, set Source for that image.

OK, we created our playground and we can open our box with toys. Let’s try Zoom effect first. Just below Application tag, insert Zoom tag like this:

< id="over" duration="100" zoomheightto="1.3" zoomwidthto="1.3">

Everything is simple here, but you also have to add another property inside Image tag:

rollOverEffect="{over}"

In this way we have made connection between two tags Image and Zoom with over ID. In the same way you can add rollOutEffect or any other like this:

< id="”out”" duration="200" zoomheightto="1" zoomwidthto="1"> and
rollOutEffect="{out}" as Image tag property.

You may notice different duration properties, which means, as you expected, that rollOut will last twice longer than rollOver. Insert another tag, Blur tag for mouseDownEffect:

< id="down" duration="1000">

In order to apply more than one effect on one action we need to use Parallel tag. If we put Zoom and Blur tags between Parallel tag, give new tag id – over while deleting Zoom and Blur id property. Something like this:

< id="over">
< duration="100" zoomheightto="1.3" zoomwidthto="1.3">
< duration="1000">
< /mx:Parallel >

Don’t forget also to delete mouseDown property or you will get an error. You can combine several effects for same action. It’s up to you to decide when is enough. You can choose between AnimateProperty, Blur, Dissolve, Fade, Glow, Iris, Move, Pause, Resize, Rotate, SoundEffect, Wipe, Zoom.




download source

Free sample code HTTP Service with PHP

Free sample code HTTP Service with PHP

This sample using Datagrid and HTTP Service. HTTP Service getting data from database with PHP.

Flex Code :
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="getListDataBrg.send()">
<mx:HTTPService id="getListDataBrg" method="POST" showBusyCursor="true" useProxy="false" url="http://localhost/kunci/srv/databrg.php"/>
<mx:DataGrid x="312" y="57" dataProvider="{getListDataBrg.lastResult.data.detail}">
<mx:columns>
<mx:DataGridColumn headerText="Item Code" dataField="kode" width="130"/>
<mx:DataGridColumn headerText="Item Name" dataField="nama"/>
<mx:DataGridColumn headerText="Item Unit" dataField="unit"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>


PHP code > databrg.php
<?
header('Content-Type: text/xml');
include('adodb/adodb.inc.php'); # load code common to ADOdb
$connectX = ADONewConnection('mssql'); # create a connection
$connectX -> Connect("yodi-it","USERNAME","PASSWORD",'DATABASENAME');

$databrg = $connectX->Execute("SELECT KDBRG,NMBRG,UNIT FROM TABLE_NAME");
$xml="<data>";
$xml.="<count>".$databrg->RecordCount()."</count>";
while(!$databrg->EOF)
{
$xml.="<detail>";
$xml.="<kode>".trim($databrg->fields[0])."</kode>";
$xml.="<nama>".trim(str_replace('&','&',$databrg->fields[1]))."</nama>";
$xml.="<unit>".trim($databrg->fields[2])."</unit>";
$xml.="</detail>";
$databrg->MoveNext();
}
$xml.="</data>";
print($xml);
?>

SQLite Example for Adobe AIR–Working with local SQL databases(with source code)

Adobe AIR includes the capability of creating and working with local SQL databases. Many stand SQL features are supported in the runtime, open source SQLite system can be used for storing local, persistent data.

The flollowing is a simplistic example that create a sqlite database, add, get, update and remove records from the “user” table.

Notice:
You might have wondered about this line:

  1. sqlConnection.openAsync(dbFile);

.Asychnronous means that your code will have an event listener on the SQLConnection and an event handler for the response.

.Synchronous means that your application will make an “inline” call to SQLite where it performs the operation and then moves on as if it were any other line of actionscript code.This tutorial is using the asynchronous method. :)


1. <?xml version="1.0" encoding="utf-8"?>
2. <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
3. preinitialize="openDatabaseConnection()"
4. fontSize="12" backgroundColor="#FFFFFF" width="600" height="700">
5. <mx:Script>
6. <![CDATA[
7. import flash.data.SQLConnection;
8. import flash.events.SQLErrorEvent;
9. import flash.events.SQLEvent;
10. import flash.filesystem.File;
11. private var conn:SQLConnection;
12. private var initComplete:Boolean = false;
13. private var sqlStat:SQLStatement;
14.
15. public function openDatabaseConnection():void{
16.
17. // create new sqlConnection
18. sqlConnection = new SQLConnection();
19. sqlConnection.addEventListener(SQLEvent.OPEN, onDatabaseOpen);
20. sqlConnection.addEventListener(SQLErrorEvent.ERROR, errorHandler);
21.
22. // get currently dir
23. var dbFile:File = File.applicationStorageDirectory.resolvePath("sampleDB.db");
24.
25. // open database,If the file doesn't exist yet, it will be created
26. sqlConnection.openAsync(dbFile);
27. }
28.
29. // connect and init database/table
30. private function onDatabaseOpen(event:SQLEvent):void
31. {
32. // init sqlStatement object
33. sqlStat = new SQLStatement();
34. sqlStat.sqlConnection = conn;
35. var sql:String = "CREATE TABLE IF NOT EXISTS user (" +
36. " id INTEGER PRIMARY KEY AUTOINCREMENT, " +
37. " name TEXT, " +
38. " password TEXT" +
39. ")";
40. sqlStat.text = sql;
41. sqlStat.addEventListener(SQLEvent.RESULT, statResult);
42. sqlStat.addEventListener(SQLErrorEvent.ERROR, createError);
43. sqlStat.execute();
44. }
45. private function statResult(event:SQLEvent):void
46. {
47. // refresh data
48. var sqlresult:SQLResult = sqlStat.getResult();
49. if(sqlresult.data == null){
50. getResult();
51. return;
52. }
53. datafiled.dataProvider = sqlresult.data;
54. }
55. // get data
56. private function getResult():void{
57. var sqlquery:String = "SELECT * FROM user"
58. excuseUpdate(sqlquery);
59. }
60. private function createError(event:SQLErrorEvent):void
61. {
62. trace("Error code:", event.error.code);
63. trace("Details:", event.error.message);
64. }
65. private function errorHandler(event:SQLErrorEvent):void
66. {
67. trace("Error code:", event.error.code);
68. trace("Details:", event.error.message);
69. }
70. // update
71. private function excuseUpdate(sql:String):void{
72. sqlStat.text = sql;
73. sqlStat.execute();
74. }
75. // insert
76. private function insertemp():void{
77. var sqlupdate:String = "Insert into user(id,name,password) values('" +
78. name.text +
79. "','" +
80. password.text +
81. "')";
82. debug.text+=sqlupdate+"\n"
83. excuseUpdate(sqlupdate)
84. }
85. // delete
86. private function deleteemp():void{
87. var sqldelete:String = "delete from user where id='" +
88. datafiled.selectedItem.id +
89. "'";
90. excuseUpdate(sqldelete);
91. debug.text+=sqldelete+"\n"
92. }
93. ]]>
94. </mx:Script>
95. <mx:TextArea x="21" y="10" width="402" height="179" id="debug"/>
96. <mx:DataGrid x="21" y="197" id="datafiled">
97. <mx:columns>
98. <mx:DataGridColumn headerText="ID" dataField="id"/>
99. <mx:DataGridColumn headerText="name" dataField="name"/>
100. <mx:DataGridColumn headerText="password" dataField="password"/>
101. </mx:columns>
102. </mx:DataGrid>
103. <mx:Form x="21" y="471">
104. <mx:FormItem label="name">
105. <mx:TextInput id="name"/>
106. </mx:FormItem>
107. <mx:FormItem label="password">
108. <mx:TextInput id="password"/>
109. </mx:FormItem>
110. </mx:Form>
111. <mx:Button x="300" y="503" label="add" click="insertemp()"/>
112. <mx:Button x="300" y="533" label="delete" click="deleteemp()"/>
113. </mx:WindowedApplication>