miércoles, 7 de abril de 2010

Communications between two Local Flex Apps - Comicacion entre dos Apps de Flex Locales


Translation:

Algunas veces queremos comunicar dos aplicaciones de Flex o Flash que se encuentran en la misma página, y no vemos la manera de hacerlo.

ActionScript tiene una clase, que nos permite hacer esto sin mucho esfuerzo. Esta clase está ubicada en flash.net. LocalConnection.

Como todo principio de Cliente servidor, una aplicación tiene que escuchar y la otra tiene que ver si hay alguien escuchando.

Veamos el primer código donde vemos la aplicación que escucha, le colocaremos un nombre a la conexión llamada myConnection:
Sometimes we want to communicate two Flex or Flash applications that are on the same page, and do not see how.

ActionScript has a class, allowing us to do so without much effort. This class is located at flash.net. LocalConnection.

The idea is like a client server connection, an application needs to listen and the other has to see if anyone is listening.

Let us first see the application code where you hear, we will place a name to the connection called myConnection:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 

 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.client = this;
    connection.connect("myConnection");
    data.addItem("The Client es THE APP, The name is myConnection");
   }
   
   public function colorBackground(sendedColor:uint):void
   {
    data.addItem("colorBackground Function");
    try
    {
     remoteColor.setStyle("backgroundColor",sendedColor);
     data.addItem("Recived Color in UInt -> "+ sendedColor);
    }
    catch (error:ArgumentError)
    {
     Alert.show("Error trying to connect to LocalConnection.");
    }
   } 
   
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 
 <s:VGroup height="100%" width="100%" 
     x="0" y="0" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <s:Panel id="remoteColor" 
     width="250" height="100" 
     title="Remote Background Color" >
  </s:Panel>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     width="100%" height="100%" 
     x="0" y="0"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>

Ahora veamos la segundo aplicación la cual envía un mensaje a myConnection buscando una función llamada colorBackground y le pasa como parámetro el Color Seleccionado:
Now for the second application which sends a message looking for a function called myConnection colorBackground and passes as parameters the Selected Color:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
      xmlns:s="library://ns.adobe.com/flex/spark" 
      xmlns:mx="library://ns.adobe.com/flex/mx" 
      minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.ColorPickerEvent;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.addEventListener(StatusEvent.STATUS, connectionStatusHandler);
    data.addItem("Add Listener Status to the Connection");
   }
   
   private function connectionStatusHandler(event:StatusEvent):void
   {
    data.addItem("Connection Status Handler");
    switch (event.level)
    {
     case "status":
      trace("Use of LocalConnection.send() succeeded");
      break;
     case "error":
      Alert.show(
       "The LocalConnection.send() call failed: "
       + event.code + "\n"
       + event.toString() );
      break;
    }
    data.addItem("Status -> "+ event.level );
   }
   
   protected function sendColorHandler(event:ColorPickerEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Send Color Handler");
    connection.send("myConnection", "colorBackground", event.color);
    data.addItem("Color Sending in UInt -> " + event.color);
   }
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 <s:VGroup x="0" y="0" 
     width="100%" height="100%" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <mx:ColorPicker change="sendColorHandler(event)"/>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     x="0" y="0" 
     width="100%" height="100%"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>


Los archivos pueden Descargarlos arriba de cada ejemplo.
The files can be downloaded above each example.

Ejemplo Uno - Recive el mensaje:
Example One - The message receiver:

Ver y Descargar Archivo del App 1:
View Source and Download Files of the App 1:


Ejemplo Dos - Envia el Mensaje:
Example Two - Sends the Message:

Ver y Descargar Archivo del App 2:
View Source and Download Files of the App 2:

viernes, 2 de abril de 2010

Cryptography in Flex - Encriptar en Flex - Flex 4


Translation:


Siempre necesitamos usar algún tipo de seguridad, para garantizar a nuestros clientes finales, la seguridad, valga la redundancia, de sus datos. Es por eso que cada ves que vamos a usar un Login o algún texto que necesite de algún tipo de Ofuscamiento, recurrimos a los que son algoritmos de Encriptación.

Flex tiene una librería para encriptar de forma muy sencilla y brinda varios algoritmos, logrando así nuestro objetivo, asegurarnos que nadie tenga la clave o texto de viaje por la red y pueda leerlo o al menos leerlo de forma inmediata.

Aquí les dejo el link para que se bajen la librería para ActionScript, as3corelib Link.

Y aquí le dejos solo la clase donde se ve mejor la implementación, de igual forma al final del texto están todas las clases y archivos del ejemplo, para verlos o descargarlos.
We always need to use some type of security to ensure our end, safety, despite the redundancy of your data. That's why every time we use a login or some text that needs some kind of obfuscation, we turn to those who are encryption algorithms.

Flex is a library for a simple way to encrypt and provides several algorithms, thus achieving our goal, to make sure that no one has the key or text traveling through the network and can read or at least read it immediately.

Here is the link to get off the library for ActionScript, as3corelib Link .

I will leave the most important class, so you can see who is implemented and you can see all the classes and download them at the end of this post.
package com.developyourdream.vo
{
 import com.adobe.crypto.MD5;
 import com.adobe.crypto.SHA1;
 import com.adobe.crypto.SHA224;
 import com.adobe.crypto.SHA256;
 import com.adobe.crypto.WSSEUsernameToken;
 import flash.utils.ByteArray;
[Bindable]
 public class LoginVO
 {
  public function LoginVO()
  {
  }
  private var _username:String;
  private var _password:String;
  private var _cryptoDetail:PasswordVO;
  private var _passwordByteArray:ByteArray;
  
  public function get username():String{
   return _username;
  }
  public function set username(value:String):void{
   _username = value;
  }
  public function get cryptoDetail():PasswordVO{
   return _cryptoDetail;
  }
  public function get password():String{
   return _password;
  }
  public function set password(value:String):void{
   _password = value;
   
   _cryptoDetail = new PasswordVO;
   
   _passwordByteArray = byteArrayTrasform(value);
   
   _cryptoDetail.originalByteArrayPassword = byteArrayToString(_passwordByteArray);
   
   _cryptoDetail.md5   = MD5.hash(_password);
   
   _cryptoDetail.sha1   = SHA1.hash(_password); 
   _cryptoDetail.sha1_base64 = SHA1.hashToBase64(_password); 
   _cryptoDetail.sha1_Bytes = SHA1.hashBytes(_passwordByteArray);
   
   _cryptoDetail.sha224  = SHA224.hash(_password); 
   _cryptoDetail.sha224_base64 = SHA224.hashToBase64(_password); 
   _cryptoDetail.sha224_Bytes = SHA224.hashBytes(_passwordByteArray);
   
   _cryptoDetail.sha256  = SHA256.hash(_password); 
   _cryptoDetail.sha256_base64 = SHA256.hashToBase64(_password); 
   _cryptoDetail.sha256_Bytes = SHA256.hashBytes(_passwordByteArray);
   
   _cryptoDetail.token = WSSEUsernameToken.getUsernameToken(_username,_password);
   
  }
  /*OTHER FUNCTIONS*/
  private function byteArrayTrasform(value:String):ByteArray
  {
   var _auxByteArray:ByteArray;
   _auxByteArray = new ByteArray();
   _auxByteArray.writeMultiByte(value,"utf-8");
   return _auxByteArray;
  }
  private function byteArrayToString(byteArray:ByteArray):String
  {
   byteArray.position = 0;
   var str:String = "";
   while(byteArray.position != byteArray.length - 1)
   {
    str += byteArray.readByte().toString(16).toUpperCase()+" ";
   }
   return str;
  } 
 }
}

Ejemplo:
Example:
Ver y Descargar Archivo:
View Source and Download Files: