<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
   <title>Comtaste Consulting | Enterprise RIA consulting and development</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/" />
   <link rel="self" type="application/atom+xml" href="http://blog.comtaste.com/atom.xml" />
   <id>tag:blog.comtaste.com,2011://1</id>
   <updated>2010-12-27T16:23:46Z</updated>
   <subtitle>Enterprise RIA development and consulting with Adobe Flex 3, LiveCycle Data Services, Flex Data Services, Actionscript 3, Java and J2EE</subtitle>
   <generator uri="http://www.sixapart.com/movabletype/">Movable Type 3.33</generator>

<entry>
   <title>Getting started with the Tabbed UI and List View in Android 2.1 SDK</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/12/tabbed_ui_and_list_view_in_and.html" />
   <id>tag:blog.comtaste.com,2010://1.129</id>
   
   <published>2010-12-27T15:40:08Z</published>
   <updated>2010-12-27T16:23:46Z</updated>
   
   <summary>We&apos;ve officially started developing under Android development with Flex/AIR for mobile. In the meantime I&apos;ve investigated into the native Android development using Java and the Android SDK. In this post I would like to share with you my experience and...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Android" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="267" label="Activity" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="254" label="Android" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="265" label="TabList" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="263" label="TabView" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[We've officially started developing under Android development with Flex/AIR for mobile. In the meantime I've investigated into the native Android development using Java and the Android SDK. 
 In this post I would like to share with you my experience and show you how to create an Android application that makes use of the Tabbed UI and the ListView.
 
For this example I'm using the Android SDK 2.1 with a Motorola Droid 2 device for testing activities.  

Let's see how to develop a simple tab menu.
 
<u>Tabbed UI</u>

To create a Tab menu it’s necessary to define a TabHost Object. This object is the root class for a tab menu and it uses a tabWidget object to show the navigation buttons, and a Framelayout Object to show the tabs content.
 
 Now we are going to see how to create a simple TabView using separated Activities for the contents of the tabs.The Activity class is the base class of all Android’s applications  and it's  is used to perform actions.
We can have several Activities in our Apllications but the user can interact with them one at a time.

The first step is to define two Activities for the Tabs’ context; for example we can use the class below:


<pre class="brush: java">
package com.comtaste.android;
import com.comtaste.android.components.PersonListAdapter;
import android.app.ListActivity;
import android.os.Bundle;
/***
 * 
 * @author Luca Florido
 *
 *	This Activity is an example to build a ListView in Android 
 */
public class SelectView extends ListActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
	/***
	 * This method is called every time the activity 
	 * is change is state (see the Android's guide for 
	 * understand the lifecycle of an Activity )
	 */
	@Override
	protected void onResume() {
		super.onResume();
		try{
			if (getListAdapter() == null ){
				int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
				setListAdapter(new 
                                 PersonListAdapter(getApplicationContext(),displayWidth));
			}else{
				PersonListAdapter p = (PersonListAdapter)getListAdapter();
				p.refresh();
			}
		}catch(Exception e ){
			e.printStackTrace();
        }
		
	}
    
}
</pre>





<pre class="brush: java">
package com.comtaste.android;

import com.comtaste.android.datamanage.EngineDB;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
/***
 * 
 * @author Luca Florido
 *
 */
public class InsertView extends Activity {
	private EditText nameED;
	private EditText surnameED;
	private EngineDB db;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = new EngineDB(getApplicationContext());
        setContentView(R.layout.inserview);
        db = new EngineDB(getApplicationContext());
		nameED = (EditText)this.findViewById(R.id.insertName);
		surnameED = (EditText)this.findViewById(R.id.insertSurname);
		Button buttonIns = (Button)this.findViewById(R.id.buttoninsert);
		buttonIns.setWidth(100);
		resize();
		buttonIns.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!nameED.getText().toString().equals("")  && !surnameED.getText().toString().equals("") ){
					db.insert(nameED.getText().toString(), surnameED.getText().toString());
					nameED.setText("");
					surnameED.setText("");
					nameED.requestFocus();
				}
				
				
			}
		});
	}
	public void resize(){
		int wd = getWindowManager().getDefaultDisplay().getWidth();
		nameED.setWidth(wd-100); 
		surnameED.setWidth(wd-100);
	}
}
</pre>

The second step is to define the view objects in an xml file and put it in the layer directory of the Android project   ( in my example I use a file called tabview.xml). Declare the following objects into the xml file: the tabWidget and the FrameLayout Objects within  a LinerLayout with vertical orientation as show below.  

<pre class="brush: xml">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;TabHost
  android:id="@android:id/tabhost"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  &lt;LinearLayout android:orientation="vertical"
	  android:layout_width="fill_parent"
	  android:layout_height="fill_parent"
	  >
	  &lt;TabWidget android:id="@android:id/tabs"
	  	android:layout_width="fill_parent"
	  	android:layout_height="wrap_content">
	  &lt;/TabWidget>
	  &lt;FrameLayout
	  	android:id="@android:id/tabcontent"
	  	android:layout_width="fill_parent"
	  	android:layout_height="wrap_content">
	  &lt;/FrameLayout>
	  &lt;Button
		android:id="@+id/closebutton"
	  	android:layout_width="100px"
	  	android:layout_height="wrap_content"
	  	android:text="@string/close"
	  	android:drawableLeft="@drawable/closeicon">
	  &lt;/Button>
  &lt;/LinearLayout>
&lt;/TabHost>
</pre>


 	Now create the Activity for the TabView. The Android’s SDK provides us a particular type of Activity for manage the tab View:  the TabActivity class.We can extend  the TabActivity class:

<pre class="brush: java">
package com.comtaste.android;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.view.View.OnClickListener;
/***
 * 
 * @author Luca Florido
 *
 * In this Activity there are all the configurations of the TabHost Object
 */
public class MenuView extends TabActivity   {
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tabview);
		/***
		 * Resource 
		 */
		Resources res = getResources(); 
		/***
		 *  Create and Initialize a TabHost Object with two TabSpec 
		 */
		TabHost tab = getTabHost();		
		TabHost.TabSpec spec;
		/***
		 * Create an Intent for the Activity in the first tab
		 */
		Intent intent;
		intent = new Intent().setClass(this, SelectView.class);
		/***
		 * Creation of the first tab
		 */
		spec = tab.newTabSpec("List").setIndicator("List",res.getDrawable(R.drawable.cancelicon));
		spec.setContent(intent);
		/***
		 * Adding of the first tab to the TabHost Object 
		 */
		tab.addTab(spec);
		/***
		 * Container of the Activity in the second tab
		 */
		intent = new Intent().setClass(this, InsertView.class);
		/***
		 * Creation of the second tab
		 */
		spec = tab.newTabSpec("Insert").setIndicator("Insert",res.getDrawable(R.drawable.inserticon));
		spec.setContent(intent);
		/***
		 * Adding of the second tab to the TabHost Object 
		 */
		tab.addTab(spec);
		/***
		 * Add a Listener to the Close Button  
		 */
		Button closeB = (Button)findViewById(R.id.closebutton); 
		closeB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
}
</pre>

In the onCreate() method we have to create an instance of the TabHost class with the method  getTabHost() of the TabActivity object.
.
 
Then, for each tab, a TabHost.TabSpec has to be created to define the tab properties such as title,icon and content.
 
With the newTabSpec(String) method we create a new TabHost.TabSpec identified by the given string tag and with the setIndicator(CharSequence, Drawable)method we can set the text and icon for the tabs. In order to add the View Activity  to each tabs it’s necessary  to use the   setContent(Intent) method where the argument  Intent is a particular object that help us to call the appropriate Activity for each tabs.
 
Now in the next step you'll add the tabs to our TabHost by calling the method addTab(TabHost.TabSpec).
 
Notice that the TabWidget object has never been istantiated. This is because a TabWidget must always be a child of a TabHost, which is what you use for almost all interaction with the tabs.
 
So when a tab is added to the TabHost, it's automatically added to the child TabWidget.
 
<u>ListView</u>

A ListView is a ViewGroup that creates a list of scrollable items. The list items are automatically added to the list using a ListAdapter.
 
In this example I'm going to show you how to create a ListView using a custom ListAdapter.
 
Suppose that we have to represent a particular type of Data inside our List. For example we can use a DTO like this:
 

<pre class="brush: java">
package com.comtaste.android.dataVO;
/***
 * 
 * @author Luca Florido
 *
 */
public class Person {
	public Person(){
		
	}
	public Person(String nameValue,String surnameValue ){
		this.name = nameValue;
		this.surname = surnameValue;
	}
	public String name;
	public String surname;
}
</pre>

Now we have to define a custom ListAdapter that is able to show the parameters of  Person’s Objects inside a List Collection (for example an ArrayList).
 
We still need two elements to show  data within a Person object 
in a right way.
 
First we need a View Container (in our example PersonView) to draw a view where we can put the values, and a button for making operations in the Collection ( for example to delete the selected data from the listcollection).
 
Second, we need a custom ListAdapter to fill the listView with PersonView Objects filled with the items inside our Collection.
  
Define a Container for the Data view. The personView object   is a simple LinearLayout class where we define the view’s objects  (as you can see in its constructor ) and a Person object  filled by the PersonListAdapter.

<pre class="brush: java">
package com.comtaste.android.components;
import com.comtaste.android.R;
import com.comtaste.android.dataVO.Person;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/***
 * 
 * @author Luca Florido
 *
 * View that contains objects to show in the list all the properties of a Person Object
 */
public class PersonView extends LinearLayout {
	public Button buttonDel;
	public Person person;
	/***
	 * 
	 * @param context Context of the application
	 * @param p Person object
	 * @param displayWidth Width of the screen
	 */
	public PersonView(Context context, Person p,int displayWidth){
		super(context);
		this.setOrientation(HORIZONTAL);
		person = p;
		TextView titleName = new TextView(context);
		TextView valueName = new TextView(context);
		TextView titleSurName = new TextView(context);
		TextView valueSurName = new TextView(context);
		titleName.setText("NAME:");
		titleName.setWidth(200);
		valueName.setText(p.name);
		titleSurName.setText("SURNAME");
		valueSurName.setText(p.surname);
		LinearLayout main = new LinearLayout(getContext());
		titleName.setWidth(displayWidth-100);
		main.setOrientation(VERTICAL);
		main.addView(titleName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(valueName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(titleSurName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(valueSurName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		addView(main, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		buttonDel  = new Button(context);
		buttonDel.setText("Delete");
		buttonDel.setWidth(100);
		Resources res = getResources();
		buttonDel.setBackgroundDrawable(res.getDrawable(R.drawable.cancelicon));
		addView(buttonDel,new LinearLayout.LayoutParams(100,LayoutParams.WRAP_CONTENT));
	}
	
}
</pre>

Now create a ListAdapter. The PersonListAdapter is an extension of BaseAdapter class that contains all the methods required by theListActivity to draw a List of Object. Below you can see the code of the PersonListAdapter.

<pre class="brush: java">
package com.comtaste.android.components;
import java.util.ArrayList;
import java.util.List;
import com.comtaste.android.dataVO.Person;
import com.comtaste.android.datamanage.EngineDB;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.view.View.OnClickListener;
/***
 * 
 * @author Luca Florido
 *	
 */
public class PersonListAdapter extends BaseAdapter {
	private Context myContext;
	public List<Person> personList;
	private Person person;
	private EngineDB db;
	private int dWidth;
	public PersonListAdapter (Context context,int displayWidth){
		myContext = context;
		dWidth = displayWidth;
		db = new EngineDB(myContext);
		personList = new ArrayList<Person>();
		personList = db.selectList();
	}
	public int getCount(){
		return personList.size();
	}
	public Object getItem(int position) {
        return position;
    }
	public long getItemId(int position) {
        return position;
    }
	/***
	 * Create the View Objects to show in the UI
	 */
	public View getView(int position,View convertView, ViewGroup parent){
		person = personList.get(position);
		//Create a new PersonView object 
		PersonView personView = new PersonView(myContext, person,dWidth);
		//Define a method to delete a Person object from the List Collection
		personView.buttonDel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EngineDB db = new EngineDB(myContext);
				PersonView per= (PersonView)v.getParent(); 
				db.delete(per.person);
				refresh();
			}
		});
		return personView;
	}
	public void refresh(){
		personList = new ArrayList<Person>();
		personList = db.selectList();
		notifyDataSetChanged();
	}
}
</pre>
 
In the constructor of the class we call a method that is able to create a List of Persons from a SQLLite database. In the getView() method a PersonView Object is created and filled with an object of the Person Collection.
 
For each position from 0 to the integer value of  getCount()  method ( the value of this method is the size of the Collection of Persons) the getView() method is called.
 
Then define the ListActivity.
 
Here is the ListActivity class that we configure as a tab of the TabHost of the section about the tabbed UI (see above)
 
 
Note that in the onResume() method of that Activity I've put some operations to refresh the Person Objects Collection and the List.
 
Doing that I can refresh my List every time a user clicks on the List Tab.
      
That’s all.
Regards


]]>
      
   </content>
</entry>
<entry>
   <title>New video on Comtaste Homepage</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/09/new_video_on_comtaste_homepage.html" />
   <id>tag:blog.comtaste.com,2010://1.127</id>
   
   <published>2010-09-29T10:34:26Z</published>
   <updated>2010-10-06T09:13:55Z</updated>
   
   <summary>Today we just released a brand new company video showcase on our site. The introduction of this video is the first step of a progressive whole site-redesign.</summary>
   <author>
      <name>Matteo Ronchi</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
         <category term="Events" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="260" label="comtaste" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="261" label="showcase" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="259" label="video" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Today we just released a brand new company video showcase on our site. The introduction of this video is the first step of a progressive whole site-redesign. We, in Comtaste, think it's a good habit keep our website up to date and in line with the direction we are aiming at. 
Now it's time for you to have a look at this <a href="http://www.comtaste.com" target="_blank">great video</a>.
To enjoy the video properly, remeber to turn the sound up.
Keep in touch with us, other improvements will come very soon!]]>
      
   </content>
</entry>
<entry>
   <title>How to install the Android SDK on Eclipse 3.5</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/09/how_to_install_the_android_sdk.html" />
   <id>tag:blog.comtaste.com,2010://1.126</id>
   
   <published>2010-09-20T10:50:28Z</published>
   <updated>2010-09-20T15:40:30Z</updated>
   
   <summary>In this post you&apos;ll learn to get started with the Android SDK (version 2.1, installing it, and set up a development environment based on Eclipse 3.5 Galileo with the Android Development Tool Plugin. First of all you have to check...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Android" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="254" label="Android" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="256" label="Eclipse" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="258" label="Galileo" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In this post you'll learn to get started with the Android SDK (version 2.1, installing it, and set up a development environment based on Eclipse 3.5 Galileo with the Android Development Tool Plugin.



First of all you have to check if your environments fits all the requirements.



Here is a link with all the software and hardware requirements for developing applications with the Android SDK:

<a href="http://developer.android.com/sdk/requirements.html">http://developer.android.com/sdk/requirements.html</a>

If it's all right in your computer , go ahead with instaling the Android SDK. 

After downloading the Android SDK starter package from this <a href="http://developer.android.com/sdk/index.html">link</a>  (make sure to download the right package for your computer), unpack it in a folder and take a note of the name and location of your SDK directory. It's important in order to complete the installation of the ADT Eclipse plugin.



It's a good idea to insert in the Path environment variables of your computer the tools directory of the SDK, in this way it's possible to run all the commands in that directory without referring to the full path.



Now it's time to install the ADT plugin for eclipse.

This plugin is the fastest way to get started with Android SDK because it has a lot of functionalities for make easier the startup and the manage of any Android projects.



For using this plugin within Eclipse (I'm using the 3.5 version, but you can use the 3.4 though. Instead for the 3.6 version the plugin doe not exist) follow these steps to download the ADT plugin:



1. Open Eclipse. From the Help menu choose “Install New Software”

2. In the Available Software dialog, click Add....

3. In the Add Site dialog  enter a name for the remote site in the "Name" field, and in the "Location" field, 

       enter this URL:

    

   https://dl-ssl.google.com/android/eclipse/ (if you have problem with https you can use http)



4. And Click OK.



5. Back in the Available Software view, you should now see "Developer Tools" item added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development    Tools. Click Next.



6. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed.    Click Next to read and accept the license agreement and install any dependencies, then click Finish.



7.  Restart Eclipse.



If the installation finish successfully,we can modify the ADT preferences in Eclipse to point to the Android SDK directory:



1- Select Window > Preferences... to open the Preferences panel.

2- Select Android from the left panel.

3- For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory.

4- Click Apply, then OK.







The SDK uses a modular structure that separates the major parts of the SDK — Android platform versions, add-ons, tools, samples, and the API documentation — into a set of separately installable components. 

The SDK starter package, which you've already downloaded, includes only a single component: the latest version of the SDK Tools. To develop any Android application, you also need to download at least one Android platform into your environment, although downloading additional components is highly recommended. 



Next time we will see how to install and update additional components and write our first "Hello World" application


]]>
      
   </content>
</entry>
<entry>
   <title>Fixing the horizontal scroll for the Flex Text Highlighter Class</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/08/fixing_the_horizontal_scroll_f.html" />
   <id>tag:blog.comtaste.com,2010://1.125</id>
   
   <published>2010-08-03T15:45:47Z</published>
   <updated>2010-08-03T16:24:02Z</updated>
   
   <summary>Recently I happened to have to implement a textarea to highlight the research done inside a textarea. For this I found an excellent library that was just in my case: Flex Text Highlighter Class. But if you turn wordwrap on...</summary>
   <author>
      <name>Liviu Stoica</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Recently I happened to have to implement a textarea to highlight the research done inside a textarea. For this I found an excellent library that was just in my case: <a href="http://tom-lee.blogspot.com/2007/01/update-flex-text-highlighter-class.html">Flex Text Highlighter Class</a>.
But if you turn wordwrap on the textarea and horizontal scroll appears that the library was unable to move to different results.
Then download this example you will find the library clean by this bug.

<a href="http://www.comtaste.com/demo/blog/HighlighterDemo/HighlighterDemo.html">Demo</a> --- <a href="http://www.comtaste.com/demo/blog/HighlighterDemo/srcview/index.html">Source</a>]]>
      
   </content>
</entry>
<entry>
   <title>Adobe Alchemy: a comparative example</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/adobe_alchemy_a_comparative_ex.html" />
   <id>tag:blog.comtaste.com,2010://1.124</id>
   
   <published>2010-07-12T15:36:04Z</published>
   <updated>2010-08-27T09:37:09Z</updated>
   
   <summary><![CDATA[In my last post I introduced the Alchemy Project and I explained how to install/set up the Alchemy environment on a Window machine to compile a very simple &quot;c&quot; file in a swc. Today I'll go deeper and talk about...]]></summary>
   <author>
      <name>Luca Galati</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="226" label="c" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="227" label="c++" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="1" label="test" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my last <a href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html">post</a> I introduced the Alchemy Project and I explained how to install/set up the Alchemy environment on a Window machine to compile a very simple &quot;c&quot; file in a swc. 
Today  I'll go deeper and talk about Alchemy through a comparative example:  Alchemy aimes to allow users to take advantage of efficient C/C++ (existing or not) designed to accomplish very cpu-intensive tasks. The performance improvements of flex applications can be very significant e I'll try to give you a sample, with a simple test: I've implemented an inefficient and decidedly didactic ordering algorithm, the <a href="http://en.wikipedia.org/wiki/Bubble_sort">BubbleSort</a>, either in Actionscript and in C/Alchemy. Then I've tested both implementation to order an actionscript reverse ordered array of integers with 20,000 elements(the worst case for the bubblesort algorithms). 

Here is the Actionscript implementation:

<pre class="brush: as3">
public function bubbleSort(array:Array):void
{
	var temp:int = 0;
	var alto:int = array.length;
	while(alto &gt; 0)
	{
		for(var i:int = 0; i&lt;alto; i++)
		{
			if(array[i] &gt; array[i+1])
			{
				temp = array[i];
				array[i] = array[i+1];
				array[i+1] = temp;
			}
		}
		alto--;
	} 
}
</pre>

and here I show you the C implementation

<pre class="brush:cpp">
void BubbleSort(int *array, int array_size)
{
   
  int i, tmp;
  int bound = array_size; 
 
  while (bound &gt; 1)
  {
	for (i=0; i&lt;bound-1; i++)
    {
        if (array[i] &gt; array[i+1]) 
        { 
			tmp = array[i]; 
            array[i] = array[i+1]; 
            array[i+1] = tmp;
        } 
    }
    bound--; 
  }
}
</pre>

Unfortunately I couldn't use the C implementation as it is. I needed to write some more code using Alchemy actionscript/C Api to realize the translation of the Actionscript array to the C integer array data structure:

<pre class="brush:cpp">
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include &quot;AS3.h&quot;
 
//INSERT HERE THE C IMPLEMENTATION OF THE BUBBLESORT ALGORITHM
 
static AS3_Val orderArray(void* self, AS3_Val args)
{
	//Creating a C representation of the Actionscript Array object
	AS3_Val actionscript_array = NULL;
	AS3_ArrayValue( args, &quot;AS3ValType&quot;, &amp;actionscript_array );
	 
	/*
	 *         Translation process from Actionscript to C in 4 steps:
	 */
	//STEP 1 : calculating the dimension of the Actionscript array
	AS3_Val actionscript_array_size =  AS3_GetS(actionscript_array, &quot;length&quot;);
	int array_size = AS3_IntValue(actionscript_array_size);
 	
	//STEP 2: declaring the C array to use with BubbleSort
	int array_c[array_size];
 	
	//STEP 3 : ActionScript function pop() of Array Class
	AS3_Val pop_function = AS3_GetS(actionscript_array, &quot;pop&quot;);
	AS3_Val emptyParams = AS3_Array(&quot;&quot;);
 	
	//STEP 4(iterative): Extracting the actionscript integer values from the actionscript array
	//and storing them into the c array
	int i = 0;
	for(i = array_size-1; i &gt;= 0 ; i--)
	{
		AS3_Val temp_actionscript_Int = AS3_Call(pop_function, actionscript_array, emptyParams);
		int tmp = AS3_IntValue(temp_actionscript_Int);
		array_c[i] = tmp;
		AS3_Release(temp_actionscript_Int);
	}
	AS3_Release(pop_function);
	/*
	 *   END of Translation process from actionscript to C
	 */
 	
	/*
	 *      Ordering operations: invoking the Bubble Sort on the c array of integers
	 */
	BubbleSort(array_c, array_size);
 	
	/*
	 *         Translation process from C to actionscript:
	 */
 	 
	//ActionScript function push() of Array Class
	AS3_Val push_function = AS3_GetS(actionscript_array, &quot;push&quot;);
 	
	//Storing the ordered integer values into a new actionscript array object
	int j;
	for( j = 0; j &lt; array_size ; j++)
	{
		AS3_Val int_to_push = AS3_Array(&quot;IntType&quot;, array_c[j]);
		AS3_Call(push_function, actionscript_array, int_to_push );
		AS3_Release(int_to_push);
	}
	AS3_Release(push_function);
 	
	return actionscript_array;
	/*
	 *   END of Translation process from C  to actionscript
	 */
}
 
//entry point for code
int main()
{
	//define the methods exposed to ActionScript
	//typed as an ActionScript Function instance
	AS3_Val orderArrayMethod = AS3_Function( NULL, orderArray );
 
	// construct an object that holds references to the functions
	AS3_Val result = AS3_Object( &quot;orderArray: AS3ValType&quot;, orderArrayMethod );
 
	// Release
	AS3_Release( orderArrayMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}
</pre>

As a consequence, when analyzing the test results, we have to consider the extra work the C/Alchemy implementation of the algorithm did to realize the ordering task.

To compile the previous code follow the instruction I showed in this <a href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html">post</a>
to obtain a file .swc you can use in a flex test application as I did in may test example.

Here the code of my flex test application:

<pre class="brush: as3">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;horizontal&quot; creationComplete=&quot;init();&quot;&gt;
	
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import mx.collections.ArrayCollection;
			
			import cmodule.bubblesort.CLibInit;			
			
			private var startDate:Date;
			private var stopDate:Date;
			
			private function init():void
			{
				
				this.addEventListener(&quot;actionscriptSortComplete&quot;,handler);
				this.addEventListener(&quot;cSortComplete&quot;,handler);
				var intArray:Array = new Array();
				var intArray2:Array = new Array();
				for(var i:int = 20000; i &gt; 0; i--)
				{
					intArray.push(i);
					intArray2.push(i);
				}
				list.dataProvider = intArray;
				list2.dataProvider = intArray2;
			}
			
			
			//INSERT HERE THE CODE OF THE ACTIONSCRIPT IMPLEMENTATION OF BUBBLESORT ALGORTHM
			
			public function orderArray(event:Event):void
			{
				startDate = new Date;
				
				if(event.target.id == &quot;actionscriptOrderingButton&quot; )
				{
					var source1:Array = (list.dataProvider as ArrayCollection).source;
					bubbleSort(source1);
					this.dispatchEvent(new Event(&quot;actionscriptSortComplete&quot;));
				}
				else
				{
					var loader:CLibInit = new CLibInit();
					var lib:Object = loader.init();
					var source2:Array = (list2.dataProvider as ArrayCollection).source;
					list2.dataProvider = lib.orderArray(source2);
					this.dispatchEvent(new Event(&quot;cSortComplete&quot;));
				}
				
				
			}
			
			public function handler(event:Event):void
			{
				stopDate = new Date();
				var diff:Number = stopDate.getTime() - startDate.getTime();
				if(event.type == &quot;actionscriptSortComplete&quot;)
				{
					timeLabel.text = &quot;time elapsed : &quot;+diff/1000+&quot; sec!&quot;;
					(list.dataProvider as ArrayCollection).refresh();
				}
				else
				{
					timeLabel2.text = &quot;time elapsed :&quot;+diff/1000+&quot;sec!&quot;;
					(list2.dataProvider as ArrayCollection).refresh();
				}
				
			}
			
		]]&gt;
	&lt;/mx:Script&gt;
	
	&lt;mx:List id=&quot;list&quot; width=&quot;30%&quot;  /&gt;
	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;actionscriptOrderingButton&quot; label=&quot;Actionscript BubbleSort&quot; click=&quot;orderArray(event);&quot;  /&gt;
		&lt;mx:Label id=&quot;timeLabel&quot; text=&quot;...&quot; /&gt;
	&lt;/mx:VBox&gt;
	&lt;mx:List id=&quot;list2&quot; width=&quot;30%&quot;/&gt;
	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;cOrderingButton&quot; label=&quot;C BubbleSort&quot; click=&quot;orderArray(event);&quot;  /&gt;
		&lt;mx:Label id=&quot;timeLabel2&quot; text=&quot;...&quot; /&gt;
	&lt;/mx:VBox&gt;
	&lt;mx:Label id=&quot;lb2&quot; text=&quot;&quot; /&gt;
	
	
&lt;/mx:Application&gt;
</pre>

And here are some screenshots of the results obtained by the test application:
<img alt="test-actionscriptbubblesort.PNG" src="http://blog.comtaste.com/test-actionscriptbubblesort.PNG" width="553" height="202" />

<img alt="test-cbubblesort.PNG" src="http://blog.comtaste.com/test-cbubblesort.PNG" width="505" height="203" />

To order an array of 20,000 integers in the worst case:
- the actionscript algorithm spent : 32.031 sec
- the Alchemy/C algorithm spent : 7 sec
Using the Alchemy/C implementation of bubblesort I got an improvement in speed of about 75%.
This is certainly an encouraging result and an evidence that Alchemy can be exploited by developers to improve performance of the most intensive task executed by their flex application.
]]>
      
   </content>
</entry>
<entry>
   <title>Managing Java Http sessions in GAE applications</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/managing_session_data_in_gae_a.html" />
   <id>tag:blog.comtaste.com,2010://1.121</id>
   
   <published>2010-07-08T09:27:34Z</published>
   <updated>2010-07-08T23:51:02Z</updated>
   
   <summary>When a J2EE developer starts the design of a Google App Engine application he has to face some problems and adapts some of the well-established design patterns in web application development. Let&apos;s start with a bit of introduction to explain...</summary>
   <author>
      <name>Emanuele Tatti</name>
      <uri>http://www.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[When a J2EE developer starts the design of a Google App Engine application he has to face some problems and adapts some of the well-established design patterns in web application development. Let's start with a bit of introduction to explain what is a Google App Engine application. 

<h3>What is Google App Engine</h3>

Citing the corresponding google <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html">page</a>: "Google App Engine lets you run your web applications on Google's infrastructure. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it's ready to serve your users."
Basically Google App Engine is a service that lets you put your application "in the cloud", a cloud completely managed by Google, so you don't have to worry about the scalability or reliability of your application. Every request made to a page of your application will be managed by one of the server in this infrastructure, but no one can guarantee that the next request will be assigned to that machine as well.

<h3>How the http session is managed</h3>
Session handling must be explicitly enabled by adding to your app engine configuration file <em><sessions-enabled>true</sessions-enabled></em> and then you will be able to access the session from within RPC services with:

<pre class="brush:java">
this.getThreadLocalRequest().getSession();
</pre>

When you enable it, you will find serialized sessions among your datastore entities as <em>_ah_SESSION</em>, this is due to the fact that "the cloud" will read and write sessions from and to the datastore, and not from and to memory as the J2EE specification states (excluding an application deployed on a cluster).
Every time the HttpSession setAttribute method is invoked, the related datastore entity is updated and every subsequent invocation to the related getAttribute method will return the same object, as you would expect from a standard web application. The problem is when your services manipulate objects stored in the session, in that case your changes will be lost when another service will get the object from the session. A very simple sample:

<strong>Service A</strong>

<pre class="brush:java">
Person p = new Person();
p.setName("Jack");
session.setAttribute("person", p);
</pre>

<strong>Service B</strong>

<pre class="brush:java">
Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack"
p.setName("Andy");
</pre>

<strong>Service A again</strong>

<pre class="brush:java">
Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack" in GAE, 
// prints "Andy" in a standard J2EE evironment
</pre>

If you want a consistent behaviour you need to invoke setAttribute again after having modified the Person object in the session. This workaround will solve all the inconsistencies but has a pretty important trade-off, every setAttribute will trigger a new serialization and write to the datastore; ok, you are in the Google cloud, but the free resources are limited.  

<h3>Alternatives to the http session</h3>

There are a lot of alternative implementantion of session utilities if you use Python:  http://wiki.github.com/dound/gae-sessions/ (it also has a comparison table with other libraries). For Java developers the only alternative is to use the <a href="http://code.google.com/appengine/docs/java/memcache/overview.html">Memcache</a> service and/or the <a href="http://code.google.com/appengine/docs/java/datastore/overview.html">DataStore</a> service. While the former has the problem of the data expiration strategy: <a href="http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires">http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires</a>, the latter will suffer of the same performance problems of the GAE session implementation.


]]>
      
   </content>
</entry>
<entry>
   <title>Flex Webservice: how to list available parameters for each operation</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/flex_webservice_how_to_list_av_1.html" />
   <id>tag:blog.comtaste.com,2010://1.123</id>
   
   <published>2010-07-03T16:14:35Z</published>
   <updated>2010-07-03T16:22:29Z</updated>
   
   <summary>In a previous post I explained how to list available operations provided by a WebService, parsing the WSDL document using some undocumented classes of the Flex 3 and 4 SDKs. This time I want to give you some suggestions about...</summary>
   <author>
      <name>Francesco Rapanà</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Web 2.0 Applications" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="210" label="webservice" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="223" label="wsdl" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In a <a href="http://blog.comtaste.com/2010/03/flex_webservice_how_to_list_av.html" target="_blank">previous post</a> I explained how to list available operations provided by a WebService, parsing the WSDL document using some undocumented classes of the Flex 3 and 4 SDKs.
This time I want to give you some suggestions about the next step: listing parameters of every operation.
NB: most of the classes in the package mx.rpc.wsdl have the tag [ExcludeClass] so they could change with an SDK update or they can be not stable. Flex Builder intellisense will not work for these classes, so you have to import them manually.
Note that I'm testing this code using a WSDL from a Axis2 WebService, it may not work on WSDL with a different structure or it may need some tweaks.

<pre class="brush: as3">
&lt;mx:Script&gt;
	&lt;![CDATA[
		import mx.rpc.soap.LoadEvent;
		import mx.rpc.wsdl.WSDLMessagePart;
		import mx.rpc.wsdl.WSDLOperation;
		import mx.rpc.xml.Schema;
		protected function loadHandler(event:LoadEvent):void
		{
			if(event.wsdl) {
				for each(var op:WSDLOperation in event.wsdl.getPort().binding.portType.operations()) {
					var param:WSDLMessagePart = op.inputMessage.getPart("parameters");
					if(param) {
						var schema:Schema = event.wsdl.schemaManager.getResourcesForURI(param.element.uri)[0] as Schema;
						var element:Object = schema.getNamedDefinition(new QName(schema.schemaConstants.xsdURI,param.element.localName),schema.schemaConstants.elementTypeQName);
						trace(element.definition, element.schema);
					} 
				}
			}
		}
	]]&gt;
&lt;/mx:Script&gt;</pre>

This small script, based on the code of the <a href="http://blog.comtaste.com/2010/03/flex_webservice_how_to_list_av.html" target="_blank">previous post</a>, analyze the inputMessage of the WSDLOperation. If there is a WSDLMessagePart with name "parameters", it looks for the related Schema and then it searches the definition of the element of the WSDLMessagePart. This definition is just the XML of the complexType of the parameter, then you have to write your custom logic to use it. Some WSDL may non have the "part" node, instead there is the name of the element, you have to slightly modify the code above.

This is just a sketch and not a ready-to-use solution but it can point you in the right direction.]]>
      
   </content>
</entry>
<entry>
   <title>Security Data Trasfer - AS3 Encrypting Libraries and Http Monitor Softwares </title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/security_data_trasfer_as3_encr_1.html" />
   <id>tag:blog.comtaste.com,2010://1.122</id>
   
   <published>2010-06-24T13:36:10Z</published>
   <updated>2010-12-27T16:18:38Z</updated>
   
   <summary>One of the most important problem in Application development is the Security of Data Transfer from\to Client to\from Server. The Flash Player environment has a lot of security rules and controls to safeguard data in the Web, but sometimes it&apos;s...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="252" label="ActionScript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="246" label="as3corelib" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="247" label="as3crypto" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="243" label="Charles" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="239" label="Encryption" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="249" label="MD5" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="245" label="SWFScan" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[One of the most important problem in Application development is the Security of Data Transfer from\to Client to\from Server. The Flash Player environment has a lot of security rules and controls to safeguard data in the Web, but sometimes it's not enough, so we have to integrate them with Encrypting Algorithms develops in our ActionScript Classes. Now we are going to see a little overview that allows us a knowledge of the most simple and useful AS library for encrypting data.

The first library is the as3crypto library. This is available in the Google Code at this <a href='http://code.google.com/p/as3crypto/'>address</a>  . As you can see on the documentation, the library provides a lot of  Hashing Algorithms, like MD5 and SHA-256, Public Key Encryption Algorithms , like RSA, and Secret Key Encryption Algorithms, and introduces a SSL engine. I suggest to see the <a href='http://crypto.hurlant.com/demo/ '>demo</a> with all the functionalities of the as3crypto library. Another Encrypting Library is as3corelib. Like the  as3crypto, the  as3corelib is published on Goggle Code at the <a href='http://code.google.com/p/as3corelib/'>address</a>, here is the source code of the library and the documentation, but there isn't a demo about it.  as3corelib also does not have Encryption Algorithms but only Hashing  Algorithms. 

Sometimes it is useful to measure the Security of our applications, so we can use these free products to see the data transfer between Client and Server : SWFScan by HP and Charles. SWFScan automatically find security vulnerabilities in applications built on the Flash Platform. It  decompiles applications built on the Flash Platform to extract the ActionScript code and statically analyzes it to identify security issues such as information disclosure; identifies and reports insecure programming and deployment practices; and suggests solutions. You can download it from this <a href='http://www.hp.com/go/swfscan '>site</a>. 
HP SWFScan offers several other features to help developers, code auditor/reviewers, and pen-testers examine the contents of Flash applications, including:
<ul>
<li>Highlighting the line of source code that contains the vulnerability to help better understand the context of the issue.</li>
<li>Providing summaries, details, and remediation advice for each vulnerability in accordance with Adobe's recommendation for secure Flash development.</li>
<li>Generating a vulnerability report to share and solve the detected issues.</li>
<li>Exporting the decompiled source code for use with other external tools.</li>
<li>Revealing all the URLs and web services the Flash Application contacts.</li>
<li>Flagging class names, function names, or variable names that may be of interest such as 
loadedUserXml or crypt().</li>
</ul>

Charles is an Http Proxy and an HTTP Monitor, it is enable to see all the data transfer in a browser web or between a client and a server, it is also ables to monitor the AMF protocol traffic. You can have more information <a href='http://www.charlesproxy.com'>here</a> . I think it's a very useful tool for the visualization of Data Trasfer between client and Server and it takes a great support for evidence the bugs in security in our SWF Applications. Next time i will deepen all the functionalities of this Software.

Regards
 ]]>
      
   </content>
</entry>
<entry>
   <title>UiBinder : a simple way to build Widget from XML markup</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/uibinder_a_simple_way_to_build.html" />
   <id>tag:blog.comtaste.com,2010://1.120</id>
   
   <published>2010-06-11T14:55:03Z</published>
   <updated>2010-06-11T15:30:26Z</updated>
   
   <summary>UiBinder helps developers to build GWT widgets in a few simple steps, exploiting the flexibility and maintainability of XML. This allows developer without a strong background in java to be competitive in the GWT code production. Thus we see UiBinder...</summary>
   <author>
      <name>Michele del Prete</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Google apps" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Java" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="234" label="GWT" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="235" label="Java" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="237" label="UiBinder" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[UiBinder helps developers to build GWT widgets in a few simple steps, exploiting the flexibility and maintainability of XML. This allows developer without a strong background in java to be competitive in the GWT code production.

Thus we see UiBinder in action : first of all we must create a web application that use Google Web Toolkit. To do this, I use the eclipse's plugin for GWT, so from the prompt do :
File --> New --> Other --> Google --> Web application project. Then fill the required fields, uncheck the "Use Google app engine" option and click "Finish".

Now we realize the following html page containing a simple widget :

<img alt="simplewidget.png" src="http://blog.comtaste.com/simplewidget.png" width="448" height="524" />

Initially we have to modify the home page, an HTML page, in which we create a "div" element that permit us to inject content from a Java class, the entryPoint :

<pre class="brush: xml">

&lt;!doctype html&gt;
 
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
 
    &lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;PostBlogUiBinder.css&quot;&gt;
 
    &lt;title&gt;Simple widget project&lt;/title&gt;
    
    &lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot; src=&quot;postbloguibinder/postbloguibinder.nocache.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
 
  &lt;body&gt;
 
    &lt;!-- OPTIONAL: include this if you want history support --&gt;
    &lt;iframe src=&quot;javascript:''&quot; id=&quot;__gwt_historyFrame&quot; tabIndex='-1' style=&quot;position:absolute;width:0;height:0;border:0&quot;&gt;&lt;/iframe&gt;
    
    &lt;!-- RECOMMENDED if your web app will not function without JavaScript enabled --&gt;
    &lt;noscript&gt;
      &lt;div style=&quot;width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif&quot;&gt;
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      &lt;/div&gt;
    &lt;/noscript&gt;
 
    &lt;h1&gt;Sample Widget&lt;/h1&gt;
 
    &lt;h3 align=&quot;center&quot;&gt;Fill the following fields&lt;/h3&gt;
     
    &lt;div id=&quot;simpleWidget&quot; align=&quot;center&quot;&gt;&lt;/div&gt;
    
  &lt;/body&gt;
&lt;/html&gt;

</pre>


as you can see we have create a div element with id called "simpleWidget" that we refer from the entrypoint java class.

Now we have to inject into this page the widget that we want to create. We do this into the entrypoint class, called SimpleWidgetEntrypoint :


<pre class="brush: java">


import com.post.uibinder.ui.SimpleWidget;
import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.user.client.ui.RootPanel;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SimpleWidgetEntrypoint implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
SimpleWidget simpleWidget = new SimpleWidget();
RootPanel.get("simpleWidget").add(simpleWidget);
}
}

</pre>

Now we have to create our widget, we can do this with the wizard plugin doing the following actions :

from the eclipse's prompt do File --> New --> Other --> Google Web Toolkit --> UiBinder --> Next

then digit the name of the java class of the widget, in our case "SimpleWidget" and then click Finish.

We can see now that the wizard has created two files :

- SimpleWidget.java
- SimpleWidget.ui.xml

To obtain our result widget we have to modify both files :

- SimpleWidget.ui.xml


<pre class="brush: xml">

&lt;!DOCTYPE ui:UiBinder SYSTEM &quot;http://dl.google.com/gwt/DTD/xhtml.ent&quot;&gt;
&lt;ui:UiBinder xmlns:ui=&quot;urn:ui:com.google.gwt.uibinder&quot;
xmlns:g=&quot;urn:import:com.google.gwt.user.client.ui&quot;&gt;
&lt;ui:style&gt;
.important {
font-weight: bold;
}
&lt;/ui:style&gt;
&lt;g:HTMLPanel ui:field=&quot;mainPanel&quot;&gt;
&lt;g:VerticalPanel&gt;
&lt;g:Label ui:field=&quot;descriptionLabel&quot; ui:text=&quot;Put a description of yourself&quot;&gt;&lt;/g:Label&gt;
&lt;g:TextArea ui:field=&quot;textArea&quot; ui:text=&quot;Put here your description&quot;&gt;&lt;/g:TextArea&gt;
&lt;g:Label ui:field=&quot;banLabel&quot; ui:text=&quot;Select which band you prefer among these&quot;&gt;&lt;/g:Label&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;U2&quot; &gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Radiohead&quot;&gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Pearl Jam&quot;&gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Depeche mode&quot;&gt;&lt;/g:RadioButton&gt;
&lt;/g:VerticalPanel&gt;
&lt;g:Button styleName=&quot;{style.important}&quot; ui:field=&quot;button&quot; ui:text=&quot;Confirm&quot; /&gt;
&lt;/g:HTMLPanel&gt;
&lt;/ui:UiBinder&gt; 

</pre>


- SimpleWidget.java

<pre class="brush: java">

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class SimpleWidget extends Composite {

private static SimpleWidgetUiBinder uiBinder = GWT
.create(SimpleWidgetUiBinder.class);

interface SimpleWidgetUiBinder extends UiBinder<Widget, SimpleWidget> {
}

@UiField
Button button;
@UiField
TextArea textArea;

public SimpleWidget() {
initWidget(uiBinder.createAndBindUi(this));
textArea.setSize("300px", "200px");
}

@UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("OK");
}

}

</pre>

To build the widget we need the following GWT elements :

- VerticalPanel
- Label
- RadioButton
- Button
- TextArea

if we don't use the UiBinder utilities we have to write the entire widget only with java code, but this time into the SimpleWidget java class we have only specified the size of the text area, all the other elements with their values are specified into the XML file.
This is why UiBinder simplifies the construction of GWT widget and simplifies also the collaboration between UI designers, which are more confortable with markup languages, and developers.]]>
      
   </content>
</entry>
<entry>
   <title>Binding improvement</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/binding_improvement.html" />
   <id>tag:blog.comtaste.com,2010://1.119</id>
   
   <published>2010-06-07T15:39:09Z</published>
   <updated>2010-06-08T10:46:12Z</updated>
   
   <summary>Since Flex 2, the Adobe Flex sdk&apos;s contain a class named BindingManager, unfortunately it&apos;s not documented in the released ASDoc, but this class it&apos;s really helpful to us to manage and debug all kind of binding inside our applications. BindingManager.debugBinding:...</summary>
   <author>
      <name>Liviu Stoica</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="50" label="actionscript" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="183" label="binding" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Since Flex 2, the Adobe Flex sdk's contain a class named BindingManager, unfortunately it's not documented in the released ASDoc, but this class it's really helpful to us to manage and debug all kind of binding inside our applications.


<strong>BindingManager.debugBinding:</strong>
Using the static method provided by the manager you will enable the debug for the property passed as parameter for the method like this:
<pre class="brush: as3">BindingManager.debugBinding( "myComponent.propertyToDebug" )</pre>

Now when you lunch your application in debug mode, you can see in the console something like this:
<em>Binding: destString = myComponent.prpertyToDebug, srcFunc result = First value
Binding: destString = myComponent.prpertyToDebug, error = TypeError: Error #1009: Cannot access a property or method of a null object reference.
Binding: destString = myComponent.propertyToDebug, srcFunc result = Changed value
</em>

<strong>BindingManager.setEnabled:</strong>
Another very handy method can be the setEnabled. By using this static method you will enable or disable all bindings for a specified component or document:
<pre class="brush: as3">BindingManager.setEnabled( yourComponent, true );</pre>


<strong>Discover all bindinded properties of a component:</strong>
From Flex 2 all documents property of the displayObject components have a non-null public _bindingsByDestination variable, containing the binding instances currently executed for the specified component.
So if you iterate inside the document._bindingsByDestination by String you will access to the "myComponent.bindedProperty":
<pre class="brush: as3">
use namespace mx_internal;
 
for (var binding:String in myComponent.document._bindingsByDestination)
{
   trace( binding );
  
  //And to access the to the binding instance use this:
  var myBinding:Binding = myComponent.document._bindingsByDestination[ binding ];  
}</pre>

This can be accessible only if you specify the use namespace <strong>mx_internal</strong>.
]]>
      
   </content>
</entry>
<entry>
   <title>Swiz framework - Custom Metadata Processor</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/swiz_framework_custom_metadata.html" />
   <id>tag:blog.comtaste.com,2010://1.118</id>
   
   <published>2010-05-31T13:40:23Z</published>
   <updated>2010-06-22T15:06:24Z</updated>
   
   <summary>In my last post I briefly introduced Swiz framework and uncovered part of its great potential. This post will be about Swiz&apos;s custom metadata processor, a powerful tool available with the 1.0 release. The metadata processors were available in previous...</summary>
   <author>
      <name>Constantin Moldovanu</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="232" label="metadata" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="224" label="swiz" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my <a href="http://blog.comtaste.com/2010/04/swiz_framework_inversion_of_co.html">last post</a> I briefly introduced Swiz framework and uncovered part of its great potential. This post will be about Swiz's custom metadata processor, a powerful tool available with the 1.0 release. The metadata processors were available in previous versions also, but now their API is open and allows developers to create their own ActionScript metadata and handle them rather easily.

As an example shows on <a href="http://swizframework.org/2009/12/swiz-1-0-reflection-api-and-custom-metadata-processors/">their site</a>, one has to choose a new metadata name and extend <code>org.swizframework.processors.BaseMetadataProcessor</code> (this class was called MetadataProcessor in the alpha release). In the example, a <em>Random</em> metadata was created, that assigns a random numeric value to any variable it decorates:
<pre class="brush: as3">
	[Random]
	public var randomNumber:Number;
</pre>

Such custom metadata are is extremely easy to use: once the processor class is created, it can simply be added to Swiz's custom processors:
<pre class="brush: xml">
	&lt;swiz:customProcessors&gt;
		&lt;processors:RandomProcessor /&gt;
	&lt;/swiz:customProcessors&gt;
</pre>

Obviously one should remember to edit the compiler parameters in order to add support for the newly created metadata: <code>-keep-as3-metadata+=Random</code>.

Since it came out, many useful custom metadata processors have been developed and released. Some of them, in no particular order, are:
<ul>
<li><a href="http://www.riaspace.net/2009/12/logprocessor-custom-metadata-processor-for-swiz-1-0-0/">Log processor</a>: just add a <em>[Log]</em> decoration to an instance of ILogger, to enable fast access to Flex logging API.</li>
<li><a href="http://odoe.net/thelab/flex/geocodeprocessor/GeocodeProcessor.html">Geocode Processor</a>: automatizes parts of the ESRI geolocation features.</li>
<li><a href="http://soenkerohde.com/2010/03/swiz-yahoo-finance-metadata-processor/">Yahoo Finance</a>: proof of concept that uses live data from Yahoo to populate a list decorated with custom metadata.</li>
<li><a href="http://code.google.com/p/foomonger-swizframework/">Foomonger</a>: metadata processor that simplifies the use of Swiz with <a href="http://code.google.com/p/as3-signals/">AS3signals</a></li>
</ul>

ActionScript metadata are customizable by themselves, but using Swiz framework makes the task more easy and fun. Looking forward to see a <a href="http://code.google.com/p/gag/">[WrittenWhile]</a> metadata!
]]>
      
   </content>
</entry>
<entry>
   <title>Using an editable Combobox as itemrenderer</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/using_an_editable_combobox_as.html" />
   <id>tag:blog.comtaste.com,2010://1.117</id>
   
   <published>2010-05-23T17:27:51Z</published>
   <updated>2010-05-23T17:53:12Z</updated>
   
   <summary>Flex editable combobox can be really useful if you need to let the user select either one of the predefined values or a custom input. The same result can be achieved using a TextInput for custom text and a button...</summary>
   <author>
      <name>Francesco Rapanà</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="3" label="flex 3" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Flex editable combobox can be really useful if you need to let the user select either one of the predefined values or a custom input. The same result can be achieved using a TextInput for custom text and a button that shows a non editable Combobox, but this solution looks less user friendly.
In this post I will show how to use an editable Combobox as itemrenderer in a List. This approach can be not the best (for example you can use an itemEditor) but maybe you will find the same issues using alternative solutions.
Let’s start creating a simple List with an ArrayCollection of CustomObject as dataProvider and using a custom itemRenderer:

Application.mxml
<pre class="brush: as3">
&lt;mx:Script&gt;
	&lt;![CDATA[
		import mx.collections.ArrayCollection;
		
		private var optionsAC:ArrayCollection = new ArrayCollection([
			"option1","option2","option3"
			]);
		[Bindable]
		private var myAC:ArrayCollection = new ArrayCollection([
			new CustomObject(false,"",optionsAC),
			new CustomObject(true,"custom Test",optionsAC),
			new CustomObject(false,"",optionsAC,2),
			]);
	]]&gt;
&lt;/mx:Script&gt;
&lt;mx:List dataProvider="{myAC}" width="300"
		 itemRenderer="customItemRenderer" /&gt;
</pre>
CustomObject.as
<pre class="brush: as3">
package
{
	import mx.collections.ArrayCollection;
	
	public class CustomObject
	{
		public var custom:Boolean;
		public var customString:String;
		public var options:ArrayCollection;
		public var optionIndex:int;
		
		public function CustomObject(c:Boolean = false,s:String = "",o:ArrayCollection = null ,oInd:int = 0)
		{
			custom = c;
			customString = s;
			options = o;
			optionIndex = oInd;
		}
	}
}
</pre>
customItemRenderer.mxml
<pre class="brush: as3">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%"&gt;
		
	&lt;mx:Script&gt;
		&lt;![CDATA[
			
			import mx.events.FlexEvent;
			
			override public function set data(value:Object):void {
				super.data = value;
				if(!data)
					return;
				if(data.custom) {
					combo.selectedIndex = -1;
					combo.text = data.customString;
				}
				else
					combo.selectedIndex = data.optionIndex;
			}
			
			private function onComboChange():void {
				if(combo.selectedItem) {
					data.optionIndex = combo.selectedIndex;
					data.custom = false;
				} else {
					data.customString = combo.text;
					data.custom = true;
				}
			}
			
		]]&gt;
	&lt;/mx:Script&gt;
	&lt;mx:ComboBox width="100%" id="combo" editable="true" dataProvider="{data.options}"  change="onComboChange()" /&gt;
&lt;/mx:HBox&gt;
</pre>
The customItemRenderer sets the data in the Combobox checking if there is a custom string or a predefined option. onComboChange saves the modified data into the custom objects whenever the user type into the Combobox or select one option from the dropdown list.
This example is straightforward and it could be useful most of the time you need something similar. But what happens if your CustomObject class is bindable?
Let’s modify CustomObject.as adding the Bindable Meta Tag:
<pre class="brush: as3">
[Bindable]
public class CustomObject
{
</pre>
Now, when onComboChange modify one of the attribute of CustomObject, a change event is dispatched, that brings to an update of the itemRenderer with a call to the set data function. Here the Combobox calls its updateDisplayList that select all the text inside its TextInput. So, if the user is typing, after the first keystroke the text will be selected and a second keystroke will eventually delete the previous inserted text.

Here’s a solution, extend the Combobox component and override its updateDisplayList:
<pre class="brush: as3">
package
{
	import mx.controls.ComboBox;
	
	public class CustomCombobox extends ComboBox
	{
		public function CustomCombobox()
		{
			super();
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			if(editable) {
				var begin:int = textInput.selectionBeginIndex;
				var end:int = textInput.selectionEndIndex;
			}
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			if (editable)
			{
				textInput.setSelection(begin, end);
			}
		}
	}
}
</pre>

The idea is simple, just save the previous selection indexes, than after the Combobox updateDisplayList restore them.
Don’t forget to change the Combobox component used in the itemRenderer with the new custom component.
I think there are many alternative solutions to obtain such interaction but I hope this could be useful to someone to save some time trying to understand why its combobox continue to select its text

This example works in Flex 3.5.]]>
      
   </content>
</entry>
<entry>
   <title>Mate Framework - an example</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/mate_framework_a_little_exampl.html" />
   <id>tag:blog.comtaste.com,2010://1.116</id>
   
   <published>2010-05-11T17:00:10Z</published>
   <updated>2010-05-12T13:58:23Z</updated>
   
   <summary>In my last post I showed you how Mate framework works. Now I would like to deepen the study on this framework with a short example, and I&apos;d like to show one of best practice ways to use it. For...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="51" label="framework" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="217" label="Mate" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="219" label="MVC" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my last post I showed you how Mate framework works. Now I would like to deepen the study on this framework with a short example, and I'd like to show one of best practice ways to use it. For this project I used Flex 4 and Mate_08_9.swc library.  

In respect of the Model View Control Pattern I create a project with six packages:  business, component, controls,maps, model and view. 

<img alt="MateProject.JPG" src="http://blog.comtaste.com/MateProject.JPG" width="240" height="229" />

In the business package I create all the classes that can communicate with remote services (like http services or wsdl services ), in fact you can find there a ServiceLocator class as an MXML file, that extends the Object class, where I put an httpService tag, from which I would like to obtain an XML File.

<pre class="brush: xml">
 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;DataPerson&gt;
	&lt;Person&gt;
		&lt;name&gt;Name&lt;/name&gt;
		&lt;surname&gt;Surname&lt;/surname&gt;
		&lt;phone&gt;12345678&lt;/phone&gt;
	&lt;/Person&gt;
	&lt;Person&gt;
		&lt;name&gt;Name 1&lt;/name&gt;
		&lt;surname&gt;Surname 1&lt;/surname&gt;
		&lt;phone&gt;123456789&lt;/phone&gt;
	&lt;/Person&gt;
&lt;/DataPerson&gt;
</pre>

In the Component package I create the components of my application (in this example only MyDataGrid.mxml) that I use into my View. 
In the controls package I put my Event class, in the maps package My Mate EventMap, and in the model package I create a singleton call MateExampleModel where I manage all the data structure used by my view components that are in View package.

Hope that the project structure is easy to understand, I would like to analize the core of the project in particular how I follow the MVC Pattern with Mate Framework.

First of all we can see into the Application tag (view.MateExample.xml) all the View components present  in my project, and it's easy to see that there are only an event dispatcher, a data binding with a property of the model, and the build of the EventMap component (component.MyEntityMap).

<pre class="brush: xml">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:component="component.*" xmlns:maps="maps.*"&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import controls.XMLLoadMateEvent;
			import model.ModelMateExample;
 
			public var evt:XMLLoadMateEvent = new XMLLoadMateEvent(XMLLoadMateEvent.XML_LOAD);
		]]&gt;
	&lt;/mx:Script&gt;
 
	&lt;mx:HBox width="100%" height="100%"&gt;
		&lt;mx:VBox width="30%"&gt;
			&lt;s:Button label="Fill the Datagrid" click="{dispatchEvent(evt)}" /&gt;
			&lt;component:MyDataGrid width="100%" height="100%" dataProvider="{ModelMateExample.instance().gridDB}"/&gt;
		&lt;/mx:VBox&gt;
	&lt;/mx:HBox&gt;
	&lt;maps:MyEntityMap /&gt;	
&lt;/mx:Application&gt;
</pre>

The Control components are  the Event Class, dispatched by the view, and the HttpServiceManage Class that contains all the methods for manage the resultObject coming from the HttpService (result and fault methods).  

The Mate Entity Map is separated by the other Control classes, and it contains all the tags that we analized in my last post... but I think is a good idea to deepen how I used that tags. First we can see how I manage the httpService: on the bottom of the file MyEventMap.mxml I build an object from my ServiceLocator and I used it to generate an instance of  an httpService  into the HttpServiveInvoker tag, and, inside it, I manage the resultObject and the fault with the methods of an instance of the HttpServiceManage Class (view the code below).

<pre class="brush: xml;highlight: [11]">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mate:EventMap xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:mate="http://mate.asfusion.com/" xmlns:business="business.*"&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import controls.HttpServiceManage;
			import controls.XMLLoadMateEvent;
		]]&gt;
	&lt;/mx:Script&gt;
  
	&lt;!-- enable debugger --&gt;
	&lt;mate:Debugger level="{Debugger.ALL}"/&gt;
  
	&lt;!-- handler of the XMLLoadMateEvent --&gt;
	&lt;mate:EventHandlers type="{XMLLoadMateEvent.XML_LOAD}" debug="true"&gt;
		&lt;!-- HTTP Service --&gt;
		&lt;mate:HTTPServiceInvoker instance="{service.httpService}" debug="true" &gt;
			&lt;!-- result handlers --&gt;
			&lt;mate:resultHandlers &gt;
				&lt;mate:MethodInvoker generator="{HttpServiceManage}" method="result" arguments="{resultObject}" &gt;
				&lt;/mate:MethodInvoker&gt;
			&lt;/mate:resultHandlers&gt;
 
			&lt;!-- fault handlers --&gt;
			&lt;mate:faultHandlers&gt;
				&lt;mate:MethodInvoker generator="{HttpServiceManage}" method="fault" arguments="{fault}" &gt;
				&lt;/mate:MethodInvoker&gt;
			&lt;/mate:faultHandlers&gt;
		&lt;/mate:HTTPServiceInvoker&gt;		
	&lt;/mate:EventHandlers&gt;
 
	&lt;!-- Service Locator --&gt;
	&lt;business:ServiceLocator id="service"/&gt;
&lt;/mate:EventMap&gt;
</pre>

It's very import to see that I manage the model of my application without the PropertyInjector tag . In fact, if you see the code of the HttpServiceManageClass, you can observe that I use the model's objects inside the result method of my httpService. 

<pre class="brush: as3">
package controls
{
	import model.ModelMateExample;	
	import mx.controls.Alert;
	import mx.rpc.Fault;
  
	public class HttpServiceManage
	{
		public function HttpServiceManage()
		{
		}
		public function result(obj:Object):void{
			ModelMateExample.instance().gridDB = obj.DataPerson.Person;
		}
		public function fault(faultObj:Fault):void{
			Alert.show("Error: "+faultObj.message);
		}
	}
}
</pre>

Generally I prefer to use this kind of solution because I think it could be clearer for whom want to analize my code to understand the funcionalities and the model's properties managed by the methods.
This approach is not the only one that you can use in your Mate Project, in fact it would like to be only an example of the flexibility of this framework.I think that Mate could be a very simple and power solution for create Flex Project with a solid structure that guarantees good quality for our projects.

<a href="http://blog.comtaste.com/MateExampleProject.zip">Download example source code</a>

Regards
]]>
      
   </content>
</entry>
<entry>
   <title>Alchemy: compiling C/C++ code into SWF or SWC</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html" />
   <id>tag:blog.comtaste.com,2010://1.115</id>
   
   <published>2010-04-30T09:29:04Z</published>
   <updated>2010-05-31T12:07:55Z</updated>
   
   <summary>Alchemy is a research project that is intended to allow user to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). With Alchemy, Web application developers can now reuse existing open...</summary>
   <author>
      <name>Luca Galati</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="226" label="c" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="227" label="c++" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="31" label="Flex 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="228" label="reuse" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Alchemy is a research project that is intended to allow user to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2).

With Alchemy, Web application developers can now reuse existing open source C and C++ client or server-side code on the Flash Platform. Alchemy aims to bring the power of high performance C and C++ libraries to Web applications with minimal degradation on AVM2. The C/C++ code is compiled to ActionScript 3.0 as a SWF or SWC that runs on Adobe Flash Player 10 or Adobe AIR 1.5. Alchemy is primarily intended to be used with C/C++ libraries that have few OS dependencies. The generated content runs within the security constraints of the AVM2, and cannot bypass Flash Player security protections. 

In this post I'm going to explain how to setup up Alchemy on Windows and then I'm showing how to walk through the steps to get a simple C code file compiled into a SWC, and then how to use that SWC within a simple Flex example.

<strong>Requirements</strong>
On windows we will use Cygwin.
<ul>
<li>Alchemy Toolkit Package for your Windows OS</li>
<li><a href="http://www.cygwin.com/">Cygwin</a> with the following packages installed </li>
<ul>
<li>Perl </li>
<li>zip </li>
<li>gcc / g++ </li>
</ul>
<li><a href="http://java.sun.com/">Java</a> </li>
<li>Flex 3.2 SDK </li>
<li>Flex SDK setup to target compilation for Flash Player 10 </li>
</ul>
Download and install Cygwin with the packages suggested before.Download and install Java.  Make sure to restart the Cygwin terminal after installing Java.  Download and install the Flex SDK, and add the $FLEX_HOME/bin directory to your Cygwin environment's path (within ~/.bashrc).Download the Alchemy Package, unzip it and then  copy  the alchemy folder to your system. We will refer to this path as $ALCHEMY_HOME. Open a Cygwin terminal and change to the $ALCHEMY_HOME/ directory. Run the $ALCHEMY_HOME/config script using the following command:

<font face="courier">./config</font>

 Open alchemy_setup for editing and add the path to the ADL executable (included in the Flex SDK): 

<font face="courier">export ADL=/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin/adl.exe</font>

Make sure to uncomment this line, and that it contains the path to ADL.exe on your system (Substitute <font face="courier">PATH_TO_FLEX_SDK_HOME</font> with the path of the Flex Sdk installed on your system). Open your bash setup script to edit. This can usually be found in the ~/.bashrc file. Edit the the .bashrc script so that alchemy-setup is run when the script is run: 

<font face="courier">source /cygdrive/c/alchemy/alchemy-setup</font>

This should be added before your PATH is modified.  Add $ALCHEMY_HOME/achacks to your path. 

<font face="courier">PATH=$ALCHEMY_HOME/achacks:/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin:$PATH</font>

Your .bashrc file should look similar to:
 
<font face="courier">source /cygdrive/c/alchemy/alchemy-setup
PATH=$ALCHEMY_HOME/achacks:/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin:$PATH
export PATH</font>

Obviously the file may contain other commands specific to your system. Save the file, and restart your cygwin terminal. Change to the $ALCHEMY_HOME/bin directory, and run the following command: 

<font face="courier">ln -s llvm-stub llvm-stub.exe</font>

Note that this step wont be necessary in future builds. Now your environment is ready to compile C/C++ code into a SWF or a SWC.

I've devoleped a simple C function to sum two doubles. Here is the code:

<pre class="brush:cpp">
//File doublesum.c
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include &quot;AS3.h&quot;
 
//Method exposed to ActionScript
//Takes two doubles and return the sum
static AS3_Val sum(void* self, AS3_Val args)
{
	//initialize double parameters to 0.0
	double operand1 = 0.0;
	double operand2 = 0.0;
	
	//parse the arguments. Expect 2.
	//pass in operand1 to hold the first argument, which
	//should be a double. Does the same with the second argument
	AS3_ArrayValue( args, &quot;DoubleType, DoubleType&quot;, &amp;operand1, &amp;operand2 );
	
	//calculate the sum and return it
	double sum = operand1+operand2;
	return AS3_Number(sum);
}
 
//entry point for code
int main()
{
	//define the methods exposed to ActionScript
	//typed as an ActionScript Function instance
	AS3_Val sumMethod = AS3_Function( NULL, sum );
 
	// construct an object that holds references to the functions
	AS3_Val result = AS3_Object( &quot;sum: AS3ValType&quot;, sumMethod );
 
	// Release
	AS3_Release( sumMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}</pre>

To compile the file doublesum.c , into the cygwin shell change to the directory where you stored the file (or your  C file) and type the following command :
 
<font face="courier">alc-on; which gcc</font>

It should print out the path that points to the gcc contained with the $ALCHEMY_HOME/achacks/ directory. Then enter the following command: 

<font face="courier">gcc doublesum.c -O3 -Wall -swc -o doublesum.swc</font>

You should see output similar to: 
<font face="courier">
WARNING: While resolving call to function 'main' arguments were dropped!

4232.achacks.swf, 261018 bytes written
frame rate: 60
frame count: 1
69 : 4
72 : 260949
76 : 32
1 : 0
0 : 0
frame rate: 24
frame count: 1
69 : 4
77 : 506
64 : 31
63 : 16
65 : 4
9 : 3
41 : 26
82 : 471
1 : 0
0 : 0

  adding: catalog.xml (deflated 75%)
  adding: library.swf (deflated 70%)
</font>

Now in the same directory you will find the file doublesum.swc. To test it I have developed an mxml file named DoubleSumTest.mxml. This is the code:

<pre class="brush:as3; html-script: true">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import cmodule.doublesum.CLibInit;
			
			private function c_doubleSumFunction(op1:Number, op2:Number):Number
			{
				var loader:CLibInit = new CLibInit();
				var lib:Object = loader.init();
				return lib.sum(op1,op2);
				
			}
			
			private function buttonHandler():void
			{
				var operand1:Number = Number(operand1Field.text);
				var operand2:Number = Number(operand2Field.text);
				var sum:Number = this.c_doubleSumFunction(operand1, operand2);
				resultField.text = String(sum);
			}
		]]&gt;
	&lt;/mx:Script&gt;
 
	&lt;mx:TextInput id=&quot;operand1Field&quot; /&gt;
	&lt;mx:Label text=&quot;+&quot; /&gt;
	&lt;mx:TextInput id=&quot;operand2Field&quot;/&gt;
	&lt;mx:Label text=&quot;=&quot; /&gt;
	&lt;mx:TextInput id=&quot;resultField&quot; /&gt;
	&lt;mx:Button id=&quot;sumButton&quot; label=&quot;sum&quot; click=&quot;buttonHandler()&quot;/&gt;
	
&lt;/mx:Application&gt; 
</pre>
Download this file,named DoubleSumTest.mxml (or write your own test file) and save it in the same directory of the doublesum.swc.
Into the cygwin shell, change to the directory where you stored the file and use the following command to compile the ActionScript/Flex code using MXMLC: 

<font face="courier">mxmlc.exe -library-path+=./doublesum.swc -target-player=10.0.0 DoubleSumTest.mxml </font>

This will generate a Flash Player 10 SWF. Executing this file in a browser  will show you 3 TextInput followed by a Button labeled sum.
Introducing 2 double numbers in the first and second TextInput and clicking on  the button will show their sum in the third TextInput calculated by the C function in doublesum.c . 

For more information about Alchemy visit: <a href="http://labs.adobe.com/technologies/alchemy/ ">http://labs.adobe.com/technologies/alchemy/ </a>.
]]>
      
   </content>
</entry>
<entry>
   <title>Create a google site with the Google sites Java API</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/create_a_google_site_with_the.html" />
   <id>tag:blog.comtaste.com,2010://1.114</id>
   
   <published>2010-04-22T16:06:08Z</published>
   <updated>2010-04-22T16:14:42Z</updated>
   
   <summary>With the google sites API we can build client application that can access, publish and modify content within a Google site In this post I show some functionalities of Google sites Java library that allow to : - Create a...</summary>
   <author>
      <name>Michele del Prete</name>
      <uri>http://www.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[With the google sites API we can build client application that can access, publish and modify content within a Google site

In this post I show some functionalities of Google sites Java library that allow to :

- Create a site
- Insert web pages into a site

All these action are done by an istance of SitesService :

<pre class="brush: java">
SitesService client = new SitesService("mySite");
</pre>

<u>Create a site</u>

This feature is only available to Google Apps domains. To create a site we must execute :

<pre class="brush: java">
    SiteEntry entry = new SiteEntry():
    entry.setTitile(new PlainTextContruct("title of the site"));
    entry.setSummary(new PlainTextConstruct("summary of the site"));
 
    Theme theme = new Theme();
    theme.setValue("theme of the site");
 
    entry.setTheme(theme);
 
    client.insert(new URL(getSiteFeedUrl(), entry));
</pre>

where the method "getSiteFeedUrl()" return the url's related of site feed of "domain", composed as follows: "http://sites.google.com/feeds/site/" + domain + "/"

where "domain" is the name of your domain. If the site is hosted on a Google account we have to put "site" instead of domain.

We can use a site feed to :

- list the Google sites that a user owns
- list the Google sites that a user has viewing permission for
- to modify the name of an existing site
- to create and/or copy an entire site

At page creation we can choose a large variety of themes, the same themes that we can select during the manual creation of a Google Site from the Url http://sites.google.com.

<u>Insert web pages</u>


Now we show how to insert web pages into the sites that we have created.

<pre class="brush: java">
WebPageEntry pageEntry = new WebPageEntry();
pageEntry.setTitle(new PlainTextConstruct("title of the page"));

XmlBlob blob = new XmlBlob();
blob.setBlob("HTML content of the page");

pageEntry.setContent(new XhtmlTextConstruct(blob));

client.insert(new URL(getContentSiteFeedUrl("siteName")), pageEntry);

</pre>

where the method "getContentSiteFeedUrl("siteName")" return the url's related of content feed of the webspace name of "siteName". With the content feed we can lists a Site's latest content. The url's feed is the follow: "http://sites.google.com/feeds/site/" + domain + "/" + siteName + "/". 

In this example I chose to create a "webpage", but there are other kinds of pages that I can create :

- FileCabinetPageEntry
- AnnouncementsPageEntry
- ListPageEntry

With Google Sites API you can create a web application that offers a service to create in a simple way a Google site, to the users of a given Google apps domain. You can find the references to the Google API to the following link : http://code.google.com/intl/it-IT/labs/.]]>
      
   </content>
</entry>

</feed>

