Razvan Surdu Personal Blog

25May/100

Remove Focus From a Text Input In Flex

If you want to remove the focus from a flex component you can use this:

this.stage.focus = null;
Tagged as: , No Comments
4Mar/100

Singletons… Learning the hard way

This post will be about the singletons, when you should use them and when not. I decided to write this post because I made a mistake on a project that I was working on using this design pattern and I had to spend half of day to fix it.

So if you don't know what a singleton is them a simple explication would be: a class that has no more then one instance witch you can use in the entire project. For a more detailed explication you can find out on wikipedia. We could even compere a singleton class to a global variable.

Why you would want to use it?
It's main advantage is that you can access and modify it from any place of your application: class methods, static methods, functions etc. Most of my singletons classes would have the role to store different properties for my application, lets say like the user that has logged on. You create a class based on this design patter, add the public property loggedUser and when the user logs in then that property is modified. You don't have to bother with passing the user variable from class to class, or component to component, if you want to use it just call the static getInstance method of the singleton class and read the loggedUser property. That's all. You can store many other information in this class like application status, general settings.

When not to use it!
You created an application using one, or two singletons and everything looks ok and works perfectly. Then someone ask you to integrate you application in a bigger one and would like to have more then one instance of you application running inside it. From the moment that a new instance of you application/component is created your app is finished. Because you used singleton classes, the classes from the second or third instance will direct to the first singleton class.

This is it's main flaw. You can not have more then one instance. Sometimes it works for you sometimes it don't. But the main purpose of object oriented programming is to have objects related with other: parents, children - inheritance, siblings - more then one instance etc. If you create a component that can be uses in only one way than you remove all the flexibility and adaptivity from it the it's life time will be a very short one.

Be very careful when you choose this design pattern. You must think ahead and realize if you want your application to be a stand alone app  or just a component from a bigger one. Choose wisely :)

Filed under: Uncategorized No Comments
17Dec/090

How character formats impact data delivery

Here is an interesting video about character formats and how to create a more scalable solution. Credits to Kevin Hoyt.

Filed under: Examples No Comments
29Nov/090

One simple arhitecture for flex

Project Structure

Project Structure

I am writing this article because many have asked me how to start a flex application and what are some best practices when laying out the foundation. I will create a mini project for this purpose and I will underline some important principals that you should consider when starting a flex application.

Ground rule: Separate your code using the Model - View - Controller design pattern. You don't what to be faced with the situation when you have a lot of lines in a single mxml file and you must quickly fix a critical bug, or you look on someone else code and don't have a clue where to develop the new feature that the project manager wanted.

Starting with the Model, I create a action script class MovieLibModel. In this class I create all the business elements of the application. In my example here I create the public var movies which holds all the movies loaded from the database. The class is a singleton and I can access it's methods from anywhere in the application using the getInstance static method. If I had a more complex application here I would store the user state, his favorite movies or any kind of data that I will later need in the interface.

package model
{
	import mx.collections.ArrayCollection;

	[Bindable]
	public class MovieLibModel
	{
		static private var _instance:MovieLibModel = null;

		public function MovieLibModel()
		{
		}

		static public function getInstance():MovieLibModel
		{
			if (MovieLibModel._instance == null)
			{
				MovieLibModel._instance = new MovieLibModel();
			}

			return MovieLibModel._instance;
		}

		public var movies:ArrayCollection = null;
	}
}

The View is represented by the application interface. Panels, buttons, alert messages and other UI elements form the visual part of the program. This part is mostly created by designers in tools like Photoshop, Fireworks and the exported with Flash Catalist. In flex you create components for the login zone, for product display page etc and you bind the visual elements to the model data. In my example I create two panels one with a datagrid used to list the movies and one with a form for adding a new movie to the databse.

interface

Application Interface




	
		

	

	
		
			
				
					
					
					
				
			
		

		
			
				
					
				
				
					
				
				
					
					
				
				
					
				
			
		
	

Now we must bind the two elements together. When the user inserts a new movie it should be added to the database, and the movie datagrid updated. For this we use the Controller. It's main roles are to handle the actions dispatched by the view, update the model, exchange data with the database or other external services. In this example I use a simple http service to communicate with the backend which is a php script.

package controller
{
	import model.MovieLibModel;

	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class MovieLibController
	{
		static private var _instance:MovieLibController = null;

		public function MovieLibController()
		{
			init();
		}

		static public function getInstance():MovieLibController
		{
			if (MovieLibController._instance == null)
			{
				MovieLibController._instance = new MovieLibController();
			}

			return MovieLibController._instance;
		}

		public var appModel:MovieLibModel = MovieLibModel.getInstance();

		private var myService:HTTPService = null;

		public function init():void
		{
			myService = new HTTPService;
			myService.method = "POST";
			myService.url = "http://localhost/razvansurdu.com/movieLib/server/";
			myService.resultFormat = "array";

			myService.addEventListener(FaultEvent.FAULT, myService_faultHandler);
			myService.addEventListener(ResultEvent.RESULT, myService_resultHandler);
		}

		public function addMovie(title:String, rating:String, description:String):void
		{
			var o:Object = new Object();
			o.title = title;
			o.rating = rating;
			o.description = description;

			o.action = "addMovie";
			myService.send(o);
		}

		public function getMovies():void
		{
			var o:Object = new Object();
			o.action = "getMovies";

			myService.send(o);
		}

		protected function myService_resultHandler(event:ResultEvent):void
		{
			appModel.movies = event.result[0].data.movie;
		}

		protected function myService_faultHandler(event:FaultEvent):void
		{
			Alert.show(event.fault.faultString);
		}
	}
}

Based on this architecture you can add more features, add more visual elements and have a well organized app, easy to debug and maintain.

7Nov/090

Convert a Xml to an ArrayCollection in AS3

Here is a quick method to convert a xml to an array collection. Because you pass the XML url (Eg: './assets/data.xml') to the first argument you will receive the array asynchronous using the callback function. If you have already the xml content in a variable use only the code in the anonymous function at the event.COMPLETE dispatch.

static public function convertXmlToArrayCollection( xmlUrl:String, rootTag:String, repeatedElement:String, callback:Function ):void
{
	var xmlLoader:URLLoader = new URLLoader();
	xmlLoader.addEventListener(Event.COMPLETE, function(e:Event):void
	{
		var xml:XMLDocument = new XMLDocument( e.target.data );
		xml.ignoreWhite = true;

		var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
		var data:Object = decoder.decodeXML( xml );
		var array:Array= ArrayUtil.toArray(data[rootTag][repeatedElement]);

		callback(new ArrayCollection( array ));
	});
		xmlLoader.load(new URLRequest(xmlUrl));
}
6Oct/090

Great day for Flex/Flash Developers

Applications for iPhoneToday at Max 2009 Adobe announced the ability to build iPhone application with action script 3. Multitouch api and other were added to flash so developers could take advantage of the iPhone features. By the end of this year Adobe promised to release the tools required and personally I can't wait to create my first flash iPhone app.

You can find more information on the adobe labs.

Tagged as: , , , No Comments
20Aug/090

Creating a system tray icon and menu for your AIR application

private function createSysTray():void
{
	if(NativeApplication.supportsDockIcon)
	{
		NativeApplication.nativeApplication.icon.bitmaps = 	[ new icon16().bitmapData ];
	    var dockIcon:DockIcon = NativeApplication.nativeApplication.icon as DockIcon;
	    NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, showMainWindow);
	    dockIcon.menu = createIconMenu();
	} else if (NativeApplication.supportsSystemTrayIcon){
		NativeApplication.nativeApplication.icon.bitmaps = 	[ new icon16().bitmapData ];
	    var sysTrayIcon:SystemTrayIcon = NativeApplication.nativeApplication.icon as SystemTrayIcon;
	    sysTrayIcon.tooltip = "Tooltip";
	   	sysTrayIcon.addEventListener(MouseEvent.CLICK,function():void
	   	{
	   		//Icon Click Handler
	   	});
	    sysTrayIcon.menu = createIconMenu();
	}
}

private function createIconMenu():NativeMenu{
    if(NativeApplication.supportsSystemTrayIcon){
    	var iconMenu:NativeMenu = new NativeMenu();

    	var showSettingsCommand:NativeMenuItem = iconMenu.addItem(new NativeMenuItem("Edit Settings"));
    	showSettingsCommand.addEventListener(Event.SELECT, showSettingsWindow);

        var exitCommand: NativeMenuItem = iconMenu.addItem(new NativeMenuItem("Close"));
        exitCommand.addEventListener(Event.SELECT, function ():void
        {
        	stage.nativeWindow.close();
        });
    }
    return iconMenu;
}
Filed under: Examples, Flex No Comments
19Aug/090

Retrieving a web page behind a proxy in php

If you need to retrieve a web page or file from the web and you are behind a proxy that requires authentication you can use this methods:

$params = array
(
	'http' => array
	(
		'method' => 'GET',
		'header'  => 'Proxy-Authorization: Basic ' . base64_encode(PROXY_USERNAME . ':' . PROXY_PASSWORD) . "\r\n\r\n",
		'proxy' => 'tcp://PROXY_ADDRESS:PROXY_PORT',
		'request_fulluri' => true,
	)
);
$context = stream_context_create($params);

echo file_get_contents('http://www.google.com', null, $context);

For this method you need to have curl extension enabled:

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL,"http://www.google.com/");
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
curl_setopt($ch, CURLOPT_PROXY, 'proxyAddress:proxyPort');
curl_setopt ($ch, CURLOPT_PROXYUSERPWD, "username:password");
$page = curl_exec($ch);
echo($page);
Filed under: Examples, Php No Comments
17Aug/090

From php to flex

Being myself a developer that started with php and moved to flex I encourage all of php developers to read this article: http://corlan.org/2009/08/14/flex-for-php-developers-article/. Mihai Corlan, one of the best flex evangelists, described in great details the similarities and differences between php and flex.

Here is the table of contents:

  1. What is Flex?
    1. Flex: two languages, one framework to bind them
    2. Why you should care about Flex
    3. From thin client to smart/rich client
  2. Introduction to the MXML language
    1. Mixing MXML with ActionScript 3
    2. CSS styles
    3. Modifying MXML code at runtime
  3. Introduction to the ActionScript 3 language
    1. Separating statements
    2. Data types, variables, constants
    3. Functions and Anonymous functions (closures)
    4. OOP: classes and interfaces
    5. Variable scope
    6. Arrays
    7. Namespaces
    8. Working with XML
    9. Dynamic ActionScript
  4. Flex is asynchronous
  5. Data binding, metadata tags, and reflection
  6. Where are my data, bring it on!
  7. User authentication in Flex and PHP projects
  8. Working on Flex and PHP projects
    1. Flex SDK
    2. Flex Builder / Flash Builder
    3. Debugging Flex applications
  9. What is Adobe AIR?
  10. What’s next?
  11. Where to go from here
Filed under: Flex No Comments
17Aug/090

Graduated

P1030888

European Engineer :)

On 16 July 2009 I graduated from the Automatics and Computer Science at the University of Polytechnic of Bucharest. Hoorrayy :)

Filed under: Uncategorized No Comments