Silverlight: Universal GUI toolkit

The most important piece of news from last week's PDC was Microsoft's decision to turn Silverlight into the universal platform for building cross platform applications.

The upcoming version of Silverlight will no longer be a Web-only technology. It will now be possible to build full desktop applications with Silverlight.

Desktop Silverlight applications differ from the standard Silverlight in a few ways:

  • Full access to the host file system, like any other .NET application would have.

  • None of the socket connectivity limitations that are present on the sandboxed versioned of Silverlight. Full network access (we should build a MonoTorrent UI for it!)

  • Built-in Notifications API to show up bubbles to the user when they need to interact with the application.


Although Moonlight has supported this mode of operation since day one, turning this into a standard way to develop applications was going to take a long time. We would have needed to port Moonlight to Windows and OSX and then we would have to bootstrap the ecosystem of "Silverlight+" applications.

But having Microsoft stand behind this new model will open the gates to a whole new class of desktop applications for the desktop. The ones that I was dreaming about just two weeks ago.

This was a big surprise for everyone. For years folks have been asking Microsoft to give Silverlight this capability to build desktop apps and to compete with Air and it is now finally here. This is a case of doing the right thing for users and developers.

Desktop Tools in Silverlight?


Now that this technology is available, perhaps it is a good time to start a movement to create a suite of Silverlight-based desktop applications.

The benefits to me are many:

  • .NET applications that actually look good. In the past your choices were basically of Gtk# or Winforms, neither one really designed for this graphic-designer driven world.

  • We can join forces with Windows/MacOS developers to create the next generation of desktop applications.

  • Developers can tap into the large ecosystem of third-party controls that exists for Silverlight.


For the Moonlight team, this means that there is a lot of work ahead of us to bring every Silverlight 3 and 4 feature. I think I speak for the whole Mono team when I say that this is exciting, fascinating, challenging and feels like we just drank a huge energy boost drink.

If you want to help, come join us in the #moonlight or #mono channels on the IRC server at irc.gnome.org.

Silverlight 4


There are many other great features in Silverlight 4, but none as important as Silverlight becoming a universal runtime for the CLR. This is a revolution.

If you are curious about all the new tactical features of the revolution, check Tim's Complete Guide to the new Silverlight Features.

If you have the time, watch Scott's keynote's presentation where he introduced the new features (he starts at 1:02). I loved the use of HTML as a Silverlight brush (paint with HTML and even Flash). If you have time, these are some great sessions on Silverlight:

Invocar funciones PHP desde Flex con AMFPHP

Adobe Flex es un framework de desarrollo que nos permite crear rápida y facilmente aplicaciones RIA (Aplicaciones de Internet Enriquecidas), basado en la plataforma Flashcombinando el lenguaje de marcas MXML ActionScript. También, gracias a su entorno de desarrollo se simplifica el desarrollo de aplicaciones AIR.


En esta oportunidad quiero explicar cómo hacer uso de Flex para invocar funciones hechas enPHP (no entraré en detalles, pues no conozco a fondo ActionScript). Una forma de hacerlo es mediante AMFPHP. Pero ¿qué es AMFPHP? Es un RPC (Llamada a Procedimientos Remotos) que nos permite comunicar datos de aplicaciones-funciones entre el cliente (JavaScript, Flash, Flex, etc) y servidor (PHP, ASP, JSP, etc). En este caso AMFPHP realiza la comunicación de procesos remotos entre Flash (y por extensión aplicaciones RIA en Flex y AIR) y PHP.


Vamos por paso para la implementación de un proyecto en Flex que llame a funciones en PHP.


1. Descargar y extrae la carpeta amfphp que contiene la siguiente estructura (y para no perderse en el tutorial, colocala en la raíz de tu sitio web de tal forma que quede así:http://localhost/amfphp)



+ ampphp
 
+services
 
+core
 
+browser
 
-gateway.php
 
-globals.php
 
-.htaccess
 
-json.php
 
-xmlrpc.php
 
-phpinfo.php

2. Verificar el funcionamiento del amfphp. Para ello abres tu navegador y escribeshttp://localhost/amfphp/browser. Aparecera una ventana de configuración donde se muestra la ubicación del archivo gateway que actuará como puerta de enlace. En esta ventana solo dale clic en Save.


Podrás apreciar un especie de explorador. En la vista árbol a tu izquierda se mostrarán todas las clases en PHP que podemos usar. Para que una clase aparezca allí debes guardarla en el directorio services.


3. Vamos crear una clase en PHP. Vamos a lista una relación de clientes de una base de datos MySQL. La estructura de la tabla es la siguiente (ingresa un par de registros luego):



CREATE TABLE IF NOT EXISTS `cliente` (
 
`id` tinyint(7) NOT NULL auto_increment,
 
`nombres` varchar(50) NOT NULL,
 
`ciudad` varchar(50) NOT NULL,
 
`sexo` char(1) NOT NULL,
 
`telefono` varchar(10) NOT NULL,
 
`fecha_nacimiento` datetime NOT NULL,
  KEY
`id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

En archivo PHP debe tener el mismo nombre que la clase, en este caso se llama sample.php:



<?php
class sample{
   
function getUsers () {
        $mysql
= mysql_connect(localhost, "root", "");

        mysql_select_db
( "empresa" );

                $Query
= "SELECT * from cliente";
                $Result
= mysql_query( $Query );
               
while ($row = mysql_fetch_object($Result)) {
                        $return
[] = $row;
               
}
               
return( $return );
       
}
}
?>

Volvamos a http://localhost/amfphp/browser y podemos apreciar en la lista de servicios, a la mano izquierda, nuestra clase llamada sample. Si la seleccionamos se muestran sus métodos, en este caso getUsers, y pulsamos el botón call se mostrará el resultado en la parte inferior.


amfphp browser


4. Abrimos Flex (en mi caso Flex Builder 3) y creamos un nuevo proyecto Flex de nombresample.


new project


new project


Configuramos la ruta en nuestro servidor local:


new project


new project


El archivo autogenerado sample.mxml lo dejamos allí por un momento. Ahora vamos agregar un archivo de ActionScript a nuestro proyecto, para ello le damos clic derecho en la carpeta srcy seleccionamos New ActionScript File.


new project


new project


El archivo RemotingConnection.as contiene un clase que llama a una conexión remota especificando la url de ésta.



package {
       
import flash.net.NetConnection;
       
import flash.net.ObjectEncoding;

       
public class RemotingConnection extends NetConnection
       
{
               
public function RemotingConnection( sURL:String )
               
{
                        objectEncoding
= ObjectEncoding.AMF0;
                       
if (sURL) connect( sURL );
               
}

               
public function AppendToGatewayUrl( s : String ) : void
               
{
                       
//
               
}
       
}
}

Ahora el archivo autogenerado sample.mxml, lo reemplazamos por el siguiente contenido:



<?xml version="1.0" encoding="utf-8"?>

       
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns="*" creationComplete="initApplication()">

       
<mx:DataGrid dataProvider="{dataProvider}">
               
<mx:columns>
                               
<mx:DataGridColumn headerText="ID" dataField="id"/>
                               
<mx:DataGridColumn headerText="Nombres" dataField="nombres"/>
                               
<mx:DataGridColumn headerText="Ciudad" dataField="ciudad"/>
                               
<mx:DataGridColumn headerText="Telefono" dataField="telefono"/>
                               
<mx:DataGridColumn headerText="Sexo" dataField="sexo"/>
                               
<mx:DataGridColumn headerText="Fecha Nacimiento" dataField="fecha_nacimiento"/>
                       
</mx:columns>
       
</mx:DataGrid>

       
<mx:Script>
                <![CDATA[
                        [Bindable]
                        public var dataProvider:Array;
                        public var gateway : RemotingConnection;

                        public function initApplication()
                        {
                                gateway = new RemotingConnection( "http://localhost/amfphp/gateway.php" );
                                gateway.call( "sample.getUsers", new Responder(onResult, onFault));
                        }

                        public function onResult( result : Array ) : void
                        {
                                dataProvider = result;
                        }

                        public function onFault( fault : String ) : void
                        {
                                trace( fault );
                        }
                ]]>
       
</mx:Script>

</mx:Application>

Hemos creado un DataGrid para mostrar los datos de la consulta al servidor MySQL. Dentro de las etiquetas <mx:Script/> hacemos uso de ActionScript para llamar a la claseRemotingConnection que creamos anteriormente. La función initApplication() se encarga de conectar con la puerta de enlace: gateway.php, y llama al método getUsers() de la clasesample. La respuesta la recibe la función onResult() que pasa los datos a la variabledataProvider y ésta pasa al DataGrid.


6. Ahora simplemente compilamos el proyecto (Ctrl + F11) y podemos apreciar el resultado en el navegador web.


new project


De esta forma podemos crear aplicaciones web complejas que incluyan inserción y actualización de datos. Pero eso no esto, incluso podemos crear aplicaciones de escritorio gracias a AIR con esta funcionalidad, es decir llamadas a procesos remotos. Les dejo los archivos de este tutorial para que lo prueben en su servidor local.


Lo vi en: Flex and PHP Using AMFPHP