July 2008 - Posts
Ok, in my last post I tried to follow Mike J. Potter's tutorial on how to read data from PHP to Flex. He actually also tried to make an example of how to write data but he left some part out.
Ofcourse I'm still just trying out the examples, making some little twists wherever I feel like adding one. To get directly to the point, I modified the PHP file in his example as follow:
<?php
$host =
"localhost";
$username =
"root";
$password =
"";
$db_name =
"flextestdb";
$mysql_connection
= mysql_connect($host, $username, $password);
mysql_select_db($db_name);
$param_username =
$_POST["username"];
$param_password =
$_POST["password"];
$text =
$param_username . $param_password;
$query =
"INSERT INTO users_tbl(username, password) VALUES('$param_username',
'$param_password')";
if (
!mysql_query($query, $mysql_connection) ){
die('ERROR: '. mysql_error() );
}
echo "INSERT
SUCCESSFUL, 1 Record Added";
?>
Pretty straight-forward. Here's the MXML code:
<?xml
version="1.0" encoding="utf-8"?>
<!--
======================================================================
Aug 1, 2008 12:27:00 PM
======================================================================
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService
id="writeData" url="http://localhost/flextest/write.php" method="POST" resultFormat="text" result="resultHandler(event)"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
/*HTTPService result callback*/
public function resultHandler( event:ResultEvent ):void
{
Alert.show("Result " +
String( event.result ) );
}
/*Function to send over HTTP*/
public
function sendData():void
{
var validEntry:Boolean = !(usernameTxt.text
== "" || passwordTxt.text == "");
if (validEntry){
var
objSend:Object = new Object;
objSend.username =
usernameTxt.text;
objSend.password =
passwordTxt.text;
writeData.send(objSend);
}
else{
Alert.show("Username
and Password cannot be blank!");
}
}
]]>
</mx:Script>
<mx:Label x="10" y="10" text="Username:
"/>
<mx:TextInput x="100" y="10" id="usernameTxt"/>
<mx:Label x="10" y="50" text="Password:
"/>
<mx:TextInput x="100" y="50" id="passwordTxt"/>
<mx:Button x="10" y="100" id="sendButton" label="Send" click="sendData()"/>
</mx:Application>
I've heard about using CSS to aid in aligning your form. Yes, CSS in Flex. But I don't know how to do that yet so I'm sticking with hardcoded values. Above you will see that I tried to validate using a simple if check and the Alert class. Spket, sad to say, as of this point doesn't have support for Actionscript, that's why the Actionscript portion were all green... No code-completion feature even for the <mx:Script> tag.

The first time I tried to run the SWF file and click on the submit button I received an error saying:
[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: http://localhost/write.php"]. URL: http://localhost/write.php"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()
at mx.rpc::Responder/fault()
at mx.rpc::AsyncRequest/fault()
at DirectHTTPMessageResponder/errorHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/redirectEvent()
Make sure you put the correct url in your HTTPService to avoid this, and if you ever encouter it, you know what to do.
Once you try out the app, data successfully inserted into the MySQL table. You can check the output of the app (see my previous post) to verify that the record was indeed inserted. Next time, I'm gonna try to combine these two so they don't have to be two separate swf files.


main.swf (The result list)

Resources:
http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&productId=2&postId=7744&loc=en_US
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Boolean.html
Note: This post is not intended as a tutorial. I'm just sharing my own personal experience with learning FLEX.
Finally, I was able to sit down for a few hours and do some coding with Flex. Well, I didn't write my own code but I think it helps a lot when you type "most" of the code you copy(you don't have to code everything).
As a learner, I want to reduce as much roadblocks as I can. I want to learn and move forward. So I installed xampp which bundles Apache Webserver and MySQL. It also has PHPMyAdmin. I followed a tutorial from adobe which will teach you how to communicate with PHP. You can find it here.
I had an MXML editor but not a PHP editor so I encountered an error right-away.

XML Parser Failure, I knew right away that I forgot to close a tag that I'm printing through PHP's echo function. I modified the PHP source a bit for my own convenience.
<?php
//modified by Lamia, original code
written by Mike J. Potter
$host =
"localhost";
$username =
"root";
$password =
""; //MYSQL bundled with xampp uses an empty space as the default
password
$db_name =
"flextestdb";
$mysql_connection
= mysql_connect($host, $username, $password);
mysql_select_db($db_name);
$query =
"SELECT * FROM users_tbl";
$result =
mysql_query($query);
echo
"<people>";
while ( $row =
mysql_fetch_object($result) ){
echo "<person>";
echo "<userid>" .
$row->user_id . "</userid>" ;
echo "<username>" .
$row->username . "</username>";
echo "<password>" .
$row->password . "</password>";
echo "</person>";
}
echo
"</people>";
?>
The database, the table name and field names are different since I wanted to adhere to my personal way of naming them. Below is the output of the above code. I included the browser output and the HTML source.

If you're working from a blank mxml project in Spket IDE, try pressing ctrl + space to bring-up the code-assist window and type "A", select Application and the mxml skeleton should be generated for you.

Original MXML code written by Mike J. Potter
<?xml
version="1.0" encoding="utf-8"?>
<!--
======================================================================
Jul 30, 2008 2:23:46 PM
======================================================================
-->
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="rest_service.send()">
<mx:HTTPService id="rest_service" url="http://localhost/flextest/rest.php"/>
<mx:DataGrid left="0" right="0" bottom="0" top="0" dataProvider="{rest_service.lastResult.people.person}">
<mx:columns>
<mx:DataGridColumn headerText="Id" dataField="userid"></mx:DataGridColumn>
<mx:DataGridColumn headerText="Username" dataField="username"></mx:DataGridColumn>
<mx:DataGridColumn headerText="Password" dataField="password"></mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
</mx:Application>
And for some nice FLEX application. :)

I tried to create a simple batch program to help me in compiling.
[code]
del *.swf
mxmlc main.mxml
[code]
In the future, I'll try to see if this can be done with Ant.

Thanks to Mike J. Potter for the wonderful tutorial at the adobe website.
Installing the Flex SDK
If you haven't downloaded the Flex SDK yet, go to the adobe website. Installing it is just a matter of extracting the zip file to your preferred directory(mine is in C:\flexSDK\bin). If you want to be able to compile from the command line, right click my computer, click on the Advance tab, then Environment Variables. Create a new system variable and put FLEX_HOME as the variable name, the location of your SDK(e.g. C:\Applications\flexSDK) as the value. Click ok. Look for the "Path" variable and click edit. At the end of the path variable value, put the following w/out the quotation marks, ";%FLEX_HOME%". Click ok until all windows are closed. You should be ready to go now. Go to your command line and type "mxmlc", if you see something like:
Adobe Flex Compiler (mxmlc)
Version 3.0.0 build 477
Copyright (c) 2004-2007 Adobe Systems, Inc. All rights reserved.
mxmlc [options] [defaultVar]
Use 'mxmlc -help' for more information.
It means you did it right.
Installing the Spket IDE, eclipse plugin
Note: Spket IDE flex editor is still in its early stage.
I was browsing for an alternative flex code editor(i.e. aside from Flex Builder) and I found spket IDE which is currently on version 1.6.12. I only needed to download the Eclipse plugin since I already have Eclipse(3.4.0) installed on my machine. I first made sure that I'm currently not running Eclipse, thenI extracted the zip file. Now, there should be a plugin and features folders. Browse inside those two directories and copy-paste the contents into your eclipse folder's features and plugin directories respectively.
Once done, open Eclipse and go to window->preferences and a new window will open. Collapse sa Spket tree, click on Flex SDK and specify your Flex SDK directory. Mine is in C:\flexSDK\. Change to the spket perspective as shown in the image below.

In an empty workspace, create a new project, under general, just select "Project". Name the project anything you want, I named mine "FlexTest". Create a new file, name it test.mxml (or whatever you like, as long as it ends with mxml). From here on, it's up to you to play with it. :)
Some notable pros and cons for this release:
Pros:
1. Very powerful code-completion feature
2. Drag and drop feature(look for the snippets window)
3. Free for non-commercial use
Cons:
1. No Flex compiler as of now
2. No visual designer
3. No Flex project support
4. No Flex file template available
Right now, the cons still a little outweigh the pros. All-in-all, it's still just an editor and you probably have to compile from the commandline. I'm looking forward to seeing improvements with this product.
Until next time 
Bored. That's the best way to describe my feelings right now. I've
had a chat with my "sensei" this morning and he told me that he noticed
my lack of enthusiasm. I agree with him, it's been sometime since I've
felt very anthusiastic about the work I do. I don't think I'll ever
like doing maintenance work, really... I've been adding a lot of stuff
as I fix bugs along the way (refactor, fancy comments, understanding
the business flow) and though they might prove beneficial they still
don't as much excitement when I'm doing development work. But since I'm
developing myself to be more proactive, I've decided this day to put
these braincells into work and search for a particular technology that
I haven't had any experience with before.
RIA... Those three
letters ring a bell! Yes, and I've chosen Adobe Flex to be my
technology of choice. I just downloaded the Flex SDK and I'm very
excited to go home and try this). No, I promise I won't spend too much
time with my PSP tonight. :)
I started out by looking at an application built with Flex.
http://examples.adobe.com/flex2/inproduct/sdk/flexstore/flexstore.html
Then, for an overview... I wanted to understand what I needed, and similar things with server-side language, Flex could do.
http://www.visualbuilder.com/flex/tutorial/
I'm hoping to push forward and write my first flex program with this tutorial here...
http://www.petefreitag.com/item/490.cfm