Archive for development

Testing COM1 ports using a virtual machine and putty

A few days ago a friend of mine asked me a few questions about how to test a COM1 device. The question sounds simple but think about that, sometimes you don’t have the needed COM1 device to test or your computer doesn’t have a COM1 port at all (for example, a laptop).

I think this is the kind of job for a Virtual Machine… Let’s try.

We would need a few things:

The secret is to redirect the COM1 port from the virtual machine to a file (possible in VMWare) or a named pipe, for starters, a named pipe is an IPC mechanism for process intercommunication.

In the virtual machine settings add a new hardware device and then select Serial Port, Add to named pipe, Finish. Write somewhere the name of the named pipe, in my case would be \.\pipe\com_1

com_port_named_pipe

Now, just for this experiment, I will use putty in the virtual machine to connect to COM1 and in my guest to connect to the named pipe, in that way I will send messages from the virtual machine to COM1 (as any other application would do) and I would be able to receive those messages in the guest through putty, and of course I can answer back from the guest.

In your putty host session remember to select “serial” as the connection type and instead of COM1 select the named pipe created by vmware

putty_guest

In the putty guest session everything is normal, just select “serial” and the expected COM* port, in my case would be COM2:

putty_guest_001

Putty attention in vmware notification icons, even when your named pipe is “com_1” could be possible that in your virtual machine that virtual port is COM2 (not COM1 as you would expect).

virtual_session

Now when I type “hello” in my virtual machine putty instance it will echo in the host putty session and the same backwards. Now, the question is simple, how do I emulate correctly my weird device?

Well, a nice and easy way would be to “record” a common communication session between your device and a machine with a COM1 installed, and then “replay” that session back in your virtual environment using putty or a home made program. You know what, I found a program to do exactly that in CodeProject (Application to Debug Serial Port communication and Basic Serial Port Listening Application), go, give a try =)

I hope this would help you someway my friend.

Proxima VAN, HTML5 para los no iniciados y curiosos

Este sabado 17 de diciembre tendre el placer de compartir con la comunidad de Alt.Net Hispano el codiciado tema “HTML5 para los no iniciados”, si, eso que esta sonando por todos lados acerca de HTML5, que tan raro es? como se come? me curara la caries? Tantas preguntas, tanto material.

HTML5 es muchisimo mas que un estandar, mucho mas que un simple buzz, va bastante mas alla de un simple lenguaje de markup. Tratare de explicar HTML5 desde el punto de vista de un desarrollador web, especialmente que implica para un developer de ASP.NET.

El evento pueden encontrarlo en el link de Google Calendar, no olviden hacer la transformacion en su huso horario.

JustCode is not loading in Visual Studio 2011

Telerik’s JustCode it’s an awesome product, it’s a very lightweight extension that may lack some features (sorry, I won’t mention names) but it does its job, and that’s good. Almost a month ago Telerik announced JustCode support for Visual Studio 2011, that’s awesome, specially when I decided to try out Visual Studio 2011 in a pristine installation inside a virtual machine (and yeah, I know other extensions already announced the same).

installer

I downloaded the JustCode internal build and the installer correctly detected my Visual Studio 2011 installation, sweet, everything finished without any problem. Then when I started Visual Studio 2011 I realized JustCode didn’t load… and all what I get it’s a very verbose exception in the JustCode’s output window:

ERROR 2011-10-23 00:23:38.842 :  [HResult: 80131602]
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at System.ComponentModel.Composition.Hosting.AssemblyCatalog.get_InnerCatalog()
[and a lot of more lines...]

I submitted some bug tickets, write to some Telerik’s developers but no right answers, you know, the usual.

Well, I decided to see what’s happened, so I did what every other developer would do, attach your debugger to Visual Studio and then found the issue. JustCode is trying to load the assembly Microsoft.VisualStudio.CSharp.Services.Language, Version=10.0.0.0 but in a machine without Visual Studio 2010 this assembly didn’t exist, it’s unique of a Visual Studio 2010 installation. Of course, I’m using a Virtual Machine snapshot, I don’t have a previous version installed. The assembly present in my VS2011 installation is Version=11.0.0.0.

The easy way to fix it? Go to a Visual Studio 2010 installation, copy the assembly Microsoft.VisualStudio.CSharp.Services.Language.dll from the Common7 directory and paste into your Telerik’s JustCode directory, that’s all, JustCode now it’s going to load. Maybe this would cause some other problems, but come on, it was my first attempt! =)

Probably a better way to fix it would be using assembly binding redirection, or taking care of the fact that maybe a previous installation it’s not present maybe in the installation process. I’m just saying!

Note for developers in general: it’s a good idea to test your installation in a pristine installation before release it to the wild, just to see what’s happening, you know, just in case =)

El espejismo de la separacion por capas, toma dos

app_3Hace varios meses escribí un blog post (que quise luego transformar en serie y como cosa rara en mi por tiempo nunca llegue a continuarlo) en el que indicaba mi falta de amor a la palabra “capas”….

El concepto de “capas” o “layers” me parece desde unos años para acá tan ortodoxo, viejo, fuera de lugar, obsoleto, mal aplicado, afuera totalmente de contexto. La idea de capas tenía mucho sentido hace décadas atrás (tampoco décadas pero fue hace tiempo) cuando los programadores cavernícolas (en los cuales me incluyo yo picando piedra) teníamos que depender fuertemente en la base de datos, hacíamos las consultas en plano SQL, insertábamos directamente en plano SQL, y si mi DB me la movían literalmente movían mi aplicación.

Esto tenía todo el sentido del mundo en nuestras aplicaciones no tan complejas y sin mucha orientación lógica que hacíamos en aplicaciones desktops o web, o sea, en vez de escribir cientos de líneas SQL esparcidas por doquier en nuestro código de php (por ejemplo), mejor lo abstraíamos todo en un solo lugar donde estaba guardadito nuestro SQL, ahí en su cajita, donde nadie lo tocaba y si alguien lo tocaba era una vez (como que si tocar una consulta no involucrara cambiar algo… silly us). Esto se llevó un paso adelante y en vez de poner consultas como SELECT * FROM [tabla] mejor usamos SP’s, así que cambiamos eso por EXEC usp_MiConsulta, esto dio origen a otro problema, pero vamos a ir al grano primero.

En ese tiempo la gente comenzó a percatarse de algo, si abstraigo las consultas a la DB, luego las llamadas a la DB en otro lado, puedo entonces poner la “lógica” de negocio en otro lado y sobre ella hacer la UI. Esto tenía mucho sentido y asi nació el concepto de “layers”… Tiene sentido, tenía sentido en ese tiempo, teníamos aplicaciones con el “típico” color aqua y un par de botones con iconos de puertas y equis tachadas en primera plana, con una grid para mostrar facturas y un botón donde agregábamos una factura nueva (generalmente con el icono más o con un lapicito que aun no entiendo porque aparecía ahí).

Luego vino la moda SOA (que pareciera nunca acabar) y dijeron, va, ahora en vez de hablar directamente la lógica con la data, vamos a tener alguien en el medio que expone esa data por un servicio. Entonces hablamos de SOA… como ya no eran 3 capas si no 4 o más renombramos el modelo a n-Capas…. y aun me perfora el oído escucharlo….

He visto degeneraciones de este modelo, un “buen” ejemplo son las aplicaciones ejemplo de MS, donde abstraen todo a servicios que al final el mismo objeto desde el comienzo al fin es el mismo. Es increíble pero he visto a desarrolladores veteranos que aun insisten en usar su versión de servicio para exponer todo, pero esa es otra historia…

Nuevamente recalco, eso tenía sentido *en ese tiempo* los ORM’s o no existían o eran sumamente rudimentarios, la mayoría de db devs que habían estaban aún acostumbrados a hacer _todo_ en la DB (no, en serio, una vez vi una app que hasta el proceso de pago de paypal era hecho internamente en la DB), tenía sentido cuando tu aplicacion era la tipica aplicación con botones grandes y background aqua… Tenía sentido cuando decías que abstraías el acceso a datos en una clase que por lo general comenzaba por una pequeña clase con un par de métodos y terminaba como cientos… porque tal cosa como reutilizar el acceso a datos se tornó un santo grial.

Eso no tiene sentido HOY, cuando nuestros objetos son (o deberían ser) ricos en comportamiento, cuando modelamos en base a lo que _va a pasar y hacer nuestra aplicación_ no en cuanto a la data que va a contener la base de datos (puntos extras para el que comprenda la diferencia entre ambos approaches en la oración anterior). No tiene sentido hoy que nuestra “lógica de negocio” realmente puede ser embebida en el objeto del dominio o de negocio, donde hacemos una distinción entre lógica de negocio (o reglas del negocio) y lógica de presentación (que como dice el nombre solamente afecta la vista). No tiene sentido cuando no interactuamos contra solo una base de datos si no contra base de datos, archivos, servicios (y generalmente varios). No tiene sentido porque no le veo ni cara ni cuerpo a tener un ORM (por simple que sea) y envolver las mismas entidades y exponerlas mediante otras entidades que contienen los mismos símbolos, no tiene sentido hablar de capa de acceso a datos ya que tus Objetos de ORM no solamente viven ahí y pueden contener la lógica que tanto necesitas en la “siguiente” capa. No tiene sentido en un mundo donde el programador está acostumbrado (y hasta espera) que la consulta se genere automáticamente mediante Linq, no tiene sentido en un mundo donde ya no escribimos SQL a mano.

¿No te gusta un ORM porque tiene demasiada carga para lo que necesitas? bueno usa un MicroORM… y aun así sigues sin hablar de capa de datos, tal cosa ya no existe. Ni siquiera Microsoft con sus prácticas habla de layers…. Vamos, ahora ni en PHP puedes tener el coraje de decir que tienes que escribir SQL a mano, porque entonces abstraer todo en una “capa”, ¿quieren producir algo de misterio? Traten de preguntarle a un programador de Rails donde está su capa de datos, no existe, ¿porque?… No es necesaria tal separación.

Ahora, lo que si debes distinguir es el concepto de Tiers, una aplicación si va a tener varios Tiers, la base de datos (a menos que sea embebida) vivirá y es por definición un tier, ¿expones servicios? bueno, otro tier mas…. Un tier es una separación física de la cual no puedes deshacerte, una layer es una separación lógica que realmente no tiene sentido en un mundo ágil donde no usamos 6 meses “diseñando” la aplicación.

Algún día ordenare todos mis pensamientos y terminare escribiendo un poco más sobre porque el concepto de layer sigue siendo obsoleto, por lo menos para mí.

NOTA: Este fue un largo correo en la lista de Alt.Net hispano que termino siendo tan largo que llego a ocupar un blog post.

Generating generic delegates with expression trees

A few weeks ago I was working in a patch for an awesome mocking meta framework named mfakes, a very awesome mocking meta-framework based in the spicy Machine Specification BDD testing framework, go, try it, you are going to love it!.

Well, one of the awesome points in mfakes it’s to abstract mocking frameworks, so mfakes provides adapters for popular mocking frameworks like Rhino Mocks, Moq, NSubstitute and FakeItEasy. So instead of thinking which one to use, just concentrate in the test. Simple.

Anyway, there was a feature lacking in mfakes, and as every developer when something it’s lacking a feature you just go ahead and implement it, nothing beats open source. The interesting point was trying to “wrap” different way to interact between every mocking framework, everyone has a different way to see the world, it’s not bad, but it’s different. I found a very interesting problem with FakeItEasy and constructor parameters in a Mock.

In most mocking frameworks there’s an easy way to specify constructor parameters for a mock, in Moq, for example, you just do something like this:

var foo = new Mock<T>("foo", "bar");

// Generate this it's easy, it's just a simple generic type
// with a parameter list

public object CreateFake(Type interfaceType, params object[] args) {
    var closedMockType = typeof(Mock<>).MakeGenericType(interfaceType);
    var objectProperty = closedMockType.GetProperty("Object", closedMockType);
    var instance = (args != null && args.Length > 0)
        ? Activator.CreateInstance(closedMockType, args) : Activator.CreateInstance(closedMockType);
    return objectProperty.GetValue(instance, null);
}

The problem it’s that FakeItEasy it’s magic, and uses a very nice strong typed way to do it

var foo = A.Fake<FooClass>(x =>
    x.WithArgumentsForConstructor(
        new[] object {"foo", "bar"}));
// Another way to do it, more strongly-typed
var foo = A.Fake<FooClass>(x =>
    x.WithArgumentsForConstructor(
        ()=> new FooClass("foo", "bar")));

Well, if you think about that, there’s not a simple way to abstract a non-generic, non-typed expression with a generic, strong-typed, functional expression, well, not a simple way to do it at least you use the expressiveness of binary expression trees. How do we abstract this? well, let’s see the simple expression:

Now, let’s create a function to return that expression based in parameters, let’s abstract everything with the only knowlege of the type and the parameters:

// Transforming this:
var foo = A.Fake<T>(Action<IFakeOptionsBuilder<T>> opts)

// Implies something like this
public static Delegate CreateForType(Type type, object[] args) {
    var optType = typeof(IFakeOptionsBuilder<>).MakeGenericType(new[] { type });
    var actType = typeof(Action<>).MakeGenericType(new[] { optType });

// Now we have the type for the action and the options builder
// Let's use it to create an expression tree!

    var r = Expression.Parameter(optType, "r");
    var method = optType.GetMethod("WithArgumentsForConstructor", new[] { typeof(IEnumerable<object>) });
    var p = Expression.Constant(ctorArgs);
    var call = Expression.Call(r, method, p);
    var lambda = Expression.Lambda(actType, call, new[] { r });
    var exp = lambda.Compile();
}

And well, now that we have the function to call (we generated it), it’s time to create the fake

public object CreateFake(Type type, params object[] args) {
    var closedFakeType = typeof(Fake<>).MakeGenericType(interfaceType);
    var objectProperty = closedFakeType.GetProperty("FakedObject", interfaceType);

    var options = args != null && args.Length > 0
        ? FakeItEasyHelper.CreateForType(interfaceType, args) : null;

    var instance = args != null && args.Length > 0
        ? Activator.CreateInstance(closedFakeType, new object[] {options})
        : Activator.CreateInstance(closedFakeType);

    return objectProperty.GetValue(instance, null);
}

See? that’s the reason because Functional programming it’s so awesome, functions are just another variable, you can generate them, use them, modify them, use them. Next time you have a problem try to think in a functional way, you will see how awesome is!.

More about Expression Trees in the amazing book C# in Depth, Second Edition by John Skeet or go and pick a functional language (like this Programming F#), study it, enjoy it, use it in your favourite non-functional language.

Happy coding!

NOTE: the patch it’s already included in mfakes, no worries!