sábado, abril 26, 2014

A propósito de una API de c++

Hace algunos días me pidieron que estudiara alguna manera de validar que una fotografía cumplía con ciertos requisitos de densidad y medida en pixeles: un requerimiento simple, que exige acceder a metadatos de la imagen. Desde el punto de vista de nuestros modelos de Plex, esto significa usar un API, ya que no existen dentro del conjunto de funciones propias del producto, ni tampoco en ninguno de sus patrones de tecnología, alguna función preelaborada que permita obtener esa información.
Un API es un trozo de código específico de una plataforma que funciona encapsulado: en su interior resuelve una necesidad específica, en este caso, tratar metadatos de una imagen, intercambiando información con el modelo a través de parámetros. Así, el modelo se mantiene a nivel abstracto, y se relaciona con código específico de plataforma a través de un marco de inicialización que resuelve la relación entre el nivel del modelo y el del código encapsulado. El marco de las APIs que Plex maneja es relativo a plataformas específicas: c++ para clientes Windows de código no administrado (en términos del marco .NET) u ODBC, un motor de VBscript incrustado para VBscript, c# para  .NET, y java o RPG para las variantes respectivas. Ya hace tiempo existe en la comunidad de Plex el estilo de definir un API de tal forma que responda a múltiples plataformas, por medio de metaoperaciones, que permitan intercambiar los parámetros entre el modelo y el código encapsulado, que será uno distinto por variante, y se resolverá en tiempo de compìlación según metaoperaciones que interroguen al modelo acerca de qué lenguaje se ha configurado. De esta forma, un sólo objeto API permite representar en un modelo su solución para tantas variantes como sea necesario y posible.
¿Estas son las únicas variantes posibles? Aunque hasta donde conozco, nadie lo ha intentado, existe una posibilidad de "sobrecargar" Plex para agregar APIs de otra plataforma o lenguaje: Plex sigue el modelo .COM, y permite importar un componente, y utilizar sus métodos y variables públicas como parte del modelo. Es entonces posible añadir transformaciones que habiliten otra variante, al menos al nivel puntual de una API. Utilizando elementos similares por otra vía, Websydian primero, y Webclient después, permitieron agregar capas de arquitectura web completas a un modelo de Plex.

Pero ahora, volviendo al pedido de lectura de metadatos de imágenes...Primero, restringimos el alcance del API a una aplicada a un modelo WinC, es decir, uno de plataforma Windows de modelo Win32, al menos para su primera versión: el horizonte de aplicación abarca por lo menos los próximos tres años. No está claro si en el futuro la aplicación continuará sobre Windows o Java, y en el primer caso, si sobre Win32 o WinRT. Digamos de todas formas que WinRT todavía no está soportado sobre Plex, lo que estrechaba el marco de posibilidades. Ahora bien, ¿qué alternativas hay disponibles para trabajar con imagenes escritas en c++ o c? En una primera revisión, encontré varias alternativas; Adobe XMP Toolkit, ExifTool (en modo de línea de comandos), Exiv2, y especialmente el Windows Imaging Component, o el objeto PropertyItem (en System.Drawing.Imaging Namespace) , ambos de Microsoft. Con algo de entusiasmo, comencé pesando las posibilidades de estas dos alternativas de Microsoft. Trabajando con Visual Studio y sobre una plataforma Windows ¿qué alternativa más "natural" puede considerarse que la del propietario de la plataforma? Sin embargo, luego de revisar la documentación (algo escasa en general), encuentré su uso demasiado exigente para el caso que debíamos atender: En primer lugar, la clase PropertyItem parecía más simple y directa de usar (a pesar de que tampoco estamos hablando de pocas líneas de código), pero aparecieron un par de observaciones (1, 2) que es necesario tener en cuenta, sin hablar de las posibles dependencias de versión del framework .NET. En el caso de WIC, examinando la documentación claramente marchabamos a matar moscas a cañonazos. Tanto por la complejidad relativa al objetivo a resolver, como también por la ambigua situación de evolución y deriva de .NET, Win32 y WinRT,decidí volver a evaluar otras opciones de código abierto, y finalmente adopté Exiv2, pero aún de una manera más simple: no recurriendo a la librería c++, sino usando el comando de consola exiv2, que permite acceder a la mayoría de los estándares de metadata...sin necesidad de asegurarse de que estén instalados los codecs adecuados...
En fin, resuelta la estrategia, en un par de días cerramos el problema con un código simple, reducido, y fácilmente ampliable a la obtención de otros atributos. En una situación de transición de la plataforma de Windows como la actual, es preferible quedar libre de dependencias y compromisos, si es posible. En tanto, ActiveX, VBA, VB for Office, c++ y en alguna medida .NET y .COM, atraviesan la borrosa frontera entre Win32, WinRT y otras alternativas que puedan sumarse a "un solo Windows"...

lunes, abril 21, 2014

Migrando a System i 7.1

En un proyecto en el que trabajo, en poco tiempo más (midiendo en meses) migraremos un conjunto de sistemas IBM i (AKA AS/400, iSeries, al menos en su base), de 6.1 a 7.1, mientras que IBM ya anuncia i 7.2 . El cambio no representa  inconvenientes mayores: probablemente no haya demasiado que tocar en aquellas aplicaciones que generamos con Plex, que básicamente no debemos recompilar ni tampoco rehacer código.Únicamente deberíamos asegurarnos de que ningún API usada o procedimiento de lenguaje de control pudiera entrar en conflicto por obsolescencia. De acuerdo a la información adelantada por IBM, los problemas no vendrían por este lado. Es casi seguro que podremos seguir trabajando todas nuestras aplicaciones RPG, sus APIs, y nuestro CLs, sin modificaciones.
En cambio, tenemos asegurado trabajo de revisión con Java, quizá el área de mayores novedades en el software incluído para la versión 7.1, ya que, si consideramos que nos movemos desde 6.1, debemos tener en cuenta que la nueva versión abandona la máquina virtual estándar de Java (esta parte tampoco nos afecta, porque Websphere 7.0 ya la usa), y utiliza sólo la propia de IBM (J9). Esto sí requiere análisis y tests para aquellas aplicaciones que no se ejecutan con Websphere.  En el caso del servidor de aplicaciones, que es el que usamos relacionado con Plex, estimo que podremos mantener inicialmente la versión 7 de Websphere, que ejecuta Java 6, pero en algún momento debemos pensar en subir su versión a 8.1, que usa Java 7. Y esto implica que también deberemos planear la migración de Plex a 7.1. No es obligatorio, ya que podríamos mantenernos como hasta ahora, pero debemos pensar que también podemos llegar a estar presionados por los cambios en Windows, de 7 a 8.
A pesar de todos estos movimientos, no es mucho lo que impacta en nuestras aplicaciones, que se mantienen con cierta holgura en estos movimientos de versiones. Más bien, lo que debemos repensar es qué cosas podríamos reenfocar, sacando provecho de las nuevas posibilidades: gran parte de los cambios se manifiestan como extensiones. Mayor es el peligro si habláramos de dependencia de Windows, ya que el paso de 7 a 8 sí apunta a un cambio de arquitectura mayor. Pero de estos inconvenientes podemos hablar mejor en otro momento.
Dany Burger, en The Four Hundered, dedica un interesante artículo a los problemas de migración de i 6.x a i 7.1 y 7.2, que me motivaron a chequear nuestros propios riesgos a futuro. Como en otras ocasiones, es de reconocer y agradecer la política de cambio y migración de IBM y el iSeries (o como lo llames), que difícilmente te deje en una situación de callejón sin salida con una aplicación antigua: se puede evolucionar gradualmente sin tirar lo que ya está hecho.

domingo, abril 06, 2014

Incorporando recursos móviles al horizonte de trabajo

Este fin de semana leí un artículo especialmente interesante de Matt Baxter-Reynolds en ZDNet, que quise conservar aquí, para uso posterior, por sus sugerencias en el enfoque a la hora de definir qué devendrá aplicación móvil, y qué no, o no tendrá relevancia.
Do you remember a time before we used to talk about "mobile"?
In reality, it's only been a few years. You don't actually have to go back that far to find a world where mobile was unusual, where the only way normal people got the internet was through a PC that was physically wired into the network. First we got Wi-Fi, then we got cellular data, but mobile was always distinct, always secondary.
Now we're operating in a world where there is no distinction. Plus it's not like mobile has "taken over" and normal desktop computing is in second place. What we're seeing is a world where a connected device is a connected device, regardless of its classification.

Differences

The difference between a non-mobile device and a mobile device is that a mobile device is one where it can be used whilst you're moving, whereas a non-mobile device is one that can be moved from place to place. This is primarily about utility. When you need to interact with a non-mobile device, you have to go through a set-up process, sit down in front of it, and start your activity.
What people want when they engage with mobile is to be able to access their data, and reach out to people in their social networks, without having to go through this specialised set-up process.
If we're particularly looking at enterprise use, a user may choose to use mobile over non-mobile for a number of reasons. For one, it may not be easy to set-up a laptop where they happen to be in space and time -- e.g. a parent dropping their kids off to school replies to an email whilst waiting around. Or, it may just be more of a hassle than what it's worth -- e.g. having a quick look at whereabouts in the city their meeting the next day happens to be during an ad break in a favourite TV show.
In these examples, there is no clear delineation between a "mobile" and "non-mobile" task. What we're looking at is choice in how something is done. The fact that we now use operating systems and form factors that are new is simply an accident. Has Microsoft moved faster into the mobile space, beating Apple and Google, we would have been using Windows as a primary mobile OS too, rather than what we have today where we have this split of operating system use that follows the split of form factor.

Unhelpful

In business what we have today is that people tend to say "We need a Mobile strategy". In that statement, "Mobile" is very much though of as having an upper-case "M".
This is an unhelpful approach. Thinking about "Mobile" (as opposed to "mobile") tends to focus the discussion around technology, whereas it's important when thinking about post-PC to think about the sociological angles first.
There's all sorts of reasons why it's helpful for certain types of professionals to be able to reply to emails whilst dropping their kids off at school. This is after all why BlackBerry became a successful business. The most obvious one is that it allows the user to do something then and there, getting it off their radar, rather than having these trivial "I wonder if…" and "I need to…" tasks gumming up their brains.
BlackBerry is very interesting here because within the enterprise they solved this problem ahead of anyone. BlackBerry invented business-oriented post-PC way before Apple did, simply through this ability to open up access to company systems to certain types of individuals. Specifically, the company system that they opened up was email, seconded by scheduling, and contacts.
What BlackBerry actually did was hit the only really obvious part of "mobile" when it comes to enterprise. If you talk to people who want to take advantage of BYOD, or want their employer to buy them a smartphone and/or tablet, as soon as you have email, scheduling, contacts, and web browsing covered, you have largely done everything that the user wants.
This is part of where thinking about "Mobile" gets stuck. Within the business sphere, there isn't really that much to do other than those basic things. If you focus on "Mobile", all you do is fiddle around the edge of that basic problem.

Alternatives

So if you're a CTO/CIO and you're in the mood for invention and innovation in the mobile space, what do you do?
If you think about "Mobile" as opposed to "mobile", you're going to look at what can be done with the technology. Moreover, you're going to look at what is safe (i.e. what your peers manage to make work), and you're going to respond to what you're being asked (e.g. "I want to reply to emails when I'm dropping the kids off at school.")
If you think about "mobile" as opposed to "Mobile", you're still in danger, as you'll be putting the cart before the horse. "Which opportunities can be delivered best through a smartphone?" is something you may ask.
Asking the question in that way puts up an artificial technical barrier to what you're trying to do. The end user doesn't care if they are mobile or not mobile when they're using what you're provided. What they do care about is that it becomes a tool that fits in with everything else that they have going on.
Perhaps one day that tool is one that they'll want to use in the office at a PC. The next day they might want to use it on a laptop at home. The day after they'll want to access it via their smartphone on a train.
Another danger here is in how businesses buy systems. Going out into the market and asking for "mobile" narrows your options. What users want is systems that are flexible and allow anytime, anyplace, anywhere working. What you need to ask for is systems that offer that flexibility.
The trick with this is to simply ignore "mobile" as a thing -- simply don't think of mobile devices as anything special.
After all, there is no "mobile".