now from home

working from home

Removing Complexity Hosting Static Websites

 The incident

One of my product websites was hit with the Google Viagra Hack. This hack injects different content to your website when is fetched by Google.

It’s subtle because you might not be aware of it for weeks. When you visit your site everything seems fine. If you take a look at your source files, everything is fine. However, when Google crawls your site it only finds Viagra links and related content.

When you google your site, you’ll find that it displays an scary message:

This site may be hacked

And the descriptions altered with medicine ads.

The investigation

Ok, so someone somehow managed to change the content of my website, at least to Google. After the initial panic, I used Google Webmaster Tools to see my website through Google eyes. It was a mess.

I investigate a bit this hack and it seems that it’s just a script that takes advantage of some PHP plugin or misconfiguration. On my website root folder there was an obfuscated PHP files called stats.php.

This website, as many others I have to maintain, are just static content. HTML, CSS and JS client code. Some of these websites are hosted on Dreamhost, together with some old WP blogs and old PHP websites, and they are likely to be the door to this hack.

My resolution: simplify

I’ve been migrating my websites away from WordPress for some months. First I discovered Jekyll but now I’m using Hugo. It just feels right to have my content as version controlled files instead of having a full PHP framework running including a MySQL database.

In my view the next logical step is to get away from traditional hosting all together. There are several alternatives like using Dropbox+Github or using Amazon S3.

I chose the later.

Hosting static websites in Amazon S3

The setup is very simple.

Basically you create a bucket with your website address, put there your files, configure the bucket to serve the website and update DNS records using Amazon Route 53.

Make Vim and command-T Work on Yosemite

The upgrade from Marvericks to Yosemite went smoothly except for one thing: vim is segfaulting every time I use Commant-T

The most common answer is that vim has been compiled with a different ruby version than Command-T. However, after being sure to recompile Command-T the problem was still there.

Turns out that I had Command-T on the vim’s plugin directory. After removing it and cloning it into ~.vim/bundle, and recompiling it with:

ruby extconf.rb

it started working again. Be sure to leave no Commant-T files on the plugin folder. I left commant-t.vim by mistake and even though I was no longer getting SEGFAULTs, command-t was not working properly.

How to Change Network Adapter Order in Windows

One of my applications acts as a TCP/IP server for an external laboratory instrument. In one of my customers, this instrument is directly connected to the PC running my app using a USB to Ethernet dongle.

The problem is that my application is binding to the default ethernet adapter which is a WIFI card.

It took me a while to find out how to change the order of the ethernet adapters. If you do a quick google search, you’ll find that you have to go to:

View network connections > Advanced settings > Change the binding order

However, this did not work for me. My app was still reporting the IP address of the WIFI adapter, even after a system restart.

Deep in a Microsfot KB support article is the solution. You can change a parameter in the adapter called Interface metric. And that worked! I put 3 on the USB converter and 5 on the WIFI adapter, and voilà!

 Click Start, click Run, type ncpa.cpl , and then click OK.

 The available connections appear in the LAN and High-Speed Internet section of
 the Network Connections window.

 Right-click the network adapter that you want to change, click Properties, and
 then click the General tab.

 In the This connection uses the following items box, select Internet Protocol
 (TCP/IP). Then, click Properties.

 In the Internet Protocol (TCP/IP) Properties dialog box, click the General
 tab, and then click Advanced.

 On the IP Settings tab, click to clear the Automatic metric check box. Then,
 type a value in the Interface metric box.

Upgrading Passenger and Nginx

I deploy code to production servers on a daily basis, however when I have to upgrade system components I feel uneasy.

I had a couple of servers still running an ancient version of nginx, 1.2.0 or somethig like that. It was upgrade time…

Better be safe than sorry

Instead of go ahead and update directly on the production machine, I launch a new linode and restore the last backup to it. This way I can see if there will be any problem with the upgrading process.

Passenger makes installing / updating nginx easy

The process can’t get easier than this:

gem update passenger
rvmsudo passenger-install-nginx-module

I choose to let it download and install nginx itself.

The last step is to edit your nginx.conf and update the passenger root folder.

Adding SPDY support

If you want to activate additional modules other than the defaults, you need to download the nginx source code first. Again the install is very simple thanks to passenger.

First download and untar the nginx source code:

tar xvzf nginx-1.4.1.tar.gz


rvmsudo passenger-install-nginx-module

This time you want to choose option 2. You simply have to type where the nginx source code is located and pass addtional compile options.

In my case to activate the SPDY module: –with-http_spdy_module

Localhost Subdomains

I maintain a multitenant rails application where each customer (tenant) gets its own subdomain.

In order to develop and test this application on my development computer I use the domain which uses a DNS trick, this domains and all its subdomains point to localhost.

This way I can type and it just works. No need to touch anything on your computer.

Today I receive a bug report that only happens on IE < 10 (oh well!). I usually just use a Windows machine and type my dev machine IP on the address bar, however this time I need to access a subdomain on my dev machine so 192.168.1.XXX:3000 was not going to work.

The solution was to edit the file \Windows\system32\drivers\etc\hosts and add the following entry:

This way now I can type on the Windows machine and get it routed to my dev box with the subdomain name.

How to Resize a VirtualBox Ubuntu Guest Partition

Usually I rarely use more than 20GB on my Linux virtual machine. However I set up Dropbox and, once it synced, I had only a few megabytes left on my VM.

These are the steps I’ve followed to resize the VM partition:

Make a backup of your VM

You can potentially destroy your VM so better safe than sorry. Make a copy of your VM.

Delete snapshots

If you have snapshots you must delete them first so changes are merged on the main disk file.

Resize the virtual disk

Run the following command:

VBoxManage.exe modifyhd ubuntu.vdi –-resize 40000

Download GParted Live CD/USB image and use it to boot the VM

You need to download GParted Once downloaded boot your VM with the GParted image.

Resize the partition

If the swap partition happens to be between the primary partition and the unallocated space, you need to remove it. Resize the primary partition and then create the swap partition back.

Be sure to write down the size of the swap partition before delete it and leave that space unallocated when resizing the primary partition.

Once you are happy with changes click apply and exit GParted. Remove it from the boot sequence and restart the VM. Enjoy the extra space.

Portabilidad Movistar-Vodafone + iPhone 5

No soy de los que cambian de móvil cada año. De hecho, el contrato de permanencia que firmé con Movistar hace unos años finalizó en 2011. Y aún seguiría con el mismo iPhone 3GS que adquirí entonces si no fuera porque lo perdí hace 1 mes (historia que no viene al caso).

Desde que lo perdí, he estado usando un iPhone 4 prestado. Comparado con mi 3GS se nota sobre todo la mayor resolución de la pantalla y que funciona algo más rápido. Sin embargo, hay cosas que eran mejor en el 3GS. La batería dura menos, el botón de inicio falla en ocasiones, la señal de WIFI es más débil y sobre todo tiene menos cobertura.

La cobertuta de Movistar no es muy buena en mi zona, ya con el 3GS tenía en ocasiones problemas, pero con el iPhone 4 directamente es imposible trabajar. Prácticamente ninguna llamada me entra directamente y los avisos de llamada llegan tarde. Para hacer una llamada tengo que esperar a ver 3 barras, estando la mayor parte del tiempo con tan solo 2.

Curiosamente la cobertura de Vodafone es excelente en esta zona. Así que decidí cambiar de compañía tras más de 3 años con Movistar.

Aprovechando el cambio de compañía y puesto que el teléfono que tengo ahora no es realmente mío, cogeré el iPhone 5.

Esta ha sido el proceso:

13/02: Hago el pedido en la web de Vodafone. El proceso es bastante claro. Elijo el plan Red Pro y un iPhone 5 32GB. Sale por 59€/mes + 176€ por el teléfono. 24 meses de permanencia. Envío la documentación que piden por email en ese mismo momento para acelerar el proceso.

14/02: Me llaman de Vodafone para formalizar el contrato. El proceso lleva unos 20 minutos pues me vuelven a pedir todos los datos que metí en el pedido. Vuelvo a enviar la documentación, esta vez por fax porque me dicen que suele ser más rápido!! En serio??

19/02: Sin noticias. Por curiosidad me meto en la página de vodafona a ver si hay alguna manera de ver el estado de mi pedido/portabilidad. Si que la hay. Sin embargo no es muy informativa. Estado del
pedido Decido llamar no sea que haya algún problema. Es un 902 de pago; mala forma de tratar a los clientes. Me atiende una señorita en España, tras pedirme el DNI, me dice que:

Hay algún problema con nuestros sistemas informáticos y no podemos saber el estado de su pedido. Llame dentro de 30 minutos.

¿Cuántas veces habré oído esa excusa? A las 2 horas vuelvo a llamar. De nuevo me atienden de forma local. Esta vez sí me dicen que hay un problema. Por lo visto falta la parte de atrás del DNI, la cual envié junto al resto de documentación. Le pregunto que si no llego a llamar, ¿cuánto tiempo habría estado parado el pedido? En su defensa hay que reconocer que sólo han pasado 4 días laborables.

Vuevo a enviar la documentación.

21/02: Sin cambios en la página de seguimiento del pedido. Llamo de nuevo al 902 y la persona que me atiende me dice que ya disponen de toda la documentación necesaria y se disponen a iniciar el proceso. 4 o 5 días más.

26/02: Vuelvo a llamar tras la falta de información en la página de seguimiento del pedido / portabilidad. Me dicen que ya está iniciado el trámite y que mañana o pasado me debería llamar Movistar para confirmar la portabilidad. Me asegura que como mucho lunes o martes debería estar ya funcionando con Vodafone.

28/02: Parece que ya hay movimiento. Recibo un SMS diciendo que la portabilidad se realizará en la madrugada del día 6 de marzo. La página de seguimiento de Vodafone sin cambios. Más tarde recibo una llamada de Movistar intentando hacerme una contraoferta. Le digo que lo siento pero que es por un problema de falta de cobertura en mi zona. Vodafone me manda un SMS dicicendo que el pedido ha sido enviado. Hay página de seguimiento del pedido. Sin embargo, la página de seguimiento original sigue diciendo que no se ha iniciado ningún trámite.

01/03: Llega el teléfono y la tarjeta SIM. Sólo queda el paso de hacer efectiva la portabilidad.

06/03: Se completa la migración y por fin puedo empezar a usar el móvil con Vodafone.


Me ha gustado bastante la página de Vodafone para realizar el pedido. Sin embargo la página de seguimiento del pedido no funciona en absoluto. Deberían deshabilitarla pues lo único que hace es preocupar al cliente y forzarle a llamar.

Tampoco me ha gustado tener que llamar a un 902 de pago para saber el estado de la portabilidad/pedido.

Muy extraño que recomienden mandar la documentación por fax en lugar de por email. Por fax!!

Tres semanas para tramitar todo esto… excesivo!

Por lo menos parece que he solucionado mis problemas de cobertura.

Building a VM to Convert Documents to PDF


To have a machine which I can throw ODT files at and get back PDF documents.

(It will work with all OpenOffice supported document types: Word, RTF, PPT, …)

Quick start

Following these steps you should get the conversion working on a clean machine. I’ve used Ubuntu 12.10 minimal server install.

sudo apt-get install
sudo apt-get install unoconv
unoconv --listener &
unoconv -f pdf test.odt

Once we get the converter working, let’s wrap this functionality in a rack application using Sinatra.

You can follow this guide, to install RVM, Ruby, passenger and nginx.

Minimal Sinatra app to convert the files to PDF

The following code expects you to POST a file. It saves it in a temp folder, converts it using unoconv and sends you the resulting PDF file.

require 'sinatra'

TMP_PATH = 'tmp/'

post '/' do
 source_file_contents = params[:file][:tempfile].read
 source_filename = get_source_filename(params[:file][:filename])
 output_filename = source_filename + '.pdf', 'w') { |f| f.write(source_file_contents) }

 %x[unoconv -f pdf #{source_filename}]

def get_source_filename(base)
 filename = params[:file][:filename].split('.')[0]
 filename = filename + '_' +
 File.join(TMP_PATH, filename)

You will also need a config file for the rack application:
require 'sinatra'
require 'converter'

run Sinatra::Application

Now we just need to configure nginx to serve our sinatra app.

  server {
    listen              80;
    server_name         localhost;
    passenger_enabled   on;
    root                /home/jose/converter/public;

This is the project folder structure:

project structure
|-- converter.rb
|-- public
`-- tmp

Testing from the command line

Now from other computer you can test the conversor using:

curl -X POST -F file=@test.odt > tmp.pdf

Change the parameters to suit your environment, but that should convert test.odt file to PDF and put the results on tmp.pdf.

What’s next

This is just a proof of concept. The Sinatra app is doing the absolute minimun to get the conversion. It’s not cleaning temporal files for example.

Also the VM is not configured to autolaunch the unoconv listener, nor monitor its status, etc.

.NET 4.0 on Windows XP SP2: Yes You Can

Quick answer

You can install .NET 4.0 on Windows XP SP2 machines and run your winforms applications with no apparent problems. Be aware that it is not a supported scenario but if you don’t have any other option you can definitely try it.


Why I’m moving to .NET 4.0

My main product is a Winforms application that runs on .NET 2.0. I’ve resisted the temptation to upgrade to newer framework versions because it’s not easy to ask or convince customers to install additional libraries even if they come from Windows Update- Also, I’ve personally seen many customers still running my app on Windows XP SP2 machines which .NET 4.0 doesn’t support, at least officially.

This app also uses SQL Server 2005 Express as its backend.

Soon, some of my bigger customers will need to upgrade to SQL Server Standard. The easy path would be to install SQL Server 2005 Standard but I don’t think that it’s even possible now. SQL Server 2005 is three major versions behind.

So for those customers is going to be SQL Server 2012. This shouldn’t be a problem as the code should work without changes just fine right?

And it does indeed. Unfortunately, my application uses SMO to create and update the database, to backup and restore data among other fancy things and that didn’t work.

So the first error when I launch my app against SQL Server 2012 is:


 This SQL Server version (11.0) is not supported. (Microsoft.SqlServer.ConnectionInfo)

Program Location:

   at Microsoft.SqlServer.Management.Common.ConnectionManager.CheckServerVersion(ServerVersion version)
   at Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
   at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()

Makes sense, as I’m using the SQL Server 2005 SMO assemblies. I just need to change those assemblies with the 2012 (v. 11) assemblies and I’m ready to go. But that doesn’t work because the new assemblies use .NET 4.0.

So, finally I have a good justification to move my application from .NET 2.0 to .NET 4.0. I updated all the projects to target .NET4 and run it on my development machine. It crashed with this exception because my app is using third party libraries targeting .NET 2.0.

Mixed mode assembly is built against version 'v2.0.50727' of the runtime 
and cannot be loaded in the 4.0 runtime without additional configuration information.

To solve this I had to add this to my app config file.

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>

Installing .NET 4.0 on Windows XP SP2

After installing a Windows XP SP2 virtual machine, I grabbed the .NET 4.0 web installer and fire it up.

It complained about Windows Installer 3.1 not being present. No problem, I installed it and tried again. This time it complained about Windows Image component not being present on the system. I installed that and tried once more:

Installing Client Profile…
Installing .NET 4 Extended…
Installation complete!

No errors.

Finally, the moment of truth. I launched my application and… everything run just fine. I’m still testing it but I’m not experiencing any problems so far.

So, yes, you can install .NET 4 on Windows XP SP2 and run .NET4 applications. At least Winforms applications. Perhaps WPF or ASP.NET applications crash as soon as you run it but for now, my winforms app is doing fine.

MSBuild: Add Git Commit Hash to AssemblyInfo

The goal is to automatically generate the AssemblyInfo.cs file every time I build my project. I also want to add the current git commit hash as the last part of the assembly version number.

If you spend some time googling around, you’ll find that there are various ways to accomplish this. This is how I do it, step by step:

Install MSBuild Community Tasks

Using nuget this is extremely simple. Open the nuget console and type:

Install-Package MSBuildTasks

Edit your project file and add a new target


<Target Name="Version">
    <GitVersion LocalPath="$(MSBuildProjectDirectory)">
        <Output TaskParameter="CommitHash" PropertyName="Revision" />
        AssemblyFileVersion="$(Major).$(Minor).$(Build)" />

Update the main Project tag to execute the new Version target before Build.

<Project ToolsVersion="4.0" DefaultTargets="Version;Build"

Note that the $(Revision) property, which holds the git commit hash value, is not included in the regular AssemblyVersion or AssemblyFileVersion attributes. The reason is because .NET expects here a number (UInt16) and if we put here a hash it will fail to compile. We use instead the attribute AssemblyInformationalVersion which allows us to put anything we want.

Display the full version in your application

Having access to the exact commit your application is running is invaluable. I display the full version including the commit hash on the About form of my applications. Also, it’s included in the automatic error reports.